babylon.2.0-alpha.debug.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array) {
  91. return new Color3(array[0], array[1], array[2]);
  92. };
  93. Color3.FromInts = function (r, g, b) {
  94. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  95. };
  96. Color3.Lerp = function (start, end, amount) {
  97. var r = start.r + ((end.r - start.r) * amount);
  98. var g = start.g + ((end.g - start.g) * amount);
  99. var b = start.b + ((end.b - start.b) * amount);
  100. return new Color3(r, g, b);
  101. };
  102. Color3.Red = function () {
  103. return new Color3(1, 0, 0);
  104. };
  105. Color3.Green = function () {
  106. return new Color3(0, 1, 0);
  107. };
  108. Color3.Blue = function () {
  109. return new Color3(0, 0, 1);
  110. };
  111. Color3.Black = function () {
  112. return new Color3(0, 0, 0);
  113. };
  114. Color3.White = function () {
  115. return new Color3(1, 1, 1);
  116. };
  117. Color3.Purple = function () {
  118. return new Color3(0.5, 0, 0.5);
  119. };
  120. Color3.Magenta = function () {
  121. return new Color3(1, 0, 1);
  122. };
  123. Color3.Yellow = function () {
  124. return new Color3(1, 1, 0);
  125. };
  126. Color3.Gray = function () {
  127. return new Color3(0.5, 0.5, 0.5);
  128. };
  129. return Color3;
  130. })();
  131. BABYLON.Color3 = Color3;
  132. var Color4 = (function () {
  133. function Color4(r, g, b, a) {
  134. this.r = r;
  135. this.g = g;
  136. this.b = b;
  137. this.a = a;
  138. }
  139. // Operators
  140. Color4.prototype.addInPlace = function (right) {
  141. this.r += right.r;
  142. this.g += right.g;
  143. this.b += right.b;
  144. this.a += right.a;
  145. };
  146. Color4.prototype.asArray = function () {
  147. var result = [];
  148. this.toArray(result, 0);
  149. return result;
  150. };
  151. Color4.prototype.toArray = function (array, index) {
  152. if (index === undefined) {
  153. index = 0;
  154. }
  155. array[index] = this.r;
  156. array[index + 1] = this.g;
  157. array[index + 2] = this.b;
  158. array[index + 3] = this.a;
  159. };
  160. Color4.prototype.add = function (right) {
  161. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  162. };
  163. Color4.prototype.subtract = function (right) {
  164. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  165. };
  166. Color4.prototype.subtractToRef = function (right, result) {
  167. result.r = this.r - right.r;
  168. result.g = this.g - right.g;
  169. result.b = this.b - right.b;
  170. result.a = this.a - right.a;
  171. };
  172. Color4.prototype.scale = function (scale) {
  173. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  174. };
  175. Color4.prototype.scaleToRef = function (scale, result) {
  176. result.r = this.r * scale;
  177. result.g = this.g * scale;
  178. result.b = this.b * scale;
  179. result.a = this.a * scale;
  180. };
  181. Color4.prototype.toString = function () {
  182. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  183. };
  184. Color4.prototype.clone = function () {
  185. return new Color4(this.r, this.g, this.b, this.a);
  186. };
  187. // Statics
  188. Color4.Lerp = function (left, right, amount) {
  189. var result = new Color4(0, 0, 0, 0);
  190. Color4.LerpToRef(left, right, amount, result);
  191. return result;
  192. };
  193. Color4.LerpToRef = function (left, right, amount, result) {
  194. result.r = left.r + (right.r - left.r) * amount;
  195. result.g = left.g + (right.g - left.g) * amount;
  196. result.b = left.b + (right.b - left.b) * amount;
  197. result.a = left.a + (right.a - left.a) * amount;
  198. };
  199. Color4.FromArray = function (array, offset) {
  200. if (typeof offset === "undefined") { offset = 0; }
  201. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  202. };
  203. Color4.FromInts = function (r, g, b, a) {
  204. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  205. };
  206. return Color4;
  207. })();
  208. BABYLON.Color4 = Color4;
  209. var Vector2 = (function () {
  210. function Vector2(x, y) {
  211. this.x = x;
  212. this.y = y;
  213. }
  214. Vector2.prototype.toString = function () {
  215. return "{X: " + this.x + " Y:" + this.y + "}";
  216. };
  217. // Operators
  218. Vector2.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. };
  225. Vector2.prototype.asArray = function () {
  226. var result = [];
  227. this.toArray(result, 0);
  228. return result;
  229. };
  230. Vector2.prototype.copyFrom = function (source) {
  231. this.x = source.x;
  232. this.y = source.y;
  233. };
  234. Vector2.prototype.copyFromFloats = function (x, y) {
  235. this.x = x;
  236. this.y = y;
  237. };
  238. Vector2.prototype.add = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.addVector3 = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.subtract = function (otherVector) {
  245. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  246. };
  247. Vector2.prototype.subtractInPlace = function (otherVector) {
  248. this.x -= otherVector.x;
  249. this.y -= otherVector.y;
  250. };
  251. Vector2.prototype.multiplyInPlace = function (otherVector) {
  252. this.x *= otherVector.x;
  253. this.y *= otherVector.y;
  254. };
  255. Vector2.prototype.multiply = function (otherVector) {
  256. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  257. };
  258. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  259. result.x = this.x * otherVector.x;
  260. result.y = this.y * otherVector.y;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. };
  272. Vector2.prototype.negate = function () {
  273. return new Vector2(-this.x, -this.y);
  274. };
  275. Vector2.prototype.scaleInPlace = function (scale) {
  276. this.x *= scale;
  277. this.y *= scale;
  278. return this;
  279. };
  280. Vector2.prototype.scale = function (scale) {
  281. return new Vector2(this.x * scale, this.y * scale);
  282. };
  283. Vector2.prototype.equals = function (otherVector) {
  284. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  285. };
  286. // Properties
  287. Vector2.prototype.length = function () {
  288. return Math.sqrt(this.x * this.x + this.y * this.y);
  289. };
  290. Vector2.prototype.lengthSquared = function () {
  291. return (this.x * this.x + this.y * this.y);
  292. };
  293. // Methods
  294. Vector2.prototype.normalize = function () {
  295. var len = this.length();
  296. if (len === 0)
  297. return this;
  298. var num = 1.0 / len;
  299. this.x *= num;
  300. this.y *= num;
  301. return this;
  302. };
  303. Vector2.prototype.clone = function () {
  304. return new Vector2(this.x, this.y);
  305. };
  306. // Statics
  307. Vector2.Zero = function () {
  308. return new Vector2(0, 0);
  309. };
  310. Vector2.FromArray = function (array, offset) {
  311. if (!offset) {
  312. offset = 0;
  313. }
  314. return new Vector2(array[offset], array[offset + 1]);
  315. };
  316. Vector2.FromArrayToRef = function (array, offset, result) {
  317. result.x = array[offset];
  318. result.y = array[offset + 1];
  319. };
  320. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  321. var squared = amount * amount;
  322. var cubed = amount * squared;
  323. 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));
  324. 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));
  325. return new Vector2(x, y);
  326. };
  327. Vector2.Clamp = function (value, min, max) {
  328. var x = value.x;
  329. x = (x > max.x) ? max.x : x;
  330. x = (x < min.x) ? min.x : x;
  331. var y = value.y;
  332. y = (y > max.y) ? max.y : y;
  333. y = (y < min.y) ? min.y : y;
  334. return new Vector2(x, y);
  335. };
  336. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  337. var squared = amount * amount;
  338. var cubed = amount * squared;
  339. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  340. var part2 = (-2.0 * cubed) + (3.0 * squared);
  341. var part3 = (cubed - (2.0 * squared)) + amount;
  342. var part4 = cubed - squared;
  343. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  344. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  345. return new Vector2(x, y);
  346. };
  347. Vector2.Lerp = function (start, end, amount) {
  348. var x = start.x + ((end.x - start.x) * amount);
  349. var y = start.y + ((end.y - start.y) * amount);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Dot = function (left, right) {
  353. return left.x * right.x + left.y * right.y;
  354. };
  355. Vector2.Normalize = function (vector) {
  356. var newVector = vector.clone();
  357. newVector.normalize();
  358. return newVector;
  359. };
  360. Vector2.Minimize = function (left, right) {
  361. var x = (left.x < right.x) ? left.x : right.x;
  362. var y = (left.y < right.y) ? left.y : right.y;
  363. return new Vector2(x, y);
  364. };
  365. Vector2.Maximize = function (left, right) {
  366. var x = (left.x > right.x) ? left.x : right.x;
  367. var y = (left.y > right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Transform = function (vector, transformation) {
  371. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  372. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Distance = function (value1, value2) {
  376. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  377. };
  378. Vector2.DistanceSquared = function (value1, value2) {
  379. var x = value1.x - value2.x;
  380. var y = value1.y - value2.y;
  381. return (x * x) + (y * y);
  382. };
  383. return Vector2;
  384. })();
  385. BABYLON.Vector2 = Vector2;
  386. var Vector3 = (function () {
  387. function Vector3(x, y, z) {
  388. this.x = x;
  389. this.y = y;
  390. this.z = z;
  391. }
  392. Vector3.prototype.toString = function () {
  393. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  394. };
  395. // Operators
  396. Vector3.prototype.asArray = function () {
  397. var result = [];
  398. this.toArray(result, 0);
  399. return result;
  400. };
  401. Vector3.prototype.toArray = function (array, index) {
  402. if (index === undefined) {
  403. index = 0;
  404. }
  405. array[index] = this.x;
  406. array[index + 1] = this.y;
  407. array[index + 2] = this.z;
  408. };
  409. Vector3.prototype.addInPlace = function (otherVector) {
  410. this.x += otherVector.x;
  411. this.y += otherVector.y;
  412. this.z += otherVector.z;
  413. };
  414. Vector3.prototype.add = function (otherVector) {
  415. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  416. };
  417. Vector3.prototype.addToRef = function (otherVector, result) {
  418. result.x = this.x + otherVector.x;
  419. result.y = this.y + otherVector.y;
  420. result.z = this.z + otherVector.z;
  421. };
  422. Vector3.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. this.z -= otherVector.z;
  426. };
  427. Vector3.prototype.subtract = function (otherVector) {
  428. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  429. };
  430. Vector3.prototype.subtractToRef = function (otherVector, result) {
  431. result.x = this.x - otherVector.x;
  432. result.y = this.y - otherVector.y;
  433. result.z = this.z - otherVector.z;
  434. };
  435. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  436. return new Vector3(this.x - x, this.y - y, this.z - z);
  437. };
  438. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  439. result.x = this.x - x;
  440. result.y = this.y - y;
  441. result.z = this.z - z;
  442. };
  443. Vector3.prototype.negate = function () {
  444. return new Vector3(-this.x, -this.y, -this.z);
  445. };
  446. Vector3.prototype.scaleInPlace = function (scale) {
  447. this.x *= scale;
  448. this.y *= scale;
  449. this.z *= scale;
  450. return this;
  451. };
  452. Vector3.prototype.scale = function (scale) {
  453. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  454. };
  455. Vector3.prototype.scaleToRef = function (scale, result) {
  456. result.x = this.x * scale;
  457. result.y = this.y * scale;
  458. result.z = this.z * scale;
  459. };
  460. Vector3.prototype.equals = function (otherVector) {
  461. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  462. };
  463. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  464. 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;
  465. };
  466. Vector3.prototype.equalsToFloats = function (x, y, z) {
  467. return this.x === x && this.y === y && this.z === z;
  468. };
  469. Vector3.prototype.multiplyInPlace = function (otherVector) {
  470. this.x *= otherVector.x;
  471. this.y *= otherVector.y;
  472. this.z *= otherVector.z;
  473. };
  474. Vector3.prototype.multiply = function (otherVector) {
  475. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  476. };
  477. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  478. result.x = this.x * otherVector.x;
  479. result.y = this.y * otherVector.y;
  480. result.z = this.z * otherVector.z;
  481. };
  482. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  483. return new Vector3(this.x * x, this.y * y, this.z * z);
  484. };
  485. Vector3.prototype.divide = function (otherVector) {
  486. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  487. };
  488. Vector3.prototype.divideToRef = function (otherVector, result) {
  489. result.x = this.x / otherVector.x;
  490. result.y = this.y / otherVector.y;
  491. result.z = this.z / otherVector.z;
  492. };
  493. Vector3.prototype.MinimizeInPlace = function (other) {
  494. if (other.x < this.x)
  495. this.x = other.x;
  496. if (other.y < this.y)
  497. this.y = other.y;
  498. if (other.z < this.z)
  499. this.z = other.z;
  500. };
  501. Vector3.prototype.MaximizeInPlace = function (other) {
  502. if (other.x > this.x)
  503. this.x = other.x;
  504. if (other.y > this.y)
  505. this.y = other.y;
  506. if (other.z > this.z)
  507. this.z = other.z;
  508. };
  509. // Properties
  510. Vector3.prototype.length = function () {
  511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  512. };
  513. Vector3.prototype.lengthSquared = function () {
  514. return (this.x * this.x + this.y * this.y + this.z * this.z);
  515. };
  516. // Methods
  517. Vector3.prototype.normalize = function () {
  518. var len = this.length();
  519. if (len === 0)
  520. return this;
  521. var num = 1.0 / len;
  522. this.x *= num;
  523. this.y *= num;
  524. this.z *= num;
  525. return this;
  526. };
  527. Vector3.prototype.clone = function () {
  528. return new Vector3(this.x, this.y, this.z);
  529. };
  530. Vector3.prototype.copyFrom = function (source) {
  531. this.x = source.x;
  532. this.y = source.y;
  533. this.z = source.z;
  534. };
  535. Vector3.prototype.copyFromFloats = function (x, y, z) {
  536. this.x = x;
  537. this.y = y;
  538. this.z = z;
  539. };
  540. // Statics
  541. Vector3.FromArray = function (array, offset) {
  542. if (!offset) {
  543. offset = 0;
  544. }
  545. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  546. };
  547. Vector3.FromArrayToRef = function (array, offset, result) {
  548. result.x = array[offset];
  549. result.y = array[offset + 1];
  550. result.z = array[offset + 2];
  551. };
  552. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatsToRef = function (x, y, z, result) {
  558. result.x = x;
  559. result.y = y;
  560. result.z = z;
  561. };
  562. Vector3.Zero = function () {
  563. return new Vector3(0, 0, 0);
  564. };
  565. Vector3.Up = function () {
  566. return new Vector3(0, 1.0, 0);
  567. };
  568. Vector3.TransformCoordinates = function (vector, transformation) {
  569. var result = Vector3.Zero();
  570. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  571. return result;
  572. };
  573. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  574. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  575. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  576. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  577. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  578. result.x = x / w;
  579. result.y = y / w;
  580. result.z = z / w;
  581. };
  582. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  583. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  584. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  585. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  586. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  587. result.x = rx / rw;
  588. result.y = ry / rw;
  589. result.z = rz / rw;
  590. };
  591. Vector3.TransformNormal = function (vector, transformation) {
  592. var result = Vector3.Zero();
  593. Vector3.TransformNormalToRef(vector, transformation, result);
  594. return result;
  595. };
  596. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  597. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  598. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  599. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  600. };
  601. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  602. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  603. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  604. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  605. };
  606. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  607. var squared = amount * amount;
  608. var cubed = amount * squared;
  609. 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));
  610. 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));
  611. 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));
  612. return new Vector3(x, y, z);
  613. };
  614. Vector3.Clamp = function (value, min, max) {
  615. var x = value.x;
  616. x = (x > max.x) ? max.x : x;
  617. x = (x < min.x) ? min.x : x;
  618. var y = value.y;
  619. y = (y > max.y) ? max.y : y;
  620. y = (y < min.y) ? min.y : y;
  621. var z = value.z;
  622. z = (z > max.z) ? max.z : z;
  623. z = (z < min.z) ? min.z : z;
  624. return new Vector3(x, y, z);
  625. };
  626. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  627. var squared = amount * amount;
  628. var cubed = amount * squared;
  629. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  630. var part2 = (-2.0 * cubed) + (3.0 * squared);
  631. var part3 = (cubed - (2.0 * squared)) + amount;
  632. var part4 = cubed - squared;
  633. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  634. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  635. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  636. return new Vector3(x, y, z);
  637. };
  638. Vector3.Lerp = function (start, end, amount) {
  639. var x = start.x + ((end.x - start.x) * amount);
  640. var y = start.y + ((end.y - start.y) * amount);
  641. var z = start.z + ((end.z - start.z) * amount);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Dot = function (left, right) {
  645. return (left.x * right.x + left.y * right.y + left.z * right.z);
  646. };
  647. Vector3.Cross = function (left, right) {
  648. var result = Vector3.Zero();
  649. Vector3.CrossToRef(left, right, result);
  650. return result;
  651. };
  652. Vector3.CrossToRef = function (left, right, result) {
  653. result.x = left.y * right.z - left.z * right.y;
  654. result.y = left.z * right.x - left.x * right.z;
  655. result.z = left.x * right.y - left.y * right.x;
  656. };
  657. Vector3.Normalize = function (vector) {
  658. var result = Vector3.Zero();
  659. Vector3.NormalizeToRef(vector, result);
  660. return result;
  661. };
  662. Vector3.NormalizeToRef = function (vector, result) {
  663. result.copyFrom(vector);
  664. result.normalize();
  665. };
  666. Vector3.Project = function (vector, world, transform, viewport) {
  667. var cw = viewport.width;
  668. var ch = viewport.height;
  669. var cx = viewport.x;
  670. var cy = viewport.y;
  671. var viewportMatrix = 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);
  672. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  673. return Vector3.TransformCoordinates(vector, finalMatrix);
  674. };
  675. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  676. var matrix = world.multiply(transform);
  677. matrix.invert();
  678. source.x = source.x / viewportWidth * 2 - 1;
  679. source.y = -(source.y / viewportHeight * 2 - 1);
  680. var vector = Vector3.TransformCoordinates(source, matrix);
  681. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  682. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  683. vector = vector.scale(1.0 / num);
  684. }
  685. return vector;
  686. };
  687. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  688. var matrix = world.multiply(view).multiply(projection);
  689. matrix.invert();
  690. source.x = source.x / viewportWidth * 2 - 1;
  691. source.y = -(source.y / viewportHeight * 2 - 1);
  692. var vector = Vector3.TransformCoordinates(source, matrix);
  693. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  694. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  695. vector = vector.scale(1.0 / num);
  696. }
  697. return vector;
  698. };
  699. Vector3.Minimize = function (left, right) {
  700. var min = left.clone();
  701. min.MinimizeInPlace(right);
  702. return min;
  703. };
  704. Vector3.Maximize = function (left, right) {
  705. var max = left.clone();
  706. max.MaximizeInPlace(right);
  707. return max;
  708. };
  709. Vector3.Distance = function (value1, value2) {
  710. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  711. };
  712. Vector3.DistanceSquared = function (value1, value2) {
  713. var x = value1.x - value2.x;
  714. var y = value1.y - value2.y;
  715. var z = value1.z - value2.z;
  716. return (x * x) + (y * y) + (z * z);
  717. };
  718. Vector3.Center = function (value1, value2) {
  719. var center = value1.add(value2);
  720. center.scaleInPlace(0.5);
  721. return center;
  722. };
  723. return Vector3;
  724. })();
  725. BABYLON.Vector3 = Vector3;
  726. //Vector4 class created for EulerAngle class conversion to Quaternion
  727. var Vector4 = (function () {
  728. function Vector4(x, y, z, w) {
  729. this.x = x;
  730. this.y = y;
  731. this.z = z;
  732. this.w = w;
  733. }
  734. Vector4.prototype.toString = function () {
  735. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  736. };
  737. // Operators
  738. Vector4.prototype.asArray = function () {
  739. var result = [];
  740. this.toArray(result, 0);
  741. return result;
  742. };
  743. Vector4.prototype.toArray = function (array, index) {
  744. if (index === undefined) {
  745. index = 0;
  746. }
  747. array[index] = this.x;
  748. array[index + 1] = this.y;
  749. array[index + 2] = this.z;
  750. array[index + 3] = this.w;
  751. };
  752. Vector4.prototype.addInPlace = function (otherVector) {
  753. this.x += otherVector.x;
  754. this.y += otherVector.y;
  755. this.z += otherVector.z;
  756. this.w += otherVector.w;
  757. };
  758. Vector4.prototype.add = function (otherVector) {
  759. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  760. };
  761. Vector4.prototype.addToRef = function (otherVector, result) {
  762. result.x = this.x + otherVector.x;
  763. result.y = this.y + otherVector.y;
  764. result.z = this.z + otherVector.z;
  765. result.w = this.w + otherVector.w;
  766. };
  767. Vector4.prototype.subtractInPlace = function (otherVector) {
  768. this.x -= otherVector.x;
  769. this.y -= otherVector.y;
  770. this.z -= otherVector.z;
  771. this.w -= otherVector.w;
  772. };
  773. Vector4.prototype.subtract = function (otherVector) {
  774. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  775. };
  776. Vector4.prototype.subtractToRef = function (otherVector, result) {
  777. result.x = this.x - otherVector.x;
  778. result.y = this.y - otherVector.y;
  779. result.z = this.z - otherVector.z;
  780. result.w = this.w - otherVector.w;
  781. };
  782. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  783. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  784. };
  785. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  786. result.x = this.x - x;
  787. result.y = this.y - y;
  788. result.z = this.z - z;
  789. result.w = this.w - w;
  790. };
  791. Vector4.prototype.negate = function () {
  792. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  793. };
  794. Vector4.prototype.scaleInPlace = function (scale) {
  795. this.x *= scale;
  796. this.y *= scale;
  797. this.z *= scale;
  798. this.w *= scale;
  799. return this;
  800. };
  801. Vector4.prototype.scale = function (scale) {
  802. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  803. };
  804. Vector4.prototype.scaleToRef = function (scale, result) {
  805. result.x = this.x * scale;
  806. result.y = this.y * scale;
  807. result.z = this.z * scale;
  808. result.w = this.w * scale;
  809. };
  810. Vector4.prototype.equals = function (otherVector) {
  811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  812. };
  813. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  814. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  815. };
  816. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  817. return this.x === x && this.y === y && this.z === z && this.w === w;
  818. };
  819. Vector4.prototype.multiplyInPlace = function (otherVector) {
  820. this.x *= otherVector.x;
  821. this.y *= otherVector.y;
  822. this.z *= otherVector.z;
  823. this.w *= otherVector.w;
  824. };
  825. Vector4.prototype.multiply = function (otherVector) {
  826. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  827. };
  828. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  829. result.x = this.x * otherVector.x;
  830. result.y = this.y * otherVector.y;
  831. result.z = this.z * otherVector.z;
  832. result.w = this.w * otherVector.w;
  833. };
  834. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  835. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  836. };
  837. Vector4.prototype.divide = function (otherVector) {
  838. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  839. };
  840. Vector4.prototype.divideToRef = function (otherVector, result) {
  841. result.x = this.x / otherVector.x;
  842. result.y = this.y / otherVector.y;
  843. result.z = this.z / otherVector.z;
  844. result.w = this.w / otherVector.w;
  845. };
  846. Vector4.prototype.MinimizeInPlace = function (other) {
  847. if (other.x < this.x)
  848. this.x = other.x;
  849. if (other.y < this.y)
  850. this.y = other.y;
  851. if (other.z < this.z)
  852. this.z = other.z;
  853. if (other.w < this.w)
  854. this.w = other.w;
  855. };
  856. Vector4.prototype.MaximizeInPlace = function (other) {
  857. if (other.x > this.x)
  858. this.x = other.x;
  859. if (other.y > this.y)
  860. this.y = other.y;
  861. if (other.z > this.z)
  862. this.z = other.z;
  863. if (other.w > this.w)
  864. this.w = other.w;
  865. };
  866. // Properties
  867. Vector4.prototype.length = function () {
  868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  869. };
  870. Vector4.prototype.lengthSquared = function () {
  871. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  872. };
  873. // Methods
  874. Vector4.prototype.normalize = function () {
  875. var len = this.length();
  876. if (len === 0)
  877. return this;
  878. var num = 1.0 / len;
  879. this.x *= num;
  880. this.y *= num;
  881. this.z *= num;
  882. this.w *= num;
  883. return this;
  884. };
  885. Vector4.prototype.clone = function () {
  886. return new Vector4(this.x, this.y, this.z, this.w);
  887. };
  888. Vector4.prototype.copyFrom = function (source) {
  889. this.x = source.x;
  890. this.y = source.y;
  891. this.z = source.z;
  892. this.w = source.w;
  893. };
  894. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. };
  900. // Statics
  901. Vector4.FromArray = function (array, offset) {
  902. if (!offset) {
  903. offset = 0;
  904. }
  905. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  906. };
  907. Vector4.FromArrayToRef = function (array, offset, result) {
  908. result.x = array[offset];
  909. result.y = array[offset + 1];
  910. result.z = array[offset + 2];
  911. result.w = array[offset + 3];
  912. };
  913. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  914. result.x = array[offset];
  915. result.y = array[offset + 1];
  916. result.z = array[offset + 2];
  917. result.w = array[offset + 3];
  918. };
  919. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  920. result.x = x;
  921. result.y = y;
  922. result.z = z;
  923. result.w = w;
  924. };
  925. Vector4.Zero = function () {
  926. return new Vector4(0, 0, 0, 0);
  927. };
  928. Vector4.Normalize = function (vector) {
  929. var result = Vector4.Zero();
  930. Vector4.NormalizeToRef(vector, result);
  931. return result;
  932. };
  933. Vector4.NormalizeToRef = function (vector, result) {
  934. result.copyFrom(vector);
  935. result.normalize();
  936. };
  937. Vector4.Minimize = function (left, right) {
  938. var min = left.clone();
  939. min.MinimizeInPlace(right);
  940. return min;
  941. };
  942. Vector4.Maximize = function (left, right) {
  943. var max = left.clone();
  944. max.MaximizeInPlace(right);
  945. return max;
  946. };
  947. Vector4.Distance = function (value1, value2) {
  948. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  949. };
  950. Vector4.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. var z = value1.z - value2.z;
  954. var w = value1.w - value2.w;
  955. return (x * x) + (y * y) + (z * z) + (w * w);
  956. };
  957. Vector4.Center = function (value1, value2) {
  958. var center = value1.add(value2);
  959. center.scaleInPlace(0.5);
  960. return center;
  961. };
  962. return Vector4;
  963. })();
  964. BABYLON.Vector4 = Vector4;
  965. var Quaternion = (function () {
  966. function Quaternion(x, y, z, w) {
  967. if (typeof x === "undefined") { x = 0; }
  968. if (typeof y === "undefined") { y = 0; }
  969. if (typeof z === "undefined") { z = 0; }
  970. if (typeof w === "undefined") { w = 1; }
  971. this.x = x;
  972. this.y = y;
  973. this.z = z;
  974. this.w = w;
  975. }
  976. Quaternion.prototype.toString = function () {
  977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  978. };
  979. Quaternion.prototype.asArray = function () {
  980. return [this.x, this.y, this.z, this.w];
  981. };
  982. Quaternion.prototype.equals = function (otherQuaternion) {
  983. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  984. };
  985. Quaternion.prototype.clone = function () {
  986. return new Quaternion(this.x, this.y, this.z, this.w);
  987. };
  988. Quaternion.prototype.copyFrom = function (other) {
  989. this.x = other.x;
  990. this.y = other.y;
  991. this.z = other.z;
  992. this.w = other.w;
  993. };
  994. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  995. this.x = x;
  996. this.y = y;
  997. this.z = z;
  998. this.w = w;
  999. };
  1000. Quaternion.prototype.add = function (other) {
  1001. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1002. };
  1003. Quaternion.prototype.subtract = function (other) {
  1004. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1005. };
  1006. Quaternion.prototype.scale = function (value) {
  1007. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1008. };
  1009. Quaternion.prototype.multiply = function (q1) {
  1010. var result = new Quaternion(0, 0, 0, 1.0);
  1011. this.multiplyToRef(q1, result);
  1012. return result;
  1013. };
  1014. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1015. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1016. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1017. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1018. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1019. };
  1020. Quaternion.prototype.length = function () {
  1021. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1022. };
  1023. Quaternion.prototype.normalize = function () {
  1024. var length = 1.0 / this.length();
  1025. this.x *= length;
  1026. this.y *= length;
  1027. this.z *= length;
  1028. this.w *= length;
  1029. };
  1030. Quaternion.prototype.toEulerAngles = function () {
  1031. var result = Vector3.Zero();
  1032. this.toEulerAnglesToRef(result);
  1033. return result;
  1034. };
  1035. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1036. //result is an EulerAngles in the in the z-x-z convention
  1037. var qx = this.x;
  1038. var qy = this.y;
  1039. var qz = this.z;
  1040. var qw = this.w;
  1041. var qxy = qx * qy;
  1042. var qxz = qx * qz;
  1043. var qwy = qw * qy;
  1044. var qwz = qw * qz;
  1045. var qwx = qw * qx;
  1046. var qyz = qy * qz;
  1047. var sqx = qx * qx;
  1048. var sqy = qy * qy;
  1049. var determinant = sqx + sqy;
  1050. if (determinant !== 0.000 && determinant !== 1.000) {
  1051. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1052. result.y = Math.acos(1 - 2 * determinant);
  1053. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1054. } else {
  1055. if (determinant === 0.0) {
  1056. result.x = 0.0;
  1057. result.y = 0.0;
  1058. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1059. } else {
  1060. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1061. result.y = Math.PI;
  1062. result.z = 0.0;
  1063. }
  1064. }
  1065. };
  1066. Quaternion.prototype.toRotationMatrix = function (result) {
  1067. var xx = this.x * this.x;
  1068. var yy = this.y * this.y;
  1069. var zz = this.z * this.z;
  1070. var xy = this.x * this.y;
  1071. var zw = this.z * this.w;
  1072. var zx = this.z * this.x;
  1073. var yw = this.y * this.w;
  1074. var yz = this.y * this.z;
  1075. var xw = this.x * this.w;
  1076. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1077. result.m[1] = 2.0 * (xy + zw);
  1078. result.m[2] = 2.0 * (zx - yw);
  1079. result.m[3] = 0;
  1080. result.m[4] = 2.0 * (xy - zw);
  1081. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1082. result.m[6] = 2.0 * (yz + xw);
  1083. result.m[7] = 0;
  1084. result.m[8] = 2.0 * (zx + yw);
  1085. result.m[9] = 2.0 * (yz - xw);
  1086. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1087. result.m[11] = 0;
  1088. result.m[12] = 0;
  1089. result.m[13] = 0;
  1090. result.m[14] = 0;
  1091. result.m[15] = 1.0;
  1092. };
  1093. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1094. var data = matrix.m;
  1095. var m11 = data[0], m12 = data[4], m13 = data[8];
  1096. var m21 = data[1], m22 = data[5], m23 = data[9];
  1097. var m31 = data[2], m32 = data[6], m33 = data[10];
  1098. var trace = m11 + m22 + m33;
  1099. var s;
  1100. if (trace > 0) {
  1101. s = 0.5 / Math.sqrt(trace + 1.0);
  1102. this.w = 0.25 / s;
  1103. this.x = (m32 - m23) * s;
  1104. this.y = (m13 - m31) * s;
  1105. this.z = (m21 - m12) * s;
  1106. return;
  1107. }
  1108. if (m11 > m22 && m11 > m33) {
  1109. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1110. this.w = (m32 - m23) / s;
  1111. this.x = 0.25 * s;
  1112. this.y = (m12 + m21) / s;
  1113. this.z = (m13 + m31) / s;
  1114. return;
  1115. }
  1116. if (m22 > m33) {
  1117. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1118. this.w = (m13 - m31) / s;
  1119. this.x = (m12 + m21) / s;
  1120. this.y = 0.25 * s;
  1121. this.z = (m23 + m32) / s;
  1122. return;
  1123. }
  1124. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1125. this.w = (m21 - m12) / s;
  1126. this.x = (m13 + m31) / s;
  1127. this.y = (m23 + m32) / s;
  1128. this.z = 0.25 * s;
  1129. };
  1130. // Statics
  1131. Quaternion.Inverse = function (q) {
  1132. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1133. };
  1134. Quaternion.RotationAxis = function (axis, angle) {
  1135. var result = new Quaternion();
  1136. var sin = Math.sin(angle / 2);
  1137. result.w = Math.cos(angle / 2);
  1138. result.x = axis.x * sin;
  1139. result.y = axis.y * sin;
  1140. result.z = axis.z * sin;
  1141. return result;
  1142. };
  1143. Quaternion.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1150. var result = new Quaternion();
  1151. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1152. return result;
  1153. };
  1154. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1155. var halfRoll = roll * 0.5;
  1156. var halfPitch = pitch * 0.5;
  1157. var halfYaw = yaw * 0.5;
  1158. var sinRoll = Math.sin(halfRoll);
  1159. var cosRoll = Math.cos(halfRoll);
  1160. var sinPitch = Math.sin(halfPitch);
  1161. var cosPitch = Math.cos(halfPitch);
  1162. var sinYaw = Math.sin(halfYaw);
  1163. var cosYaw = Math.cos(halfYaw);
  1164. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1165. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1166. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1167. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1168. };
  1169. Quaternion.Slerp = function (left, right, amount) {
  1170. var num2;
  1171. var num3;
  1172. var num = amount;
  1173. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1174. var flag = false;
  1175. if (num4 < 0) {
  1176. flag = true;
  1177. num4 = -num4;
  1178. }
  1179. if (num4 > 0.999999) {
  1180. num3 = 1 - num;
  1181. num2 = flag ? -num : num;
  1182. } else {
  1183. var num5 = Math.acos(num4);
  1184. var num6 = (1.0 / Math.sin(num5));
  1185. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1186. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1187. }
  1188. 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));
  1189. };
  1190. return Quaternion;
  1191. })();
  1192. BABYLON.Quaternion = Quaternion;
  1193. var Matrix = (function () {
  1194. function Matrix() {
  1195. this.m = new Float32Array(16);
  1196. }
  1197. // Properties
  1198. Matrix.prototype.isIdentity = function () {
  1199. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1200. return false;
  1201. 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)
  1202. return false;
  1203. return true;
  1204. };
  1205. Matrix.prototype.determinant = function () {
  1206. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1207. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1208. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1209. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1210. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1211. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1212. 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))));
  1213. };
  1214. // Methods
  1215. Matrix.prototype.toArray = function () {
  1216. return this.m;
  1217. };
  1218. Matrix.prototype.asArray = function () {
  1219. return this.toArray();
  1220. };
  1221. Matrix.prototype.invert = function () {
  1222. this.invertToRef(this);
  1223. };
  1224. Matrix.prototype.invertToRef = function (other) {
  1225. var l1 = this.m[0];
  1226. var l2 = this.m[1];
  1227. var l3 = this.m[2];
  1228. var l4 = this.m[3];
  1229. var l5 = this.m[4];
  1230. var l6 = this.m[5];
  1231. var l7 = this.m[6];
  1232. var l8 = this.m[7];
  1233. var l9 = this.m[8];
  1234. var l10 = this.m[9];
  1235. var l11 = this.m[10];
  1236. var l12 = this.m[11];
  1237. var l13 = this.m[12];
  1238. var l14 = this.m[13];
  1239. var l15 = this.m[14];
  1240. var l16 = this.m[15];
  1241. var l17 = (l11 * l16) - (l12 * l15);
  1242. var l18 = (l10 * l16) - (l12 * l14);
  1243. var l19 = (l10 * l15) - (l11 * l14);
  1244. var l20 = (l9 * l16) - (l12 * l13);
  1245. var l21 = (l9 * l15) - (l11 * l13);
  1246. var l22 = (l9 * l14) - (l10 * l13);
  1247. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1248. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1249. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1250. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1251. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1252. var l28 = (l7 * l16) - (l8 * l15);
  1253. var l29 = (l6 * l16) - (l8 * l14);
  1254. var l30 = (l6 * l15) - (l7 * l14);
  1255. var l31 = (l5 * l16) - (l8 * l13);
  1256. var l32 = (l5 * l15) - (l7 * l13);
  1257. var l33 = (l5 * l14) - (l6 * l13);
  1258. var l34 = (l7 * l12) - (l8 * l11);
  1259. var l35 = (l6 * l12) - (l8 * l10);
  1260. var l36 = (l6 * l11) - (l7 * l10);
  1261. var l37 = (l5 * l12) - (l8 * l9);
  1262. var l38 = (l5 * l11) - (l7 * l9);
  1263. var l39 = (l5 * l10) - (l6 * l9);
  1264. other.m[0] = l23 * l27;
  1265. other.m[4] = l24 * l27;
  1266. other.m[8] = l25 * l27;
  1267. other.m[12] = l26 * l27;
  1268. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1269. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1270. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1271. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1272. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1273. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1274. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1275. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1276. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1277. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1278. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1279. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1280. };
  1281. Matrix.prototype.setTranslation = function (vector3) {
  1282. this.m[12] = vector3.x;
  1283. this.m[13] = vector3.y;
  1284. this.m[14] = vector3.z;
  1285. };
  1286. Matrix.prototype.multiply = function (other) {
  1287. var result = new Matrix();
  1288. this.multiplyToRef(other, result);
  1289. return result;
  1290. };
  1291. Matrix.prototype.copyFrom = function (other) {
  1292. for (var index = 0; index < 16; index++) {
  1293. this.m[index] = other.m[index];
  1294. }
  1295. };
  1296. Matrix.prototype.copyToArray = function (array, offset) {
  1297. if (typeof offset === "undefined") { offset = 0; }
  1298. for (var index = 0; index < 16; index++) {
  1299. array[offset + index] = this.m[index];
  1300. }
  1301. };
  1302. Matrix.prototype.multiplyToRef = function (other, result) {
  1303. this.multiplyToArray(other, result.m, 0);
  1304. };
  1305. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1306. var tm0 = this.m[0];
  1307. var tm1 = this.m[1];
  1308. var tm2 = this.m[2];
  1309. var tm3 = this.m[3];
  1310. var tm4 = this.m[4];
  1311. var tm5 = this.m[5];
  1312. var tm6 = this.m[6];
  1313. var tm7 = this.m[7];
  1314. var tm8 = this.m[8];
  1315. var tm9 = this.m[9];
  1316. var tm10 = this.m[10];
  1317. var tm11 = this.m[11];
  1318. var tm12 = this.m[12];
  1319. var tm13 = this.m[13];
  1320. var tm14 = this.m[14];
  1321. var tm15 = this.m[15];
  1322. var om0 = other.m[0];
  1323. var om1 = other.m[1];
  1324. var om2 = other.m[2];
  1325. var om3 = other.m[3];
  1326. var om4 = other.m[4];
  1327. var om5 = other.m[5];
  1328. var om6 = other.m[6];
  1329. var om7 = other.m[7];
  1330. var om8 = other.m[8];
  1331. var om9 = other.m[9];
  1332. var om10 = other.m[10];
  1333. var om11 = other.m[11];
  1334. var om12 = other.m[12];
  1335. var om13 = other.m[13];
  1336. var om14 = other.m[14];
  1337. var om15 = other.m[15];
  1338. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1339. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1340. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1341. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1342. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1343. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1344. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1345. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1346. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1347. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1348. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1349. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1350. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1351. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1352. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1353. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1354. };
  1355. Matrix.prototype.equals = function (value) {
  1356. 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]);
  1357. };
  1358. Matrix.prototype.clone = function () {
  1359. 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]);
  1360. };
  1361. // Statics
  1362. Matrix.FromArray = function (array, offset) {
  1363. var result = new Matrix();
  1364. if (!offset) {
  1365. offset = 0;
  1366. }
  1367. Matrix.FromArrayToRef(array, offset, result);
  1368. return result;
  1369. };
  1370. Matrix.FromArrayToRef = function (array, offset, result) {
  1371. for (var index = 0; index < 16; index++) {
  1372. result.m[index] = array[index + offset];
  1373. }
  1374. };
  1375. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1376. result.m[0] = initialM11;
  1377. result.m[1] = initialM12;
  1378. result.m[2] = initialM13;
  1379. result.m[3] = initialM14;
  1380. result.m[4] = initialM21;
  1381. result.m[5] = initialM22;
  1382. result.m[6] = initialM23;
  1383. result.m[7] = initialM24;
  1384. result.m[8] = initialM31;
  1385. result.m[9] = initialM32;
  1386. result.m[10] = initialM33;
  1387. result.m[11] = initialM34;
  1388. result.m[12] = initialM41;
  1389. result.m[13] = initialM42;
  1390. result.m[14] = initialM43;
  1391. result.m[15] = initialM44;
  1392. };
  1393. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1394. var result = new Matrix();
  1395. result.m[0] = initialM11;
  1396. result.m[1] = initialM12;
  1397. result.m[2] = initialM13;
  1398. result.m[3] = initialM14;
  1399. result.m[4] = initialM21;
  1400. result.m[5] = initialM22;
  1401. result.m[6] = initialM23;
  1402. result.m[7] = initialM24;
  1403. result.m[8] = initialM31;
  1404. result.m[9] = initialM32;
  1405. result.m[10] = initialM33;
  1406. result.m[11] = initialM34;
  1407. result.m[12] = initialM41;
  1408. result.m[13] = initialM42;
  1409. result.m[14] = initialM43;
  1410. result.m[15] = initialM44;
  1411. return result;
  1412. };
  1413. Matrix.Identity = function () {
  1414. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1415. };
  1416. Matrix.IdentityToRef = function (result) {
  1417. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1418. };
  1419. Matrix.Zero = function () {
  1420. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1421. };
  1422. Matrix.RotationX = function (angle) {
  1423. var result = new Matrix();
  1424. Matrix.RotationXToRef(angle, result);
  1425. return result;
  1426. };
  1427. Matrix.Invert = function (source) {
  1428. var result = new Matrix();
  1429. source.invertToRef(result);
  1430. return result;
  1431. };
  1432. Matrix.RotationXToRef = function (angle, result) {
  1433. var s = Math.sin(angle);
  1434. var c = Math.cos(angle);
  1435. result.m[0] = 1.0;
  1436. result.m[15] = 1.0;
  1437. result.m[5] = c;
  1438. result.m[10] = c;
  1439. result.m[9] = -s;
  1440. result.m[6] = s;
  1441. result.m[1] = 0;
  1442. result.m[2] = 0;
  1443. result.m[3] = 0;
  1444. result.m[4] = 0;
  1445. result.m[7] = 0;
  1446. result.m[8] = 0;
  1447. result.m[11] = 0;
  1448. result.m[12] = 0;
  1449. result.m[13] = 0;
  1450. result.m[14] = 0;
  1451. };
  1452. Matrix.RotationY = function (angle) {
  1453. var result = new Matrix();
  1454. Matrix.RotationYToRef(angle, result);
  1455. return result;
  1456. };
  1457. Matrix.RotationYToRef = function (angle, result) {
  1458. var s = Math.sin(angle);
  1459. var c = Math.cos(angle);
  1460. result.m[5] = 1.0;
  1461. result.m[15] = 1.0;
  1462. result.m[0] = c;
  1463. result.m[2] = -s;
  1464. result.m[8] = s;
  1465. result.m[10] = c;
  1466. result.m[1] = 0;
  1467. result.m[3] = 0;
  1468. result.m[4] = 0;
  1469. result.m[6] = 0;
  1470. result.m[7] = 0;
  1471. result.m[9] = 0;
  1472. result.m[11] = 0;
  1473. result.m[12] = 0;
  1474. result.m[13] = 0;
  1475. result.m[14] = 0;
  1476. };
  1477. Matrix.RotationZ = function (angle) {
  1478. var result = new Matrix();
  1479. Matrix.RotationZToRef(angle, result);
  1480. return result;
  1481. };
  1482. Matrix.RotationZToRef = function (angle, result) {
  1483. var s = Math.sin(angle);
  1484. var c = Math.cos(angle);
  1485. result.m[10] = 1.0;
  1486. result.m[15] = 1.0;
  1487. result.m[0] = c;
  1488. result.m[1] = s;
  1489. result.m[4] = -s;
  1490. result.m[5] = c;
  1491. result.m[2] = 0;
  1492. result.m[3] = 0;
  1493. result.m[6] = 0;
  1494. result.m[7] = 0;
  1495. result.m[8] = 0;
  1496. result.m[9] = 0;
  1497. result.m[11] = 0;
  1498. result.m[12] = 0;
  1499. result.m[13] = 0;
  1500. result.m[14] = 0;
  1501. };
  1502. Matrix.RotationAxis = function (axis, angle) {
  1503. var s = Math.sin(-angle);
  1504. var c = Math.cos(-angle);
  1505. var c1 = 1 - c;
  1506. axis.normalize();
  1507. var result = Matrix.Zero();
  1508. result.m[0] = (axis.x * axis.x) * c1 + c;
  1509. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1510. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1511. result.m[3] = 0.0;
  1512. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1513. result.m[5] = (axis.y * axis.y) * c1 + c;
  1514. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1515. result.m[7] = 0.0;
  1516. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1517. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1518. result.m[10] = (axis.z * axis.z) * c1 + c;
  1519. result.m[11] = 0.0;
  1520. result.m[15] = 1.0;
  1521. return result;
  1522. };
  1523. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1524. var result = new Matrix();
  1525. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1526. return result;
  1527. };
  1528. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1529. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1530. this._tempQuaternion.toRotationMatrix(result);
  1531. };
  1532. Matrix.Scaling = function (x, y, z) {
  1533. var result = Matrix.Zero();
  1534. Matrix.ScalingToRef(x, y, z, result);
  1535. return result;
  1536. };
  1537. Matrix.ScalingToRef = function (x, y, z, result) {
  1538. result.m[0] = x;
  1539. result.m[1] = 0;
  1540. result.m[2] = 0;
  1541. result.m[3] = 0;
  1542. result.m[4] = 0;
  1543. result.m[5] = y;
  1544. result.m[6] = 0;
  1545. result.m[7] = 0;
  1546. result.m[8] = 0;
  1547. result.m[9] = 0;
  1548. result.m[10] = z;
  1549. result.m[11] = 0;
  1550. result.m[12] = 0;
  1551. result.m[13] = 0;
  1552. result.m[14] = 0;
  1553. result.m[15] = 1.0;
  1554. };
  1555. Matrix.Translation = function (x, y, z) {
  1556. var result = Matrix.Identity();
  1557. Matrix.TranslationToRef(x, y, z, result);
  1558. return result;
  1559. };
  1560. Matrix.TranslationToRef = function (x, y, z, result) {
  1561. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1562. };
  1563. Matrix.LookAtLH = function (eye, target, up) {
  1564. var result = Matrix.Zero();
  1565. Matrix.LookAtLHToRef(eye, target, up, result);
  1566. return result;
  1567. };
  1568. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1569. // Z axis
  1570. target.subtractToRef(eye, this._zAxis);
  1571. this._zAxis.normalize();
  1572. // X axis
  1573. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1574. this._xAxis.normalize();
  1575. // Y axis
  1576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1577. this._yAxis.normalize();
  1578. // Eye angles
  1579. var ex = -Vector3.Dot(this._xAxis, eye);
  1580. var ey = -Vector3.Dot(this._yAxis, eye);
  1581. var ez = -Vector3.Dot(this._zAxis, eye);
  1582. 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);
  1583. };
  1584. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1585. var hw = 2.0 / width;
  1586. var hh = 2.0 / height;
  1587. var id = 1.0 / (zfar - znear);
  1588. var nid = znear / (znear - zfar);
  1589. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1590. };
  1591. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1592. var matrix = Matrix.Zero();
  1593. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1594. return matrix;
  1595. };
  1596. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1597. result.m[0] = 2.0 / (right - left);
  1598. result.m[1] = result.m[2] = result.m[3] = 0;
  1599. result.m[5] = 2.0 / (top - bottom);
  1600. result.m[4] = result.m[6] = result.m[7] = 0;
  1601. result.m[10] = -1.0 / (znear - zfar);
  1602. result.m[8] = result.m[9] = result.m[11] = 0;
  1603. result.m[12] = (left + right) / (left - right);
  1604. result.m[13] = (top + bottom) / (bottom - top);
  1605. result.m[14] = znear / (znear - zfar);
  1606. result.m[15] = 1.0;
  1607. };
  1608. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1609. var matrix = Matrix.Zero();
  1610. matrix.m[0] = (2.0 * znear) / width;
  1611. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1612. matrix.m[5] = (2.0 * znear) / height;
  1613. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1614. matrix.m[10] = -zfar / (znear - zfar);
  1615. matrix.m[8] = matrix.m[9] = 0.0;
  1616. matrix.m[11] = 1.0;
  1617. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1618. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1619. return matrix;
  1620. };
  1621. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1622. var matrix = Matrix.Zero();
  1623. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1624. return matrix;
  1625. };
  1626. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1627. var tan = 1.0 / (Math.tan(fov * 0.5));
  1628. result.m[0] = tan / aspect;
  1629. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1630. result.m[5] = tan;
  1631. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1632. result.m[8] = result.m[9] = 0.0;
  1633. result.m[10] = -zfar / (znear - zfar);
  1634. result.m[11] = 1.0;
  1635. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1636. result.m[14] = (znear * zfar) / (znear - zfar);
  1637. };
  1638. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1639. var cw = viewport.width;
  1640. var ch = viewport.height;
  1641. var cx = viewport.x;
  1642. var cy = viewport.y;
  1643. 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);
  1644. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1645. };
  1646. Matrix.Transpose = function (matrix) {
  1647. var result = new Matrix();
  1648. result.m[0] = matrix.m[0];
  1649. result.m[1] = matrix.m[4];
  1650. result.m[2] = matrix.m[8];
  1651. result.m[3] = matrix.m[12];
  1652. result.m[4] = matrix.m[1];
  1653. result.m[5] = matrix.m[5];
  1654. result.m[6] = matrix.m[9];
  1655. result.m[7] = matrix.m[13];
  1656. result.m[8] = matrix.m[2];
  1657. result.m[9] = matrix.m[6];
  1658. result.m[10] = matrix.m[10];
  1659. result.m[11] = matrix.m[14];
  1660. result.m[12] = matrix.m[3];
  1661. result.m[13] = matrix.m[7];
  1662. result.m[14] = matrix.m[11];
  1663. result.m[15] = matrix.m[15];
  1664. return result;
  1665. };
  1666. Matrix.Reflection = function (plane) {
  1667. var matrix = new Matrix();
  1668. Matrix.ReflectionToRef(plane, matrix);
  1669. return matrix;
  1670. };
  1671. Matrix.ReflectionToRef = function (plane, result) {
  1672. plane.normalize();
  1673. var x = plane.normal.x;
  1674. var y = plane.normal.y;
  1675. var z = plane.normal.z;
  1676. var temp = -2 * x;
  1677. var temp2 = -2 * y;
  1678. var temp3 = -2 * z;
  1679. result.m[0] = (temp * x) + 1;
  1680. result.m[1] = temp2 * x;
  1681. result.m[2] = temp3 * x;
  1682. result.m[3] = 0.0;
  1683. result.m[4] = temp * y;
  1684. result.m[5] = (temp2 * y) + 1;
  1685. result.m[6] = temp3 * y;
  1686. result.m[7] = 0.0;
  1687. result.m[8] = temp * z;
  1688. result.m[9] = temp2 * z;
  1689. result.m[10] = (temp3 * z) + 1;
  1690. result.m[11] = 0.0;
  1691. result.m[12] = temp * plane.d;
  1692. result.m[13] = temp2 * plane.d;
  1693. result.m[14] = temp3 * plane.d;
  1694. result.m[15] = 1.0;
  1695. };
  1696. Matrix._tempQuaternion = new Quaternion();
  1697. Matrix._xAxis = Vector3.Zero();
  1698. Matrix._yAxis = Vector3.Zero();
  1699. Matrix._zAxis = Vector3.Zero();
  1700. return Matrix;
  1701. })();
  1702. BABYLON.Matrix = Matrix;
  1703. var Plane = (function () {
  1704. function Plane(a, b, c, d) {
  1705. this.normal = new Vector3(a, b, c);
  1706. this.d = d;
  1707. }
  1708. Plane.prototype.asArray = function () {
  1709. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1710. };
  1711. // Methods
  1712. Plane.prototype.clone = function () {
  1713. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1714. };
  1715. Plane.prototype.normalize = function () {
  1716. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1717. var magnitude = 0;
  1718. if (norm !== 0) {
  1719. magnitude = 1.0 / norm;
  1720. }
  1721. this.normal.x *= magnitude;
  1722. this.normal.y *= magnitude;
  1723. this.normal.z *= magnitude;
  1724. this.d *= magnitude;
  1725. };
  1726. Plane.prototype.transform = function (transformation) {
  1727. var transposedMatrix = Matrix.Transpose(transformation);
  1728. var x = this.normal.x;
  1729. var y = this.normal.y;
  1730. var z = this.normal.z;
  1731. var d = this.d;
  1732. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1733. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1734. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1735. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1736. return new Plane(normalX, normalY, normalZ, finalD);
  1737. };
  1738. Plane.prototype.dotCoordinate = function (point) {
  1739. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1740. };
  1741. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1742. var x1 = point2.x - point1.x;
  1743. var y1 = point2.y - point1.y;
  1744. var z1 = point2.z - point1.z;
  1745. var x2 = point3.x - point1.x;
  1746. var y2 = point3.y - point1.y;
  1747. var z2 = point3.z - point1.z;
  1748. var yz = (y1 * z2) - (z1 * y2);
  1749. var xz = (z1 * x2) - (x1 * z2);
  1750. var xy = (x1 * y2) - (y1 * x2);
  1751. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1752. var invPyth;
  1753. if (pyth !== 0) {
  1754. invPyth = 1.0 / pyth;
  1755. } else {
  1756. invPyth = 0;
  1757. }
  1758. this.normal.x = yz * invPyth;
  1759. this.normal.y = xz * invPyth;
  1760. this.normal.z = xy * invPyth;
  1761. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1762. };
  1763. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1764. var dot = Vector3.Dot(this.normal, direction);
  1765. return (dot <= epsilon);
  1766. };
  1767. Plane.prototype.signedDistanceTo = function (point) {
  1768. return Vector3.Dot(point, this.normal) + this.d;
  1769. };
  1770. // Statics
  1771. Plane.FromArray = function (array) {
  1772. return new Plane(array[0], array[1], array[2], array[3]);
  1773. };
  1774. Plane.FromPoints = function (point1, point2, point3) {
  1775. var result = new Plane(0, 0, 0, 0);
  1776. result.copyFromPoints(point1, point2, point3);
  1777. return result;
  1778. };
  1779. Plane.FromPositionAndNormal = function (origin, normal) {
  1780. var result = new Plane(0, 0, 0, 0);
  1781. normal.normalize();
  1782. result.normal = normal;
  1783. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1784. return result;
  1785. };
  1786. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1787. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1788. return Vector3.Dot(point, normal) + d;
  1789. };
  1790. return Plane;
  1791. })();
  1792. BABYLON.Plane = Plane;
  1793. var Viewport = (function () {
  1794. function Viewport(x, y, width, height) {
  1795. this.x = x;
  1796. this.y = y;
  1797. this.width = width;
  1798. this.height = height;
  1799. }
  1800. Viewport.prototype.toGlobal = function (engine) {
  1801. var width = engine.getRenderWidth();
  1802. var height = engine.getRenderHeight();
  1803. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1804. };
  1805. return Viewport;
  1806. })();
  1807. BABYLON.Viewport = Viewport;
  1808. var Frustum = (function () {
  1809. function Frustum() {
  1810. }
  1811. Frustum.GetPlanes = function (transform) {
  1812. var frustumPlanes = [];
  1813. for (var index = 0; index < 6; index++) {
  1814. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1815. }
  1816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1817. return frustumPlanes;
  1818. };
  1819. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1820. // Near
  1821. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1822. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1823. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1824. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1825. frustumPlanes[0].normalize();
  1826. // Far
  1827. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1828. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1829. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1830. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1831. frustumPlanes[1].normalize();
  1832. // Left
  1833. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1834. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1835. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1836. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1837. frustumPlanes[2].normalize();
  1838. // Right
  1839. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1840. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1841. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1842. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1843. frustumPlanes[3].normalize();
  1844. // Top
  1845. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1846. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1847. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1848. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1849. frustumPlanes[4].normalize();
  1850. // Bottom
  1851. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1852. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1853. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1854. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1855. frustumPlanes[5].normalize();
  1856. };
  1857. return Frustum;
  1858. })();
  1859. BABYLON.Frustum = Frustum;
  1860. var Ray = (function () {
  1861. function Ray(origin, direction, length) {
  1862. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1863. this.origin = origin;
  1864. this.direction = direction;
  1865. this.length = length;
  1866. }
  1867. // Methods
  1868. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1869. var d = 0.0;
  1870. var maxValue = Number.MAX_VALUE;
  1871. if (Math.abs(this.direction.x) < 0.0000001) {
  1872. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1873. return false;
  1874. }
  1875. } else {
  1876. var inv = 1.0 / this.direction.x;
  1877. var min = (minimum.x - this.origin.x) * inv;
  1878. var max = (maximum.x - this.origin.x) * inv;
  1879. if (max === -Infinity) {
  1880. max = Infinity;
  1881. }
  1882. if (min > max) {
  1883. var temp = min;
  1884. min = max;
  1885. max = temp;
  1886. }
  1887. d = Math.max(min, d);
  1888. maxValue = Math.min(max, maxValue);
  1889. if (d > maxValue) {
  1890. return false;
  1891. }
  1892. }
  1893. if (Math.abs(this.direction.y) < 0.0000001) {
  1894. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1895. return false;
  1896. }
  1897. } else {
  1898. inv = 1.0 / this.direction.y;
  1899. min = (minimum.y - this.origin.y) * inv;
  1900. max = (maximum.y - this.origin.y) * inv;
  1901. if (max === -Infinity) {
  1902. max = Infinity;
  1903. }
  1904. if (min > max) {
  1905. temp = min;
  1906. min = max;
  1907. max = temp;
  1908. }
  1909. d = Math.max(min, d);
  1910. maxValue = Math.min(max, maxValue);
  1911. if (d > maxValue) {
  1912. return false;
  1913. }
  1914. }
  1915. if (Math.abs(this.direction.z) < 0.0000001) {
  1916. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1917. return false;
  1918. }
  1919. } else {
  1920. inv = 1.0 / this.direction.z;
  1921. min = (minimum.z - this.origin.z) * inv;
  1922. max = (maximum.z - this.origin.z) * inv;
  1923. if (max === -Infinity) {
  1924. max = Infinity;
  1925. }
  1926. if (min > max) {
  1927. temp = min;
  1928. min = max;
  1929. max = temp;
  1930. }
  1931. d = Math.max(min, d);
  1932. maxValue = Math.min(max, maxValue);
  1933. if (d > maxValue) {
  1934. return false;
  1935. }
  1936. }
  1937. return true;
  1938. };
  1939. Ray.prototype.intersectsBox = function (box) {
  1940. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1941. };
  1942. Ray.prototype.intersectsSphere = function (sphere) {
  1943. var x = sphere.center.x - this.origin.x;
  1944. var y = sphere.center.y - this.origin.y;
  1945. var z = sphere.center.z - this.origin.z;
  1946. var pyth = (x * x) + (y * y) + (z * z);
  1947. var rr = sphere.radius * sphere.radius;
  1948. if (pyth <= rr) {
  1949. return true;
  1950. }
  1951. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1952. if (dot < 0.0) {
  1953. return false;
  1954. }
  1955. var temp = pyth - (dot * dot);
  1956. return temp <= rr;
  1957. };
  1958. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1959. if (!this._edge1) {
  1960. this._edge1 = Vector3.Zero();
  1961. this._edge2 = Vector3.Zero();
  1962. this._pvec = Vector3.Zero();
  1963. this._tvec = Vector3.Zero();
  1964. this._qvec = Vector3.Zero();
  1965. }
  1966. vertex1.subtractToRef(vertex0, this._edge1);
  1967. vertex2.subtractToRef(vertex0, this._edge2);
  1968. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1969. var det = Vector3.Dot(this._edge1, this._pvec);
  1970. if (det === 0) {
  1971. return null;
  1972. }
  1973. var invdet = 1 / det;
  1974. this.origin.subtractToRef(vertex0, this._tvec);
  1975. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1976. if (bu < 0 || bu > 1.0) {
  1977. return null;
  1978. }
  1979. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1980. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1981. if (bv < 0 || bu + bv > 1.0) {
  1982. return null;
  1983. }
  1984. //check if the distance is longer than the predefined length.
  1985. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1986. if (distance > this.length) {
  1987. return null;
  1988. }
  1989. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1990. };
  1991. // Statics
  1992. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1993. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1994. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1995. var direction = end.subtract(start);
  1996. direction.normalize();
  1997. return new Ray(start, direction);
  1998. };
  1999. /**
  2000. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2001. * transformed to the given world matrix.
  2002. * @param origin The origin point
  2003. * @param end The end point
  2004. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2005. */
  2006. Ray.CreateNewFromTo = function (origin, end, world) {
  2007. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2008. var direction = end.subtract(origin);
  2009. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2010. direction.normalize();
  2011. return Ray.Transform(new Ray(origin, direction, length), world);
  2012. };
  2013. Ray.Transform = function (ray, matrix) {
  2014. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2015. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2016. return new Ray(newOrigin, newDirection, ray.length);
  2017. };
  2018. return Ray;
  2019. })();
  2020. BABYLON.Ray = Ray;
  2021. (function (Space) {
  2022. Space[Space["LOCAL"] = 0] = "LOCAL";
  2023. Space[Space["WORLD"] = 1] = "WORLD";
  2024. })(BABYLON.Space || (BABYLON.Space = {}));
  2025. var Space = BABYLON.Space;
  2026. var Axis = (function () {
  2027. function Axis() {
  2028. }
  2029. Axis.X = new Vector3(1, 0, 0);
  2030. Axis.Y = new Vector3(0, 1, 0);
  2031. Axis.Z = new Vector3(0, 0, 1);
  2032. return Axis;
  2033. })();
  2034. BABYLON.Axis = Axis;
  2035. ;
  2036. var BezierCurve = (function () {
  2037. function BezierCurve() {
  2038. }
  2039. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2040. // Extract X (which is equal to time here)
  2041. var f0 = 1 - 3 * x2 + 3 * x1;
  2042. var f1 = 3 * x2 - 6 * x1;
  2043. var f2 = 3 * x1;
  2044. var refinedT = t;
  2045. for (var i = 0; i < 5; i++) {
  2046. var refinedT2 = refinedT * refinedT;
  2047. var refinedT3 = refinedT2 * refinedT;
  2048. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2049. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2050. refinedT -= (x - t) * slope;
  2051. refinedT = Math.min(1, Math.max(0, refinedT));
  2052. }
  2053. // Resolve cubic bezier for the given x
  2054. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2055. };
  2056. return BezierCurve;
  2057. })();
  2058. BABYLON.BezierCurve = BezierCurve;
  2059. (function (Orientation) {
  2060. Orientation[Orientation["CW"] = 0] = "CW";
  2061. Orientation[Orientation["CCW"] = 1] = "CCW";
  2062. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2063. var Orientation = BABYLON.Orientation;
  2064. var Angle = (function () {
  2065. function Angle(radians) {
  2066. var _this = this;
  2067. this.degrees = function () {
  2068. return _this._radians * 180 / Math.PI;
  2069. };
  2070. this.radians = function () {
  2071. return _this._radians;
  2072. };
  2073. this._radians = radians;
  2074. if (this._radians < 0)
  2075. this._radians += (2 * Math.PI);
  2076. }
  2077. Angle.BetweenTwoPoints = function (a, b) {
  2078. var delta = b.subtract(a);
  2079. var theta = Math.atan2(delta.y, delta.x);
  2080. return new Angle(theta);
  2081. };
  2082. Angle.FromRadians = function (radians) {
  2083. return new Angle(radians);
  2084. };
  2085. Angle.FromDegrees = function (degrees) {
  2086. return new Angle(degrees * Math.PI / 180);
  2087. };
  2088. return Angle;
  2089. })();
  2090. BABYLON.Angle = Angle;
  2091. var Arc2 = (function () {
  2092. function Arc2(startPoint, midPoint, endPoint) {
  2093. this.startPoint = startPoint;
  2094. this.midPoint = midPoint;
  2095. this.endPoint = endPoint;
  2096. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2097. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2098. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2099. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2100. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2101. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2102. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2103. var a1 = this.startAngle.degrees();
  2104. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2105. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2106. // angles correction
  2107. if (a2 - a1 > +180.0)
  2108. a2 -= 360.0;
  2109. if (a2 - a1 < -180.0)
  2110. a2 += 360.0;
  2111. if (a3 - a2 > +180.0)
  2112. a3 -= 360.0;
  2113. if (a3 - a2 < -180.0)
  2114. a3 += 360.0;
  2115. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2116. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2117. }
  2118. return Arc2;
  2119. })();
  2120. BABYLON.Arc2 = Arc2;
  2121. var PathCursor = (function () {
  2122. function PathCursor(path) {
  2123. this.path = path;
  2124. this._onchange = new Array();
  2125. this.value = 0;
  2126. this.animations = new Array();
  2127. }
  2128. PathCursor.prototype.getPoint = function () {
  2129. var point = this.path.getPointAtLengthPosition(this.value);
  2130. return new Vector3(point.x, 0, point.y);
  2131. };
  2132. PathCursor.prototype.moveAhead = function (step) {
  2133. if (typeof step === "undefined") { step = 0.002; }
  2134. this.move(step);
  2135. };
  2136. PathCursor.prototype.moveBack = function (step) {
  2137. if (typeof step === "undefined") { step = 0.002; }
  2138. this.move(-step);
  2139. };
  2140. PathCursor.prototype.move = function (step) {
  2141. if (Math.abs(step) > 1) {
  2142. throw "step size should be less than 1.";
  2143. }
  2144. this.value += step;
  2145. this.ensureLimits();
  2146. this.raiseOnChange();
  2147. };
  2148. PathCursor.prototype.ensureLimits = function () {
  2149. while (this.value > 1) {
  2150. this.value -= 1;
  2151. }
  2152. while (this.value < 0) {
  2153. this.value += 1;
  2154. }
  2155. };
  2156. // used by animation engine
  2157. PathCursor.prototype.markAsDirty = function (propertyName) {
  2158. this.ensureLimits();
  2159. this.raiseOnChange();
  2160. };
  2161. PathCursor.prototype.raiseOnChange = function () {
  2162. var _this = this;
  2163. this._onchange.forEach(function (f) {
  2164. return f(_this);
  2165. });
  2166. };
  2167. PathCursor.prototype.onchange = function (f) {
  2168. this._onchange.push(f);
  2169. };
  2170. return PathCursor;
  2171. })();
  2172. BABYLON.PathCursor = PathCursor;
  2173. var Path2 = (function () {
  2174. function Path2(x, y) {
  2175. this._points = [];
  2176. this._length = 0;
  2177. this.closed = false;
  2178. this._points.push(new Vector2(x, y));
  2179. }
  2180. Path2.prototype.addLineTo = function (x, y) {
  2181. if (closed) {
  2182. BABYLON.Tools.Error("cannot add lines to closed paths");
  2183. return this;
  2184. }
  2185. var newPoint = new Vector2(x, y);
  2186. var previousPoint = this._points[this._points.length - 1];
  2187. this._points.push(newPoint);
  2188. this._length += newPoint.subtract(previousPoint).length();
  2189. return this;
  2190. };
  2191. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2192. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2193. if (closed) {
  2194. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2195. return this;
  2196. }
  2197. var startPoint = this._points[this._points.length - 1];
  2198. var midPoint = new Vector2(midX, midY);
  2199. var endPoint = new Vector2(endX, endY);
  2200. var arc = new Arc2(startPoint, midPoint, endPoint);
  2201. var increment = arc.angle.radians() / numberOfSegments;
  2202. if (arc.orientation === 0 /* CW */)
  2203. increment *= -1;
  2204. var currentAngle = arc.startAngle.radians() + increment;
  2205. for (var i = 0; i < numberOfSegments; i++) {
  2206. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2207. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2208. this.addLineTo(x, y);
  2209. currentAngle += increment;
  2210. }
  2211. return this;
  2212. };
  2213. Path2.prototype.close = function () {
  2214. this.closed = true;
  2215. return this;
  2216. };
  2217. Path2.prototype.length = function () {
  2218. var result = this._length;
  2219. if (!this.closed) {
  2220. var lastPoint = this._points[this._points.length - 1];
  2221. var firstPoint = this._points[0];
  2222. result += (firstPoint.subtract(lastPoint).length());
  2223. }
  2224. return result;
  2225. };
  2226. Path2.prototype.getPoints = function () {
  2227. return this._points;
  2228. };
  2229. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2230. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2231. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2232. return;
  2233. }
  2234. var lengthPosition = normalizedLengthPosition * this.length();
  2235. var previousOffset = 0;
  2236. for (var i = 0; i < this._points.length; i++) {
  2237. var j = (i + 1) % this._points.length;
  2238. var a = this._points[i];
  2239. var b = this._points[j];
  2240. var bToA = b.subtract(a);
  2241. var nextOffset = (bToA.length() + previousOffset);
  2242. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2243. var dir = bToA.normalize();
  2244. var localOffset = lengthPosition - previousOffset;
  2245. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2246. }
  2247. previousOffset = nextOffset;
  2248. }
  2249. BABYLON.Tools.Error("internal error");
  2250. };
  2251. Path2.StartingAt = function (x, y) {
  2252. return new Path2(x, y);
  2253. };
  2254. return Path2;
  2255. })();
  2256. BABYLON.Path2 = Path2;
  2257. })(BABYLON || (BABYLON = {}));
  2258. //# sourceMappingURL=babylon.math.js.map
  2259. var BABYLON;
  2260. (function (BABYLON) {
  2261. // Screenshots
  2262. var screenshotCanvas;
  2263. var cloneValue = function (source, destinationObject) {
  2264. if (!source)
  2265. return null;
  2266. if (source instanceof BABYLON.Mesh) {
  2267. return null;
  2268. }
  2269. if (source instanceof BABYLON.SubMesh) {
  2270. return source.clone(destinationObject);
  2271. } else if (source.clone) {
  2272. return source.clone();
  2273. }
  2274. return null;
  2275. };
  2276. var Tools = (function () {
  2277. function Tools() {
  2278. }
  2279. Tools.GetFilename = function (path) {
  2280. var index = path.lastIndexOf("/");
  2281. if (index < 0)
  2282. return path;
  2283. return path.substring(index + 1);
  2284. };
  2285. Tools.GetDOMTextContent = function (element) {
  2286. var result = "";
  2287. var child = element.firstChild;
  2288. while (child) {
  2289. if (child.nodeType == 3) {
  2290. result += child.textContent;
  2291. }
  2292. child = child.nextSibling;
  2293. }
  2294. return result;
  2295. };
  2296. Tools.ToDegrees = function (angle) {
  2297. return angle * 180 / Math.PI;
  2298. };
  2299. Tools.ToRadians = function (angle) {
  2300. return angle * Math.PI / 180;
  2301. };
  2302. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2303. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2304. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2305. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2306. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2307. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2308. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2309. }
  2310. return {
  2311. minimum: minimum,
  2312. maximum: maximum
  2313. };
  2314. };
  2315. Tools.ExtractMinAndMax = function (positions, start, count) {
  2316. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2317. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2318. for (var index = start; index < start + count; index++) {
  2319. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2320. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2321. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2322. }
  2323. return {
  2324. minimum: minimum,
  2325. maximum: maximum
  2326. };
  2327. };
  2328. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2329. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2330. return undefined;
  2331. return Array.isArray(obj) ? obj : [obj];
  2332. };
  2333. // Misc.
  2334. Tools.GetPointerPrefix = function () {
  2335. var eventPrefix = "pointer";
  2336. // Check if hand.js is referenced or if the browser natively supports pointer events
  2337. if (!navigator.pointerEnabled) {
  2338. eventPrefix = "mouse";
  2339. }
  2340. return eventPrefix;
  2341. };
  2342. Tools.QueueNewFrame = function (func) {
  2343. if (window.requestAnimationFrame)
  2344. window.requestAnimationFrame(func);
  2345. else if (window.msRequestAnimationFrame)
  2346. window.msRequestAnimationFrame(func);
  2347. else if (window.webkitRequestAnimationFrame)
  2348. window.webkitRequestAnimationFrame(func);
  2349. else if (window.mozRequestAnimationFrame)
  2350. window.mozRequestAnimationFrame(func);
  2351. else if (window.oRequestAnimationFrame)
  2352. window.oRequestAnimationFrame(func);
  2353. else {
  2354. window.setTimeout(func, 16);
  2355. }
  2356. };
  2357. Tools.RequestFullscreen = function (element) {
  2358. if (element.requestFullscreen)
  2359. element.requestFullscreen();
  2360. else if (element.msRequestFullscreen)
  2361. element.msRequestFullscreen();
  2362. else if (element.webkitRequestFullscreen)
  2363. element.webkitRequestFullscreen();
  2364. else if (element.mozRequestFullScreen)
  2365. element.mozRequestFullScreen();
  2366. };
  2367. Tools.ExitFullscreen = function () {
  2368. if (document.exitFullscreen) {
  2369. document.exitFullscreen();
  2370. } else if (document.mozCancelFullScreen) {
  2371. document.mozCancelFullScreen();
  2372. } else if (document.webkitCancelFullScreen) {
  2373. document.webkitCancelFullScreen();
  2374. } else if (document.msCancelFullScreen) {
  2375. document.msCancelFullScreen();
  2376. }
  2377. };
  2378. // External files
  2379. Tools.CleanUrl = function (url) {
  2380. url = url.replace(/#/mg, "%23");
  2381. return url;
  2382. };
  2383. Tools.LoadImage = function (url, onload, onerror, database) {
  2384. url = Tools.CleanUrl(url);
  2385. var img = new Image();
  2386. if (url.substr(0, 5) != "data:")
  2387. img.crossOrigin = 'anonymous';
  2388. img.onload = function () {
  2389. onload(img);
  2390. };
  2391. img.onerror = function (err) {
  2392. onerror(img, err);
  2393. };
  2394. var noIndexedDB = function () {
  2395. img.src = url;
  2396. };
  2397. var loadFromIndexedDB = function () {
  2398. database.loadImageFromDB(url, img);
  2399. };
  2400. //ANY database to do!
  2401. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2402. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2403. } else {
  2404. if (url.indexOf("file:") === -1) {
  2405. noIndexedDB();
  2406. } else {
  2407. try {
  2408. var textureName = url.substring(5);
  2409. var blobURL;
  2410. try {
  2411. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2412. } catch (ex) {
  2413. // Chrome doesn't support oneTimeOnly parameter
  2414. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2415. }
  2416. img.src = blobURL;
  2417. } catch (e) {
  2418. Tools.Log("Error while trying to load texture: " + textureName);
  2419. img.src = null;
  2420. }
  2421. }
  2422. }
  2423. return img;
  2424. };
  2425. //ANY
  2426. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2427. url = Tools.CleanUrl(url);
  2428. var noIndexedDB = function () {
  2429. var request = new XMLHttpRequest();
  2430. var loadUrl = Tools.BaseUrl + url;
  2431. request.open('GET', loadUrl, true);
  2432. if (useArrayBuffer) {
  2433. request.responseType = "arraybuffer";
  2434. }
  2435. request.onprogress = progressCallBack;
  2436. request.onreadystatechange = function () {
  2437. if (request.readyState == 4) {
  2438. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2439. callback(!useArrayBuffer ? request.responseText : request.response);
  2440. } else {
  2441. if (onError) {
  2442. onError();
  2443. } else {
  2444. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2445. }
  2446. }
  2447. }
  2448. };
  2449. request.send(null);
  2450. };
  2451. var loadFromIndexedDB = function () {
  2452. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2453. };
  2454. if (url.indexOf("file:") !== -1) {
  2455. var fileName = url.substring(5);
  2456. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2457. } else {
  2458. // Caching all files
  2459. if (database && database.enableSceneOffline) {
  2460. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2461. } else {
  2462. noIndexedDB();
  2463. }
  2464. }
  2465. };
  2466. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2467. var reader = new FileReader();
  2468. reader.onload = function (e) {
  2469. callback(e.target.result);
  2470. };
  2471. reader.onprogress = progressCallback;
  2472. reader.readAsDataURL(fileToLoad);
  2473. };
  2474. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2475. var reader = new FileReader();
  2476. reader.onload = function (e) {
  2477. callback(e.target.result);
  2478. };
  2479. reader.onprogress = progressCallBack;
  2480. if (!useArrayBuffer) {
  2481. // Asynchronous read
  2482. reader.readAsText(fileToLoad);
  2483. } else {
  2484. reader.readAsArrayBuffer(fileToLoad);
  2485. }
  2486. };
  2487. // Misc.
  2488. Tools.Clamp = function (value, min, max) {
  2489. if (typeof min === "undefined") { min = 0; }
  2490. if (typeof max === "undefined") { max = 1; }
  2491. return Math.min(max, Math.max(min, value));
  2492. };
  2493. Tools.Format = function (value, decimals) {
  2494. if (typeof decimals === "undefined") { decimals = 2; }
  2495. return value.toFixed(decimals);
  2496. };
  2497. Tools.CheckExtends = function (v, min, max) {
  2498. if (v.x < min.x)
  2499. min.x = v.x;
  2500. if (v.y < min.y)
  2501. min.y = v.y;
  2502. if (v.z < min.z)
  2503. min.z = v.z;
  2504. if (v.x > max.x)
  2505. max.x = v.x;
  2506. if (v.y > max.y)
  2507. max.y = v.y;
  2508. if (v.z > max.z)
  2509. max.z = v.z;
  2510. };
  2511. Tools.WithinEpsilon = function (a, b) {
  2512. var num = a - b;
  2513. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2514. };
  2515. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2516. for (var prop in source) {
  2517. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2518. continue;
  2519. }
  2520. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2521. continue;
  2522. }
  2523. var sourceValue = source[prop];
  2524. var typeOfSourceValue = typeof sourceValue;
  2525. if (typeOfSourceValue == "function") {
  2526. continue;
  2527. }
  2528. if (typeOfSourceValue == "object") {
  2529. if (sourceValue instanceof Array) {
  2530. destination[prop] = [];
  2531. if (sourceValue.length > 0) {
  2532. if (typeof sourceValue[0] == "object") {
  2533. for (var index = 0; index < sourceValue.length; index++) {
  2534. var clonedValue = cloneValue(sourceValue[index], destination);
  2535. if (destination[prop].indexOf(clonedValue) === -1) {
  2536. destination[prop].push(clonedValue);
  2537. }
  2538. }
  2539. } else {
  2540. destination[prop] = sourceValue.slice(0);
  2541. }
  2542. }
  2543. } else {
  2544. destination[prop] = cloneValue(sourceValue, destination);
  2545. }
  2546. } else {
  2547. destination[prop] = sourceValue;
  2548. }
  2549. }
  2550. };
  2551. Tools.IsEmpty = function (obj) {
  2552. for (var i in obj) {
  2553. return false;
  2554. }
  2555. return true;
  2556. };
  2557. Tools.RegisterTopRootEvents = function (events) {
  2558. for (var index = 0; index < events.length; index++) {
  2559. var event = events[index];
  2560. window.addEventListener(event.name, event.handler, false);
  2561. try {
  2562. if (window.parent) {
  2563. window.parent.addEventListener(event.name, event.handler, false);
  2564. }
  2565. } catch (e) {
  2566. // Silently fails...
  2567. }
  2568. }
  2569. };
  2570. Tools.UnregisterTopRootEvents = function (events) {
  2571. for (var index = 0; index < events.length; index++) {
  2572. var event = events[index];
  2573. window.removeEventListener(event.name, event.handler);
  2574. try {
  2575. if (window.parent) {
  2576. window.parent.removeEventListener(event.name, event.handler);
  2577. }
  2578. } catch (e) {
  2579. // Silently fails...
  2580. }
  2581. }
  2582. };
  2583. Tools.CreateScreenshot = function (engine, camera, size) {
  2584. var width;
  2585. var height;
  2586. var scene = camera.getScene();
  2587. var previousCamera = null;
  2588. if (scene.activeCamera !== camera) {
  2589. previousCamera = scene.activeCamera;
  2590. scene.activeCamera = camera;
  2591. }
  2592. //If a precision value is specified
  2593. if (size.precision) {
  2594. width = Math.round(engine.getRenderWidth() * size.precision);
  2595. height = Math.round(width / engine.getAspectRatio(camera));
  2596. size = { width: width, height: height };
  2597. } else if (size.width && size.height) {
  2598. width = size.width;
  2599. height = size.height;
  2600. } else if (size.width && !size.height) {
  2601. width = size.width;
  2602. height = Math.round(width / engine.getAspectRatio(camera));
  2603. size = { width: width, height: height };
  2604. } else if (size.height && !size.width) {
  2605. height = size.height;
  2606. width = Math.round(height * engine.getAspectRatio(camera));
  2607. size = { width: width, height: height };
  2608. } else if (!isNaN(size)) {
  2609. height = size;
  2610. width = size;
  2611. } else {
  2612. Tools.Error("Invalid 'size' parameter !");
  2613. return;
  2614. }
  2615. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2616. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2617. texture.renderList = engine.scenes[0].meshes;
  2618. texture.onAfterRender = function () {
  2619. // Read the contents of the framebuffer
  2620. var numberOfChannelsByLine = width * 4;
  2621. var halfHeight = height / 2;
  2622. //Reading datas from WebGL
  2623. var data = engine.readPixels(0, 0, width, height);
  2624. for (var i = 0; i < halfHeight; i++) {
  2625. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2626. var currentCell = j + i * numberOfChannelsByLine;
  2627. var targetLine = height - i - 1;
  2628. var targetCell = j + targetLine * numberOfChannelsByLine;
  2629. var temp = data[currentCell];
  2630. data[currentCell] = data[targetCell];
  2631. data[targetCell] = temp;
  2632. }
  2633. }
  2634. // Create a 2D canvas to store the result
  2635. if (!screenshotCanvas) {
  2636. screenshotCanvas = document.createElement('canvas');
  2637. }
  2638. screenshotCanvas.width = width;
  2639. screenshotCanvas.height = height;
  2640. var context = screenshotCanvas.getContext('2d');
  2641. // Copy the pixels to a 2D canvas
  2642. var imageData = context.createImageData(width, height);
  2643. imageData.data.set(data);
  2644. context.putImageData(imageData, 0, 0);
  2645. var base64Image = screenshotCanvas.toDataURL();
  2646. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2647. if (("download" in document.createElement("a"))) {
  2648. var a = window.document.createElement("a");
  2649. a.href = base64Image;
  2650. var date = new Date();
  2651. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2652. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2653. window.document.body.appendChild(a);
  2654. a.addEventListener("click", function () {
  2655. a.parentElement.removeChild(a);
  2656. });
  2657. a.click();
  2658. //Or opening a new tab with the image if it is not possible to automatically start download.
  2659. } else {
  2660. var newWindow = window.open("");
  2661. var img = newWindow.document.createElement("img");
  2662. img.src = base64Image;
  2663. newWindow.document.body.appendChild(img);
  2664. }
  2665. };
  2666. texture.render(true);
  2667. texture.dispose();
  2668. if (previousCamera) {
  2669. scene.activeCamera = previousCamera;
  2670. }
  2671. };
  2672. // XHR response validator for local file scenario
  2673. Tools.ValidateXHRData = function (xhr, dataType) {
  2674. if (typeof dataType === "undefined") { dataType = 7; }
  2675. try {
  2676. if (dataType & 1) {
  2677. if (xhr.responseText && xhr.responseText.length > 0) {
  2678. return true;
  2679. } else if (dataType === 1) {
  2680. return false;
  2681. }
  2682. }
  2683. if (dataType & 2) {
  2684. // Check header width and height since there is no "TGA" magic number
  2685. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2686. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2687. return true;
  2688. } else if (dataType === 2) {
  2689. return false;
  2690. }
  2691. }
  2692. if (dataType & 4) {
  2693. // Check for the "DDS" magic number
  2694. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2695. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2696. return true;
  2697. } else {
  2698. return false;
  2699. }
  2700. }
  2701. } catch (e) {
  2702. // Global protection
  2703. }
  2704. return false;
  2705. };
  2706. Object.defineProperty(Tools, "NoneLogLevel", {
  2707. get: function () {
  2708. return Tools._NoneLogLevel;
  2709. },
  2710. enumerable: true,
  2711. configurable: true
  2712. });
  2713. Object.defineProperty(Tools, "MessageLogLevel", {
  2714. get: function () {
  2715. return Tools._MessageLogLevel;
  2716. },
  2717. enumerable: true,
  2718. configurable: true
  2719. });
  2720. Object.defineProperty(Tools, "WarningLogLevel", {
  2721. get: function () {
  2722. return Tools._WarningLogLevel;
  2723. },
  2724. enumerable: true,
  2725. configurable: true
  2726. });
  2727. Object.defineProperty(Tools, "ErrorLogLevel", {
  2728. get: function () {
  2729. return Tools._ErrorLogLevel;
  2730. },
  2731. enumerable: true,
  2732. configurable: true
  2733. });
  2734. Object.defineProperty(Tools, "AllLogLevel", {
  2735. get: function () {
  2736. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2737. },
  2738. enumerable: true,
  2739. configurable: true
  2740. });
  2741. Tools._AddLogEntry = function (entry) {
  2742. Tools._LogCache = entry + Tools._LogCache;
  2743. if (Tools.OnNewCacheEntry) {
  2744. Tools.OnNewCacheEntry(entry);
  2745. }
  2746. };
  2747. Tools._FormatMessage = function (message) {
  2748. var padStr = function (i) {
  2749. return (i < 10) ? "0" + i : "" + i;
  2750. };
  2751. var date = new Date();
  2752. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2753. };
  2754. Tools._LogDisabled = function (message) {
  2755. // nothing to do
  2756. };
  2757. Tools._LogEnabled = function (message) {
  2758. var formattedMessage = Tools._FormatMessage(message);
  2759. console.log("BJS - " + formattedMessage);
  2760. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2761. Tools._AddLogEntry(entry);
  2762. };
  2763. Tools._WarnDisabled = function (message) {
  2764. // nothing to do
  2765. };
  2766. Tools._WarnEnabled = function (message) {
  2767. var formattedMessage = Tools._FormatMessage(message);
  2768. console.warn("BJS - " + formattedMessage);
  2769. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2770. Tools._AddLogEntry(entry);
  2771. };
  2772. Tools._ErrorDisabled = function (message) {
  2773. // nothing to do
  2774. };
  2775. Tools._ErrorEnabled = function (message) {
  2776. var formattedMessage = Tools._FormatMessage(message);
  2777. console.error("BJS - " + formattedMessage);
  2778. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2779. Tools._AddLogEntry(entry);
  2780. };
  2781. Object.defineProperty(Tools, "LogCache", {
  2782. get: function () {
  2783. return Tools._LogCache;
  2784. },
  2785. enumerable: true,
  2786. configurable: true
  2787. });
  2788. Object.defineProperty(Tools, "LogLevels", {
  2789. set: function (level) {
  2790. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2791. Tools.Log = Tools._LogEnabled;
  2792. } else {
  2793. Tools.Log = Tools._LogDisabled;
  2794. }
  2795. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2796. Tools.Warn = Tools._WarnEnabled;
  2797. } else {
  2798. Tools.Warn = Tools._WarnDisabled;
  2799. }
  2800. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2801. Tools.Error = Tools._ErrorEnabled;
  2802. } else {
  2803. Tools.Error = Tools._ErrorDisabled;
  2804. }
  2805. },
  2806. enumerable: true,
  2807. configurable: true
  2808. });
  2809. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2810. get: function () {
  2811. return Tools._PerformanceNoneLogLevel;
  2812. },
  2813. enumerable: true,
  2814. configurable: true
  2815. });
  2816. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2817. get: function () {
  2818. return Tools._PerformanceUserMarkLogLevel;
  2819. },
  2820. enumerable: true,
  2821. configurable: true
  2822. });
  2823. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2824. get: function () {
  2825. return Tools._PerformanceConsoleLogLevel;
  2826. },
  2827. enumerable: true,
  2828. configurable: true
  2829. });
  2830. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2831. set: function (level) {
  2832. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2833. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2834. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2835. return;
  2836. }
  2837. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2838. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2839. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2840. return;
  2841. }
  2842. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2843. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2844. },
  2845. enumerable: true,
  2846. configurable: true
  2847. });
  2848. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2849. };
  2850. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2851. };
  2852. Tools._StartUserMark = function (counterName, condition) {
  2853. if (typeof condition === "undefined") { condition = true; }
  2854. if (!condition || !Tools._performance.mark) {
  2855. return;
  2856. }
  2857. Tools._performance.mark(counterName + "-Begin");
  2858. };
  2859. Tools._EndUserMark = function (counterName, condition) {
  2860. if (typeof condition === "undefined") { condition = true; }
  2861. if (!condition || !Tools._performance.mark) {
  2862. return;
  2863. }
  2864. Tools._performance.mark(counterName + "-End");
  2865. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2866. };
  2867. Tools._StartPerformanceConsole = function (counterName, condition) {
  2868. if (typeof condition === "undefined") { condition = true; }
  2869. if (!condition) {
  2870. return;
  2871. }
  2872. Tools._StartUserMark(counterName, condition);
  2873. if (console.time) {
  2874. console.time(counterName);
  2875. }
  2876. };
  2877. Tools._EndPerformanceConsole = function (counterName, condition) {
  2878. if (typeof condition === "undefined") { condition = true; }
  2879. if (!condition) {
  2880. return;
  2881. }
  2882. Tools._EndUserMark(counterName, condition);
  2883. if (console.time) {
  2884. console.timeEnd(counterName);
  2885. }
  2886. };
  2887. Object.defineProperty(Tools, "Now", {
  2888. get: function () {
  2889. if (window.performance && window.performance.now) {
  2890. return window.performance.now();
  2891. }
  2892. return new Date().getTime();
  2893. },
  2894. enumerable: true,
  2895. configurable: true
  2896. });
  2897. // Deprecated
  2898. Tools.GetFps = function () {
  2899. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2900. return 0;
  2901. };
  2902. Tools.BaseUrl = "";
  2903. Tools.GetExponantOfTwo = function (value, max) {
  2904. var count = 1;
  2905. do {
  2906. count *= 2;
  2907. } while(count < value);
  2908. if (count > max)
  2909. count = max;
  2910. return count;
  2911. };
  2912. Tools._NoneLogLevel = 0;
  2913. Tools._MessageLogLevel = 1;
  2914. Tools._WarningLogLevel = 2;
  2915. Tools._ErrorLogLevel = 4;
  2916. Tools._LogCache = "";
  2917. Tools.Log = Tools._LogEnabled;
  2918. Tools.Warn = Tools._WarnEnabled;
  2919. Tools.Error = Tools._ErrorEnabled;
  2920. Tools._PerformanceNoneLogLevel = 0;
  2921. Tools._PerformanceUserMarkLogLevel = 1;
  2922. Tools._PerformanceConsoleLogLevel = 2;
  2923. Tools._performance = window.performance;
  2924. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2925. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2926. return Tools;
  2927. })();
  2928. BABYLON.Tools = Tools;
  2929. })(BABYLON || (BABYLON = {}));
  2930. //# sourceMappingURL=babylon.tools.js.map
  2931. var BABYLON;
  2932. (function (BABYLON) {
  2933. var _DepthCullingState = (function () {
  2934. function _DepthCullingState() {
  2935. this._isDepthTestDirty = false;
  2936. this._isDepthMaskDirty = false;
  2937. this._isDepthFuncDirty = false;
  2938. this._isCullFaceDirty = false;
  2939. this._isCullDirty = false;
  2940. }
  2941. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2942. get: function () {
  2943. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2944. },
  2945. enumerable: true,
  2946. configurable: true
  2947. });
  2948. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2949. get: function () {
  2950. return this._cullFace;
  2951. },
  2952. set: function (value) {
  2953. if (this._cullFace === value) {
  2954. return;
  2955. }
  2956. this._cullFace = value;
  2957. this._isCullFaceDirty = true;
  2958. },
  2959. enumerable: true,
  2960. configurable: true
  2961. });
  2962. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2963. get: function () {
  2964. return this._cull;
  2965. },
  2966. set: function (value) {
  2967. if (this._cull === value) {
  2968. return;
  2969. }
  2970. this._cull = value;
  2971. this._isCullDirty = true;
  2972. },
  2973. enumerable: true,
  2974. configurable: true
  2975. });
  2976. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2977. get: function () {
  2978. return this._depthFunc;
  2979. },
  2980. set: function (value) {
  2981. if (this._depthFunc === value) {
  2982. return;
  2983. }
  2984. this._depthFunc = value;
  2985. this._isDepthFuncDirty = true;
  2986. },
  2987. enumerable: true,
  2988. configurable: true
  2989. });
  2990. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2991. get: function () {
  2992. return this._depthMask;
  2993. },
  2994. set: function (value) {
  2995. if (this._depthMask === value) {
  2996. return;
  2997. }
  2998. this._depthMask = value;
  2999. this._isDepthMaskDirty = true;
  3000. },
  3001. enumerable: true,
  3002. configurable: true
  3003. });
  3004. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3005. get: function () {
  3006. return this._depthTest;
  3007. },
  3008. set: function (value) {
  3009. if (this._depthTest === value) {
  3010. return;
  3011. }
  3012. this._depthTest = value;
  3013. this._isDepthTestDirty = true;
  3014. },
  3015. enumerable: true,
  3016. configurable: true
  3017. });
  3018. _DepthCullingState.prototype.reset = function () {
  3019. this._depthMask = true;
  3020. this._depthTest = true;
  3021. this._depthFunc = null;
  3022. this._cull = null;
  3023. this._cullFace = null;
  3024. this._isDepthTestDirty = true;
  3025. this._isDepthMaskDirty = true;
  3026. this._isDepthFuncDirty = false;
  3027. this._isCullFaceDirty = false;
  3028. this._isCullDirty = false;
  3029. };
  3030. _DepthCullingState.prototype.apply = function (gl) {
  3031. if (!this.isDirty) {
  3032. return;
  3033. }
  3034. // Cull
  3035. if (this._isCullDirty) {
  3036. if (this.cull === true) {
  3037. gl.enable(gl.CULL_FACE);
  3038. } else if (this.cull === false) {
  3039. gl.disable(gl.CULL_FACE);
  3040. }
  3041. this._isCullDirty = false;
  3042. }
  3043. // Cull face
  3044. if (this._isCullFaceDirty) {
  3045. gl.cullFace(this.cullFace);
  3046. this._isCullFaceDirty = false;
  3047. }
  3048. // Depth mask
  3049. if (this._isDepthMaskDirty) {
  3050. gl.depthMask(this.depthMask);
  3051. this._isDepthMaskDirty = false;
  3052. }
  3053. // Depth test
  3054. if (this._isDepthTestDirty) {
  3055. if (this.depthTest === true) {
  3056. gl.enable(gl.DEPTH_TEST);
  3057. } else if (this.depthTest === false) {
  3058. gl.disable(gl.DEPTH_TEST);
  3059. }
  3060. this._isDepthTestDirty = false;
  3061. }
  3062. // Depth func
  3063. if (this._isDepthFuncDirty) {
  3064. gl.depthFunc(this.depthFunc);
  3065. this._isDepthFuncDirty = false;
  3066. }
  3067. };
  3068. return _DepthCullingState;
  3069. })();
  3070. BABYLON._DepthCullingState = _DepthCullingState;
  3071. var _AlphaState = (function () {
  3072. function _AlphaState() {
  3073. this._isAlphaBlendDirty = false;
  3074. this._isBlendFunctionParametersDirty = false;
  3075. this._alphaBlend = false;
  3076. this._blendFunctionParameters = new Array(4);
  3077. }
  3078. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3079. get: function () {
  3080. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3081. },
  3082. enumerable: true,
  3083. configurable: true
  3084. });
  3085. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3086. get: function () {
  3087. return this._alphaBlend;
  3088. },
  3089. set: function (value) {
  3090. if (this._alphaBlend === value) {
  3091. return;
  3092. }
  3093. this._alphaBlend = value;
  3094. this._isAlphaBlendDirty = true;
  3095. },
  3096. enumerable: true,
  3097. configurable: true
  3098. });
  3099. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3100. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3101. return;
  3102. }
  3103. this._blendFunctionParameters[0] = value0;
  3104. this._blendFunctionParameters[1] = value1;
  3105. this._blendFunctionParameters[2] = value2;
  3106. this._blendFunctionParameters[3] = value3;
  3107. this._isBlendFunctionParametersDirty = true;
  3108. };
  3109. _AlphaState.prototype.reset = function () {
  3110. this._alphaBlend = false;
  3111. this._blendFunctionParameters[0] = null;
  3112. this._blendFunctionParameters[1] = null;
  3113. this._blendFunctionParameters[2] = null;
  3114. this._blendFunctionParameters[3] = null;
  3115. this._isAlphaBlendDirty = true;
  3116. this._isBlendFunctionParametersDirty = false;
  3117. };
  3118. _AlphaState.prototype.apply = function (gl) {
  3119. if (!this.isDirty) {
  3120. return;
  3121. }
  3122. // Alpha blend
  3123. if (this._isAlphaBlendDirty) {
  3124. if (this._alphaBlend === true) {
  3125. gl.enable(gl.BLEND);
  3126. } else if (this._alphaBlend === false) {
  3127. gl.disable(gl.BLEND);
  3128. }
  3129. this._isAlphaBlendDirty = false;
  3130. }
  3131. // Alpha function
  3132. if (this._isBlendFunctionParametersDirty) {
  3133. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3134. this._isBlendFunctionParametersDirty = false;
  3135. }
  3136. };
  3137. return _AlphaState;
  3138. })();
  3139. BABYLON._AlphaState = _AlphaState;
  3140. var compileShader = function (gl, source, type, defines) {
  3141. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3142. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3143. gl.compileShader(shader);
  3144. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3145. throw new Error(gl.getShaderInfoLog(shader));
  3146. }
  3147. return shader;
  3148. };
  3149. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3150. var magFilter = gl.NEAREST;
  3151. var minFilter = gl.NEAREST;
  3152. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3153. magFilter = gl.LINEAR;
  3154. if (generateMipMaps) {
  3155. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3156. } else {
  3157. minFilter = gl.LINEAR;
  3158. }
  3159. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3160. magFilter = gl.LINEAR;
  3161. if (generateMipMaps) {
  3162. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3163. } else {
  3164. minFilter = gl.LINEAR;
  3165. }
  3166. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3167. magFilter = gl.NEAREST;
  3168. if (generateMipMaps) {
  3169. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3170. } else {
  3171. minFilter = gl.NEAREST;
  3172. }
  3173. }
  3174. return {
  3175. min: minFilter,
  3176. mag: magFilter
  3177. };
  3178. };
  3179. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3180. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3181. var engine = scene.getEngine();
  3182. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3183. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3184. gl.bindTexture(gl.TEXTURE_2D, texture);
  3185. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3186. processFunction(potWidth, potHeight);
  3187. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3190. if (!noMipmap && !isCompressed) {
  3191. gl.generateMipmap(gl.TEXTURE_2D);
  3192. }
  3193. gl.bindTexture(gl.TEXTURE_2D, null);
  3194. engine._activeTexturesCache = [];
  3195. texture._baseWidth = width;
  3196. texture._baseHeight = height;
  3197. texture._width = potWidth;
  3198. texture._height = potHeight;
  3199. texture.isReady = true;
  3200. texture.samplingMode = samplingMode;
  3201. scene._removePendingData(texture);
  3202. };
  3203. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3204. var img;
  3205. var onload = function () {
  3206. loadedImages[index] = img;
  3207. loadedImages._internalCount++;
  3208. scene._removePendingData(img);
  3209. if (loadedImages._internalCount == 6) {
  3210. onfinish(loadedImages);
  3211. }
  3212. };
  3213. var onerror = function () {
  3214. scene._removePendingData(img);
  3215. };
  3216. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3217. scene._addPendingData(img);
  3218. };
  3219. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3220. var loadedImages = [];
  3221. loadedImages._internalCount = 0;
  3222. for (var index = 0; index < 6; index++) {
  3223. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3224. }
  3225. };
  3226. var EngineCapabilities = (function () {
  3227. function EngineCapabilities() {
  3228. }
  3229. return EngineCapabilities;
  3230. })();
  3231. BABYLON.EngineCapabilities = EngineCapabilities;
  3232. var Engine = (function () {
  3233. function Engine(canvas, antialias, options) {
  3234. var _this = this;
  3235. // Public members
  3236. this.isFullscreen = false;
  3237. this.isPointerLock = false;
  3238. this.cullBackFaces = true;
  3239. this.renderEvenInBackground = true;
  3240. this.scenes = new Array();
  3241. this._windowIsBackground = false;
  3242. this._loadingDivBackgroundColor = "black";
  3243. this._drawCalls = 0;
  3244. this._renderingQueueLaunched = false;
  3245. this._activeRenderLoops = [];
  3246. // FPS
  3247. this.fpsRange = 60;
  3248. this.previousFramesDuration = [];
  3249. this.fps = 60;
  3250. this.deltaTime = 0;
  3251. // States
  3252. this._depthCullingState = new _DepthCullingState();
  3253. this._alphaState = new _AlphaState();
  3254. this._alphaMode = Engine.ALPHA_DISABLE;
  3255. // Cache
  3256. this._loadedTexturesCache = new Array();
  3257. this._activeTexturesCache = new Array();
  3258. this._compiledEffects = {};
  3259. this._uintIndicesCurrentlySet = false;
  3260. this._renderingCanvas = canvas;
  3261. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3262. options = options || {};
  3263. options.antialias = antialias;
  3264. try {
  3265. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3266. } catch (e) {
  3267. throw new Error("WebGL not supported");
  3268. }
  3269. if (!this._gl) {
  3270. throw new Error("WebGL not supported");
  3271. }
  3272. this._onBlur = function () {
  3273. _this._windowIsBackground = true;
  3274. };
  3275. this._onFocus = function () {
  3276. _this._windowIsBackground = false;
  3277. };
  3278. window.addEventListener("blur", this._onBlur);
  3279. window.addEventListener("focus", this._onFocus);
  3280. // Textures
  3281. this._workingCanvas = document.createElement("canvas");
  3282. this._workingContext = this._workingCanvas.getContext("2d");
  3283. // Viewport
  3284. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3285. this.resize();
  3286. // Caps
  3287. this._caps = new EngineCapabilities();
  3288. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3289. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3290. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3291. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3292. // Extensions
  3293. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3294. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3295. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3296. 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');
  3297. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3298. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3299. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3300. // Depth buffer
  3301. this.setDepthBuffer(true);
  3302. this.setDepthFunctionToLessOrEqual();
  3303. this.setDepthWrite(true);
  3304. // Fullscreen
  3305. this._onFullscreenChange = function () {
  3306. if (document.fullscreen !== undefined) {
  3307. _this.isFullscreen = document.fullscreen;
  3308. } else if (document.mozFullScreen !== undefined) {
  3309. _this.isFullscreen = document.mozFullScreen;
  3310. } else if (document.webkitIsFullScreen !== undefined) {
  3311. _this.isFullscreen = document.webkitIsFullScreen;
  3312. } else if (document.msIsFullScreen !== undefined) {
  3313. _this.isFullscreen = document.msIsFullScreen;
  3314. }
  3315. // Pointer lock
  3316. if (_this.isFullscreen && _this._pointerLockRequested) {
  3317. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3318. if (canvas.requestPointerLock) {
  3319. canvas.requestPointerLock();
  3320. }
  3321. }
  3322. };
  3323. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3324. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3325. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3326. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3327. // Pointer lock
  3328. this._onPointerLockChange = function () {
  3329. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3330. };
  3331. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3332. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3333. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3334. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3335. this._audioEngine = new BABYLON.AudioEngine();
  3336. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3337. }
  3338. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3339. get: function () {
  3340. return Engine._ALPHA_DISABLE;
  3341. },
  3342. enumerable: true,
  3343. configurable: true
  3344. });
  3345. Object.defineProperty(Engine, "ALPHA_ADD", {
  3346. get: function () {
  3347. return Engine._ALPHA_ADD;
  3348. },
  3349. enumerable: true,
  3350. configurable: true
  3351. });
  3352. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3353. get: function () {
  3354. return Engine._ALPHA_COMBINE;
  3355. },
  3356. enumerable: true,
  3357. configurable: true
  3358. });
  3359. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3360. get: function () {
  3361. return Engine._DELAYLOADSTATE_NONE;
  3362. },
  3363. enumerable: true,
  3364. configurable: true
  3365. });
  3366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3367. get: function () {
  3368. return Engine._DELAYLOADSTATE_LOADED;
  3369. },
  3370. enumerable: true,
  3371. configurable: true
  3372. });
  3373. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3374. get: function () {
  3375. return Engine._DELAYLOADSTATE_LOADING;
  3376. },
  3377. enumerable: true,
  3378. configurable: true
  3379. });
  3380. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3381. get: function () {
  3382. return Engine._DELAYLOADSTATE_NOTLOADED;
  3383. },
  3384. enumerable: true,
  3385. configurable: true
  3386. });
  3387. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3388. get: function () {
  3389. return Engine._TEXTUREFORMAT_ALPHA;
  3390. },
  3391. enumerable: true,
  3392. configurable: true
  3393. });
  3394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3395. get: function () {
  3396. return Engine._TEXTUREFORMAT_LUMINANCE;
  3397. },
  3398. enumerable: true,
  3399. configurable: true
  3400. });
  3401. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3402. get: function () {
  3403. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3404. },
  3405. enumerable: true,
  3406. configurable: true
  3407. });
  3408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3409. get: function () {
  3410. return Engine._TEXTUREFORMAT_RGB;
  3411. },
  3412. enumerable: true,
  3413. configurable: true
  3414. });
  3415. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3416. get: function () {
  3417. return Engine._TEXTUREFORMAT_RGBA;
  3418. },
  3419. enumerable: true,
  3420. configurable: true
  3421. });
  3422. Object.defineProperty(Engine, "Version", {
  3423. get: function () {
  3424. return "2.0.0";
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Engine.prototype.getAudioEngine = function () {
  3430. return this._audioEngine;
  3431. };
  3432. Engine.prototype.getAspectRatio = function (camera) {
  3433. var viewport = camera.viewport;
  3434. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3435. };
  3436. Engine.prototype.getRenderWidth = function () {
  3437. if (this._currentRenderTarget) {
  3438. return this._currentRenderTarget._width;
  3439. }
  3440. return this._renderingCanvas.width;
  3441. };
  3442. Engine.prototype.getRenderHeight = function () {
  3443. if (this._currentRenderTarget) {
  3444. return this._currentRenderTarget._height;
  3445. }
  3446. return this._renderingCanvas.height;
  3447. };
  3448. Engine.prototype.getRenderingCanvas = function () {
  3449. return this._renderingCanvas;
  3450. };
  3451. Engine.prototype.getRenderingCanvasClientRect = function () {
  3452. return this._renderingCanvas.getBoundingClientRect();
  3453. };
  3454. Engine.prototype.setHardwareScalingLevel = function (level) {
  3455. this._hardwareScalingLevel = level;
  3456. this.resize();
  3457. };
  3458. Engine.prototype.getHardwareScalingLevel = function () {
  3459. return this._hardwareScalingLevel;
  3460. };
  3461. Engine.prototype.getLoadedTexturesCache = function () {
  3462. return this._loadedTexturesCache;
  3463. };
  3464. Engine.prototype.getCaps = function () {
  3465. return this._caps;
  3466. };
  3467. Object.defineProperty(Engine.prototype, "drawCalls", {
  3468. get: function () {
  3469. return this._drawCalls;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. // Methods
  3475. Engine.prototype.resetDrawCalls = function () {
  3476. this._drawCalls = 0;
  3477. };
  3478. Engine.prototype.setDepthFunctionToGreater = function () {
  3479. this._depthCullingState.depthFunc = this._gl.GREATER;
  3480. };
  3481. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3482. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3483. };
  3484. Engine.prototype.setDepthFunctionToLess = function () {
  3485. this._depthCullingState.depthFunc = this._gl.LESS;
  3486. };
  3487. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3488. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3489. };
  3490. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3491. if (!renderFunction) {
  3492. this._activeRenderLoops = [];
  3493. return;
  3494. }
  3495. var index = this._activeRenderLoops.indexOf(renderFunction);
  3496. if (index >= 0) {
  3497. this._activeRenderLoops.splice(index, 1);
  3498. }
  3499. };
  3500. Engine.prototype._renderLoop = function () {
  3501. var _this = this;
  3502. var shouldRender = true;
  3503. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3504. shouldRender = false;
  3505. }
  3506. if (shouldRender) {
  3507. // Start new frame
  3508. this.beginFrame();
  3509. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3510. var renderFunction = this._activeRenderLoops[index];
  3511. renderFunction();
  3512. }
  3513. // Present
  3514. this.endFrame();
  3515. }
  3516. if (this._activeRenderLoops.length > 0) {
  3517. // Register new frame
  3518. BABYLON.Tools.QueueNewFrame(function () {
  3519. _this._renderLoop();
  3520. });
  3521. } else {
  3522. this._renderingQueueLaunched = false;
  3523. }
  3524. };
  3525. Engine.prototype.runRenderLoop = function (renderFunction) {
  3526. var _this = this;
  3527. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3528. return;
  3529. }
  3530. this._activeRenderLoops.push(renderFunction);
  3531. if (!this._renderingQueueLaunched) {
  3532. this._renderingQueueLaunched = true;
  3533. BABYLON.Tools.QueueNewFrame(function () {
  3534. _this._renderLoop();
  3535. });
  3536. }
  3537. };
  3538. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3539. if (this.isFullscreen) {
  3540. BABYLON.Tools.ExitFullscreen();
  3541. } else {
  3542. this._pointerLockRequested = requestPointerLock;
  3543. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3544. }
  3545. };
  3546. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3547. this.applyStates();
  3548. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3549. if (this._depthCullingState.depthMask) {
  3550. this._gl.clearDepth(1.0);
  3551. }
  3552. var mode = 0;
  3553. if (backBuffer)
  3554. mode |= this._gl.COLOR_BUFFER_BIT;
  3555. if (depthStencil && this._depthCullingState.depthMask)
  3556. mode |= this._gl.DEPTH_BUFFER_BIT;
  3557. this._gl.clear(mode);
  3558. };
  3559. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3560. var width = requiredWidth || this._renderingCanvas.width;
  3561. var height = requiredHeight || this._renderingCanvas.height;
  3562. var x = viewport.x || 0;
  3563. var y = viewport.y || 0;
  3564. this._cachedViewport = viewport;
  3565. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3566. };
  3567. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3568. this._cachedViewport = null;
  3569. this._gl.viewport(x, y, width, height);
  3570. };
  3571. Engine.prototype.beginFrame = function () {
  3572. this._measureFps();
  3573. };
  3574. Engine.prototype.endFrame = function () {
  3575. this.flushFramebuffer();
  3576. };
  3577. Engine.prototype.resize = function () {
  3578. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3579. };
  3580. Engine.prototype.setSize = function (width, height) {
  3581. this._renderingCanvas.width = width;
  3582. this._renderingCanvas.height = height;
  3583. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3584. };
  3585. Engine.prototype.bindFramebuffer = function (texture) {
  3586. this._currentRenderTarget = texture;
  3587. var gl = this._gl;
  3588. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3589. this._gl.viewport(0, 0, texture._width, texture._height);
  3590. this.wipeCaches();
  3591. };
  3592. Engine.prototype.unBindFramebuffer = function (texture) {
  3593. this._currentRenderTarget = null;
  3594. if (texture.generateMipMaps) {
  3595. var gl = this._gl;
  3596. gl.bindTexture(gl.TEXTURE_2D, texture);
  3597. gl.generateMipmap(gl.TEXTURE_2D);
  3598. gl.bindTexture(gl.TEXTURE_2D, null);
  3599. }
  3600. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3601. };
  3602. Engine.prototype.flushFramebuffer = function () {
  3603. // this._gl.flush();
  3604. };
  3605. Engine.prototype.restoreDefaultFramebuffer = function () {
  3606. this._currentRenderTarget = null;
  3607. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3608. this.setViewport(this._cachedViewport);
  3609. this.wipeCaches();
  3610. };
  3611. // VBOs
  3612. Engine.prototype._resetVertexBufferBinding = function () {
  3613. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3614. this._cachedVertexBuffers = null;
  3615. };
  3616. Engine.prototype.createVertexBuffer = function (vertices) {
  3617. var vbo = this._gl.createBuffer();
  3618. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3619. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3620. this._resetVertexBufferBinding();
  3621. vbo.references = 1;
  3622. return vbo;
  3623. };
  3624. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3625. var vbo = this._gl.createBuffer();
  3626. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3627. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3628. this._resetVertexBufferBinding();
  3629. vbo.references = 1;
  3630. return vbo;
  3631. };
  3632. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3633. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3634. if (offset === undefined) {
  3635. offset = 0;
  3636. }
  3637. if (vertices instanceof Float32Array) {
  3638. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3639. } else {
  3640. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3641. }
  3642. this._resetVertexBufferBinding();
  3643. };
  3644. Engine.prototype._resetIndexBufferBinding = function () {
  3645. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3646. this._cachedIndexBuffer = null;
  3647. };
  3648. Engine.prototype.createIndexBuffer = function (indices) {
  3649. var vbo = this._gl.createBuffer();
  3650. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3651. // Check for 32 bits indices
  3652. var arrayBuffer;
  3653. var need32Bits = false;
  3654. if (this._caps.uintIndices) {
  3655. for (var index = 0; index < indices.length; index++) {
  3656. if (indices[index] > 65535) {
  3657. need32Bits = true;
  3658. break;
  3659. }
  3660. }
  3661. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3662. } else {
  3663. arrayBuffer = new Uint16Array(indices);
  3664. }
  3665. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3666. this._resetIndexBufferBinding();
  3667. vbo.references = 1;
  3668. vbo.is32Bits = need32Bits;
  3669. return vbo;
  3670. };
  3671. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3672. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3673. this._cachedVertexBuffers = vertexBuffer;
  3674. this._cachedEffectForVertexBuffers = effect;
  3675. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3676. var offset = 0;
  3677. for (var index = 0; index < vertexDeclaration.length; index++) {
  3678. var order = effect.getAttributeLocation(index);
  3679. if (order >= 0) {
  3680. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3681. }
  3682. offset += vertexDeclaration[index] * 4;
  3683. }
  3684. }
  3685. if (this._cachedIndexBuffer !== indexBuffer) {
  3686. this._cachedIndexBuffer = indexBuffer;
  3687. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3688. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3689. }
  3690. };
  3691. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3692. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3693. this._cachedVertexBuffers = vertexBuffers;
  3694. this._cachedEffectForVertexBuffers = effect;
  3695. var attributes = effect.getAttributesNames();
  3696. for (var index = 0; index < attributes.length; index++) {
  3697. var order = effect.getAttributeLocation(index);
  3698. if (order >= 0) {
  3699. var vertexBuffer = vertexBuffers[attributes[index]];
  3700. if (!vertexBuffer) {
  3701. continue;
  3702. }
  3703. var stride = vertexBuffer.getStrideSize();
  3704. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3705. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3706. }
  3707. }
  3708. }
  3709. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3710. this._cachedIndexBuffer = indexBuffer;
  3711. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3712. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3713. }
  3714. };
  3715. Engine.prototype._releaseBuffer = function (buffer) {
  3716. buffer.references--;
  3717. if (buffer.references === 0) {
  3718. this._gl.deleteBuffer(buffer);
  3719. return true;
  3720. }
  3721. return false;
  3722. };
  3723. Engine.prototype.createInstancesBuffer = function (capacity) {
  3724. var buffer = this._gl.createBuffer();
  3725. buffer.capacity = capacity;
  3726. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3727. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3728. return buffer;
  3729. };
  3730. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3731. this._gl.deleteBuffer(buffer);
  3732. };
  3733. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3734. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3735. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3736. for (var index = 0; index < 4; index++) {
  3737. var offsetLocation = offsetLocations[index];
  3738. this._gl.enableVertexAttribArray(offsetLocation);
  3739. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3740. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3741. }
  3742. };
  3743. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3744. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3745. for (var index = 0; index < 4; index++) {
  3746. var offsetLocation = offsetLocations[index];
  3747. this._gl.disableVertexAttribArray(offsetLocation);
  3748. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3749. }
  3750. };
  3751. Engine.prototype.applyStates = function () {
  3752. this._depthCullingState.apply(this._gl);
  3753. this._alphaState.apply(this._gl);
  3754. };
  3755. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3756. // Apply states
  3757. this.applyStates();
  3758. this._drawCalls++;
  3759. // Render
  3760. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3761. if (instancesCount) {
  3762. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3763. return;
  3764. }
  3765. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3766. };
  3767. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3768. // Apply states
  3769. this.applyStates();
  3770. this._drawCalls++;
  3771. if (instancesCount) {
  3772. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3773. return;
  3774. }
  3775. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3776. };
  3777. // Shaders
  3778. Engine.prototype._releaseEffect = function (effect) {
  3779. if (this._compiledEffects[effect._key]) {
  3780. delete this._compiledEffects[effect._key];
  3781. if (effect.getProgram()) {
  3782. this._gl.deleteProgram(effect.getProgram());
  3783. }
  3784. }
  3785. };
  3786. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3787. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3788. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3789. var name = vertex + "+" + fragment + "@" + defines;
  3790. if (this._compiledEffects[name]) {
  3791. return this._compiledEffects[name];
  3792. }
  3793. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3794. effect._key = name;
  3795. this._compiledEffects[name] = effect;
  3796. return effect;
  3797. };
  3798. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3799. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3800. if (typeof samplers === "undefined") { samplers = []; }
  3801. if (typeof defines === "undefined") { defines = ""; }
  3802. return this.createEffect({
  3803. vertex: "particles",
  3804. fragmentElement: fragmentName
  3805. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3806. };
  3807. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3808. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3809. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3810. var shaderProgram = this._gl.createProgram();
  3811. this._gl.attachShader(shaderProgram, vertexShader);
  3812. this._gl.attachShader(shaderProgram, fragmentShader);
  3813. this._gl.linkProgram(shaderProgram);
  3814. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3815. if (!linked) {
  3816. var error = this._gl.getProgramInfoLog(shaderProgram);
  3817. if (error) {
  3818. throw new Error(error);
  3819. }
  3820. }
  3821. this._gl.deleteShader(vertexShader);
  3822. this._gl.deleteShader(fragmentShader);
  3823. return shaderProgram;
  3824. };
  3825. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3826. var results = [];
  3827. for (var index = 0; index < uniformsNames.length; index++) {
  3828. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3829. }
  3830. return results;
  3831. };
  3832. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3833. var results = [];
  3834. for (var index = 0; index < attributesNames.length; index++) {
  3835. try {
  3836. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3837. } catch (e) {
  3838. results.push(-1);
  3839. }
  3840. }
  3841. return results;
  3842. };
  3843. Engine.prototype.enableEffect = function (effect) {
  3844. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3845. if (effect && effect.onBind) {
  3846. effect.onBind(effect);
  3847. }
  3848. return;
  3849. }
  3850. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3851. // Use program
  3852. this._gl.useProgram(effect.getProgram());
  3853. for (var i in this._vertexAttribArrays) {
  3854. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3855. continue;
  3856. }
  3857. this._vertexAttribArrays[i] = false;
  3858. this._gl.disableVertexAttribArray(i);
  3859. }
  3860. var attributesCount = effect.getAttributesCount();
  3861. for (var index = 0; index < attributesCount; index++) {
  3862. // Attributes
  3863. var order = effect.getAttributeLocation(index);
  3864. if (order >= 0) {
  3865. this._vertexAttribArrays[order] = true;
  3866. this._gl.enableVertexAttribArray(order);
  3867. }
  3868. }
  3869. this._currentEffect = effect;
  3870. if (effect.onBind) {
  3871. effect.onBind(effect);
  3872. }
  3873. };
  3874. Engine.prototype.setArray = function (uniform, array) {
  3875. if (!uniform)
  3876. return;
  3877. this._gl.uniform1fv(uniform, array);
  3878. };
  3879. Engine.prototype.setMatrices = function (uniform, matrices) {
  3880. if (!uniform)
  3881. return;
  3882. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3883. };
  3884. Engine.prototype.setMatrix = function (uniform, matrix) {
  3885. if (!uniform)
  3886. return;
  3887. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3888. };
  3889. Engine.prototype.setFloat = function (uniform, value) {
  3890. if (!uniform)
  3891. return;
  3892. this._gl.uniform1f(uniform, value);
  3893. };
  3894. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3895. if (!uniform)
  3896. return;
  3897. this._gl.uniform2f(uniform, x, y);
  3898. };
  3899. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3900. if (!uniform)
  3901. return;
  3902. this._gl.uniform3f(uniform, x, y, z);
  3903. };
  3904. Engine.prototype.setBool = function (uniform, bool) {
  3905. if (!uniform)
  3906. return;
  3907. this._gl.uniform1i(uniform, bool);
  3908. };
  3909. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3910. if (!uniform)
  3911. return;
  3912. this._gl.uniform4f(uniform, x, y, z, w);
  3913. };
  3914. Engine.prototype.setColor3 = function (uniform, color3) {
  3915. if (!uniform)
  3916. return;
  3917. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3918. };
  3919. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3920. if (!uniform)
  3921. return;
  3922. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3923. };
  3924. // States
  3925. Engine.prototype.setState = function (culling, force) {
  3926. // Culling
  3927. if (this._depthCullingState.cull !== culling || force) {
  3928. if (culling) {
  3929. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3930. this._depthCullingState.cull = true;
  3931. } else {
  3932. this._depthCullingState.cull = false;
  3933. }
  3934. }
  3935. };
  3936. Engine.prototype.setDepthBuffer = function (enable) {
  3937. this._depthCullingState.depthTest = enable;
  3938. };
  3939. Engine.prototype.getDepthWrite = function () {
  3940. return this._depthCullingState.depthMask;
  3941. };
  3942. Engine.prototype.setDepthWrite = function (enable) {
  3943. this._depthCullingState.depthMask = enable;
  3944. };
  3945. Engine.prototype.setColorWrite = function (enable) {
  3946. this._gl.colorMask(enable, enable, enable, enable);
  3947. };
  3948. Engine.prototype.setAlphaMode = function (mode) {
  3949. switch (mode) {
  3950. case BABYLON.Engine.ALPHA_DISABLE:
  3951. this.setDepthWrite(true);
  3952. this._alphaState.alphaBlend = false;
  3953. break;
  3954. case BABYLON.Engine.ALPHA_COMBINE:
  3955. this.setDepthWrite(false);
  3956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3957. this._alphaState.alphaBlend = true;
  3958. break;
  3959. case BABYLON.Engine.ALPHA_ADD:
  3960. this.setDepthWrite(false);
  3961. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3962. this._alphaState.alphaBlend = true;
  3963. break;
  3964. }
  3965. this._alphaMode = mode;
  3966. };
  3967. Engine.prototype.getAlphaMode = function () {
  3968. return this._alphaMode;
  3969. };
  3970. Engine.prototype.setAlphaTesting = function (enable) {
  3971. this._alphaTest = enable;
  3972. };
  3973. Engine.prototype.getAlphaTesting = function () {
  3974. return this._alphaTest;
  3975. };
  3976. // Textures
  3977. Engine.prototype.wipeCaches = function () {
  3978. this._activeTexturesCache = [];
  3979. this._currentEffect = null;
  3980. this._depthCullingState.reset();
  3981. this._alphaState.reset();
  3982. this._cachedVertexBuffers = null;
  3983. this._cachedIndexBuffer = null;
  3984. this._cachedEffectForVertexBuffers = null;
  3985. };
  3986. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3987. var gl = this._gl;
  3988. gl.bindTexture(gl.TEXTURE_2D, texture);
  3989. var magFilter = gl.NEAREST;
  3990. var minFilter = gl.NEAREST;
  3991. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3992. magFilter = gl.LINEAR;
  3993. minFilter = gl.LINEAR;
  3994. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3995. magFilter = gl.LINEAR;
  3996. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3997. }
  3998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4000. gl.bindTexture(gl.TEXTURE_2D, null);
  4001. texture.samplingMode = samplingMode;
  4002. };
  4003. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4004. var _this = this;
  4005. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4006. if (typeof onLoad === "undefined") { onLoad = null; }
  4007. if (typeof onError === "undefined") { onError = null; }
  4008. if (typeof buffer === "undefined") { buffer = null; }
  4009. var texture = this._gl.createTexture();
  4010. var extension;
  4011. var fromData = false;
  4012. if (url.substr(0, 5) === "data:") {
  4013. fromData = true;
  4014. }
  4015. if (!fromData)
  4016. extension = url.substr(url.length - 4, 4).toLowerCase();
  4017. else {
  4018. var oldUrl = url;
  4019. fromData = oldUrl.split(':');
  4020. url = oldUrl;
  4021. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4022. }
  4023. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4024. var isTGA = (extension === ".tga");
  4025. scene._addPendingData(texture);
  4026. texture.url = url;
  4027. texture.noMipmap = noMipmap;
  4028. texture.references = 1;
  4029. this._loadedTexturesCache.push(texture);
  4030. var onerror = function () {
  4031. scene._removePendingData(texture);
  4032. if (onError) {
  4033. onError();
  4034. }
  4035. };
  4036. if (isTGA) {
  4037. var callback = function (arrayBuffer) {
  4038. var data = new Uint8Array(arrayBuffer);
  4039. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4040. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4041. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4042. if (onLoad) {
  4043. onLoad();
  4044. }
  4045. }, samplingMode);
  4046. };
  4047. if (!(fromData instanceof Array))
  4048. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4049. callback(arrayBuffer);
  4050. }, onerror, scene.database, true);
  4051. else
  4052. callback(buffer);
  4053. } else if (isDDS) {
  4054. callback = function (data) {
  4055. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4056. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  4057. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4058. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4059. if (onLoad) {
  4060. onLoad();
  4061. }
  4062. }, samplingMode);
  4063. };
  4064. if (!(fromData instanceof Array))
  4065. BABYLON.Tools.LoadFile(url, function (data) {
  4066. callback(data);
  4067. }, onerror, scene.database, true);
  4068. else
  4069. callback(buffer);
  4070. } else {
  4071. var onload = function (img) {
  4072. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4073. var isPot = (img.width == potWidth && img.height == potHeight);
  4074. if (!isPot) {
  4075. _this._workingCanvas.width = potWidth;
  4076. _this._workingCanvas.height = potHeight;
  4077. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4078. }
  4079. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4080. if (onLoad) {
  4081. onLoad();
  4082. }
  4083. }, samplingMode);
  4084. };
  4085. if (!(fromData instanceof Array))
  4086. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4087. else
  4088. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4089. }
  4090. return texture;
  4091. };
  4092. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4093. var texture = this._gl.createTexture();
  4094. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4095. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4096. // Format
  4097. var internalFormat = this._gl.RGBA;
  4098. switch (format) {
  4099. case Engine.TEXTUREFORMAT_ALPHA:
  4100. internalFormat = this._gl.ALPHA;
  4101. break;
  4102. case Engine.TEXTUREFORMAT_LUMINANCE:
  4103. internalFormat = this._gl.LUMINANCE;
  4104. break;
  4105. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4106. internalFormat = this._gl.LUMINANCE_ALPHA;
  4107. break;
  4108. case Engine.TEXTUREFORMAT_RGB:
  4109. internalFormat = this._gl.RGB;
  4110. break;
  4111. case Engine.TEXTUREFORMAT_RGBA:
  4112. internalFormat = this._gl.RGBA;
  4113. break;
  4114. }
  4115. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4116. if (generateMipMaps) {
  4117. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4118. }
  4119. // Filters
  4120. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4121. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4122. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4123. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4124. this._activeTexturesCache = [];
  4125. texture._baseWidth = width;
  4126. texture._baseHeight = height;
  4127. texture._width = width;
  4128. texture._height = height;
  4129. texture.isReady = true;
  4130. texture.references = 1;
  4131. texture.samplingMode = samplingMode;
  4132. this._loadedTexturesCache.push(texture);
  4133. return texture;
  4134. };
  4135. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4136. var texture = this._gl.createTexture();
  4137. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4138. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4139. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4140. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4141. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4142. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4143. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4144. this._activeTexturesCache = [];
  4145. texture._baseWidth = width;
  4146. texture._baseHeight = height;
  4147. texture._width = width;
  4148. texture._height = height;
  4149. texture.isReady = false;
  4150. texture.generateMipMaps = generateMipMaps;
  4151. texture.references = 1;
  4152. texture.samplingMode = samplingMode;
  4153. this._loadedTexturesCache.push(texture);
  4154. return texture;
  4155. };
  4156. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4157. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4158. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4159. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4160. if (texture.generateMipMaps) {
  4161. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4162. }
  4163. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4164. this._activeTexturesCache = [];
  4165. texture.isReady = true;
  4166. };
  4167. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4168. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4169. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4170. // Scale the video if it is a NPOT using the current working canvas
  4171. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4172. if (!texture._workingCanvas) {
  4173. texture._workingCanvas = document.createElement("canvas");
  4174. texture._workingContext = texture._workingCanvas.getContext("2d");
  4175. texture._workingCanvas.width = texture._width;
  4176. texture._workingCanvas.height = texture._height;
  4177. }
  4178. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4179. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4180. } else {
  4181. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4182. }
  4183. if (texture.generateMipMaps) {
  4184. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4185. }
  4186. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4187. this._activeTexturesCache = [];
  4188. texture.isReady = true;
  4189. };
  4190. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4191. // old version had a "generateMipMaps" arg instead of options.
  4192. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4193. // in the same way, generateDepthBuffer is defaulted to true
  4194. var generateMipMaps = false;
  4195. var generateDepthBuffer = true;
  4196. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4197. if (options !== undefined) {
  4198. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4199. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4200. if (options.samplingMode !== undefined) {
  4201. samplingMode = options.samplingMode;
  4202. }
  4203. }
  4204. var gl = this._gl;
  4205. var texture = gl.createTexture();
  4206. gl.bindTexture(gl.TEXTURE_2D, texture);
  4207. var width = size.width || size;
  4208. var height = size.height || size;
  4209. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4214. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4215. var depthBuffer;
  4216. // Create the depth buffer
  4217. if (generateDepthBuffer) {
  4218. depthBuffer = gl.createRenderbuffer();
  4219. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4220. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4221. }
  4222. // Create the framebuffer
  4223. var framebuffer = gl.createFramebuffer();
  4224. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4226. if (generateDepthBuffer) {
  4227. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4228. }
  4229. // Unbind
  4230. gl.bindTexture(gl.TEXTURE_2D, null);
  4231. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4232. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4233. texture._framebuffer = framebuffer;
  4234. if (generateDepthBuffer) {
  4235. texture._depthBuffer = depthBuffer;
  4236. }
  4237. texture._width = width;
  4238. texture._height = height;
  4239. texture.isReady = true;
  4240. texture.generateMipMaps = generateMipMaps;
  4241. texture.references = 1;
  4242. texture.samplingMode = samplingMode;
  4243. this._activeTexturesCache = [];
  4244. this._loadedTexturesCache.push(texture);
  4245. return texture;
  4246. };
  4247. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4248. var _this = this;
  4249. var gl = this._gl;
  4250. var texture = gl.createTexture();
  4251. texture.isCube = true;
  4252. texture.url = rootUrl;
  4253. texture.references = 1;
  4254. this._loadedTexturesCache.push(texture);
  4255. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4256. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4257. if (isDDS) {
  4258. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4259. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4260. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4261. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4262. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4263. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4264. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4265. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4266. }
  4267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4271. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4272. _this._activeTexturesCache = [];
  4273. texture._width = info.width;
  4274. texture._height = info.height;
  4275. texture.isReady = true;
  4276. }, null, null, true);
  4277. } else {
  4278. cascadeLoad(rootUrl, scene, function (imgs) {
  4279. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4280. var height = width;
  4281. _this._workingCanvas.width = width;
  4282. _this._workingCanvas.height = height;
  4283. var faces = [
  4284. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4285. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4286. ];
  4287. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4288. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4289. for (var index = 0; index < faces.length; index++) {
  4290. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4291. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4292. }
  4293. if (!noMipmap) {
  4294. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4295. }
  4296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4300. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4301. _this._activeTexturesCache = [];
  4302. texture._width = width;
  4303. texture._height = height;
  4304. texture.isReady = true;
  4305. }, extensions);
  4306. }
  4307. return texture;
  4308. };
  4309. Engine.prototype._releaseTexture = function (texture) {
  4310. var gl = this._gl;
  4311. if (texture._framebuffer) {
  4312. gl.deleteFramebuffer(texture._framebuffer);
  4313. }
  4314. if (texture._depthBuffer) {
  4315. gl.deleteRenderbuffer(texture._depthBuffer);
  4316. }
  4317. gl.deleteTexture(texture);
  4318. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4319. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4320. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4321. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4322. this._activeTexturesCache[channel] = null;
  4323. }
  4324. var index = this._loadedTexturesCache.indexOf(texture);
  4325. if (index !== -1) {
  4326. this._loadedTexturesCache.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype.bindSamplers = function (effect) {
  4330. this._gl.useProgram(effect.getProgram());
  4331. var samplers = effect.getSamplers();
  4332. for (var index = 0; index < samplers.length; index++) {
  4333. var uniform = effect.getUniform(samplers[index]);
  4334. this._gl.uniform1i(uniform, index);
  4335. }
  4336. this._currentEffect = null;
  4337. };
  4338. Engine.prototype._bindTexture = function (channel, texture) {
  4339. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4340. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4341. this._activeTexturesCache[channel] = null;
  4342. };
  4343. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4344. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4345. };
  4346. Engine.prototype.setTexture = function (channel, texture) {
  4347. if (channel < 0) {
  4348. return;
  4349. }
  4350. // Not ready?
  4351. if (!texture || !texture.isReady()) {
  4352. if (this._activeTexturesCache[channel] != null) {
  4353. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4354. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4355. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4356. this._activeTexturesCache[channel] = null;
  4357. }
  4358. return;
  4359. }
  4360. // Video
  4361. if (texture instanceof BABYLON.VideoTexture) {
  4362. if (texture.update()) {
  4363. this._activeTexturesCache[channel] = null;
  4364. }
  4365. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4366. texture.delayLoad();
  4367. return;
  4368. }
  4369. if (this._activeTexturesCache[channel] == texture) {
  4370. return;
  4371. }
  4372. this._activeTexturesCache[channel] = texture;
  4373. var internalTexture = texture.getInternalTexture();
  4374. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4375. if (internalTexture.isCube) {
  4376. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4377. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4378. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4379. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4380. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4381. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4383. }
  4384. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4385. } else {
  4386. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4387. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4388. internalTexture._cachedWrapU = texture.wrapU;
  4389. switch (texture.wrapU) {
  4390. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4391. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4392. break;
  4393. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4394. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4395. break;
  4396. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4398. break;
  4399. }
  4400. }
  4401. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4402. internalTexture._cachedWrapV = texture.wrapV;
  4403. switch (texture.wrapV) {
  4404. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4405. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4406. break;
  4407. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4408. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4409. break;
  4410. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4411. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4412. break;
  4413. }
  4414. }
  4415. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4416. }
  4417. };
  4418. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4419. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4420. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4421. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4422. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4423. }
  4424. };
  4425. Engine.prototype.readPixels = function (x, y, width, height) {
  4426. var data = new Uint8Array(height * width * 4);
  4427. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4428. return data;
  4429. };
  4430. // Dispose
  4431. Engine.prototype.dispose = function () {
  4432. this.hideLoadingUI();
  4433. this.stopRenderLoop();
  4434. while (this.scenes.length) {
  4435. this.scenes[0].dispose();
  4436. }
  4437. for (var name in this._compiledEffects) {
  4438. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4439. }
  4440. for (var i in this._vertexAttribArrays) {
  4441. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4442. continue;
  4443. }
  4444. this._gl.disableVertexAttribArray(i);
  4445. }
  4446. // Events
  4447. window.removeEventListener("blur", this._onBlur);
  4448. window.removeEventListener("focus", this._onFocus);
  4449. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4450. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4451. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4452. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4453. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4454. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4455. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4456. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4457. };
  4458. // Loading screen
  4459. Engine.prototype.displayLoadingUI = function () {
  4460. var _this = this;
  4461. this._loadingDiv = document.createElement("div");
  4462. this._loadingDiv.style.opacity = "0";
  4463. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4464. // Loading text
  4465. this._loadingTextDiv = document.createElement("div");
  4466. this._loadingTextDiv.style.position = "absolute";
  4467. this._loadingTextDiv.style.left = "0";
  4468. this._loadingTextDiv.style.top = "50%";
  4469. this._loadingTextDiv.style.marginTop = "80px";
  4470. this._loadingTextDiv.style.width = "100%";
  4471. this._loadingTextDiv.style.height = "20px";
  4472. this._loadingTextDiv.style.fontFamily = "Arial";
  4473. this._loadingTextDiv.style.fontSize = "14px";
  4474. this._loadingTextDiv.style.color = "white";
  4475. this._loadingTextDiv.style.textAlign = "center";
  4476. this._loadingTextDiv.innerHTML = "Loading";
  4477. this._loadingDiv.appendChild(this._loadingTextDiv);
  4478. // Loading img
  4479. var imgBack = new Image();
  4480. 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==";
  4481. imgBack.style.position = "absolute";
  4482. imgBack.style.left = "50%";
  4483. imgBack.style.top = "50%";
  4484. imgBack.style.marginLeft = "-50px";
  4485. imgBack.style.marginTop = "-50px";
  4486. imgBack.style.transition = "transform 1.0s ease";
  4487. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4488. var deg = 360;
  4489. var onTransitionEnd = function () {
  4490. deg += 360;
  4491. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4492. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4493. };
  4494. imgBack.addEventListener("transitionend", onTransitionEnd);
  4495. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4496. this._loadingDiv.appendChild(imgBack);
  4497. // front image
  4498. var imgFront = new Image();
  4499. 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=";
  4500. imgFront.style.position = "absolute";
  4501. imgFront.style.left = "50%";
  4502. imgFront.style.top = "50%";
  4503. imgFront.style.marginLeft = "-50px";
  4504. imgFront.style.marginTop = "-50px";
  4505. this._loadingDiv.appendChild(imgFront);
  4506. // Resize
  4507. this._resizeLoadingUI = function () {
  4508. var canvasRect = _this.getRenderingCanvasClientRect();
  4509. _this._loadingDiv.style.position = "absolute";
  4510. _this._loadingDiv.style.left = canvasRect.left + "px";
  4511. _this._loadingDiv.style.top = canvasRect.top + "px";
  4512. _this._loadingDiv.style.width = canvasRect.width + "px";
  4513. _this._loadingDiv.style.height = canvasRect.height + "px";
  4514. };
  4515. this._resizeLoadingUI();
  4516. window.addEventListener("resize", this._resizeLoadingUI);
  4517. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4518. document.body.appendChild(this._loadingDiv);
  4519. setTimeout(function () {
  4520. _this._loadingDiv.style.opacity = "1";
  4521. imgBack.style.transform = "rotateZ(360deg)";
  4522. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4523. }, 0);
  4524. };
  4525. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4526. set: function (text) {
  4527. if (!this._loadingDiv) {
  4528. return;
  4529. }
  4530. this._loadingTextDiv.innerHTML = text;
  4531. },
  4532. enumerable: true,
  4533. configurable: true
  4534. });
  4535. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4536. get: function () {
  4537. return this._loadingDivBackgroundColor;
  4538. },
  4539. set: function (color) {
  4540. this._loadingDivBackgroundColor = color;
  4541. if (!this._loadingDiv) {
  4542. return;
  4543. }
  4544. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4545. },
  4546. enumerable: true,
  4547. configurable: true
  4548. });
  4549. Engine.prototype.hideLoadingUI = function () {
  4550. var _this = this;
  4551. if (!this._loadingDiv) {
  4552. return;
  4553. }
  4554. var onTransitionEnd = function () {
  4555. if (!_this._loadingDiv) {
  4556. return;
  4557. }
  4558. document.body.removeChild(_this._loadingDiv);
  4559. window.removeEventListener("resize", _this._resizeLoadingUI);
  4560. _this._loadingDiv = null;
  4561. };
  4562. this._loadingDiv.style.opacity = "0";
  4563. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4564. };
  4565. // FPS
  4566. Engine.prototype.getFps = function () {
  4567. return this.fps;
  4568. };
  4569. Engine.prototype.getDeltaTime = function () {
  4570. return this.deltaTime;
  4571. };
  4572. Engine.prototype._measureFps = function () {
  4573. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4574. var length = this.previousFramesDuration.length;
  4575. if (length >= 2) {
  4576. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4577. }
  4578. if (length >= this.fpsRange) {
  4579. if (length > this.fpsRange) {
  4580. this.previousFramesDuration.splice(0, 1);
  4581. length = this.previousFramesDuration.length;
  4582. }
  4583. var sum = 0;
  4584. for (var id = 0; id < length - 1; id++) {
  4585. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4586. }
  4587. this.fps = 1000.0 / (sum / (length - 1));
  4588. }
  4589. };
  4590. // Statics
  4591. Engine.isSupported = function () {
  4592. try {
  4593. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4594. if (navigator.isCocoonJS) {
  4595. return true;
  4596. }
  4597. var tempcanvas = document.createElement("canvas");
  4598. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4599. return gl != null && !!window.WebGLRenderingContext;
  4600. } catch (e) {
  4601. return false;
  4602. }
  4603. };
  4604. Engine._ALPHA_DISABLE = 0;
  4605. Engine._ALPHA_ADD = 1;
  4606. Engine._ALPHA_COMBINE = 2;
  4607. Engine._DELAYLOADSTATE_NONE = 0;
  4608. Engine._DELAYLOADSTATE_LOADED = 1;
  4609. Engine._DELAYLOADSTATE_LOADING = 2;
  4610. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4611. Engine._TEXTUREFORMAT_ALPHA = 0;
  4612. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4613. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4614. Engine._TEXTUREFORMAT_RGB = 4;
  4615. Engine._TEXTUREFORMAT_RGBA = 4;
  4616. Engine.Epsilon = 0.001;
  4617. Engine.CollisionsEpsilon = 0.001;
  4618. Engine.ShadersRepository = "Babylon/Shaders/";
  4619. return Engine;
  4620. })();
  4621. BABYLON.Engine = Engine;
  4622. })(BABYLON || (BABYLON = {}));
  4623. //# sourceMappingURL=babylon.engine.js.map
  4624. var BABYLON;
  4625. (function (BABYLON) {
  4626. var Node = (function () {
  4627. function Node(name, scene) {
  4628. this.state = "";
  4629. this.animations = new Array();
  4630. this._childrenFlag = -1;
  4631. this._isEnabled = true;
  4632. this._isReady = true;
  4633. this._currentRenderId = -1;
  4634. this.name = name;
  4635. this.id = name;
  4636. this._scene = scene;
  4637. this._initCache();
  4638. }
  4639. Node.prototype.getScene = function () {
  4640. return this._scene;
  4641. };
  4642. Node.prototype.getEngine = function () {
  4643. return this._scene.getEngine();
  4644. };
  4645. // override it in derived class
  4646. Node.prototype.getWorldMatrix = function () {
  4647. return BABYLON.Matrix.Identity();
  4648. };
  4649. // override it in derived class if you add new variables to the cache
  4650. // and call the parent class method
  4651. Node.prototype._initCache = function () {
  4652. this._cache = {};
  4653. this._cache.parent = undefined;
  4654. };
  4655. Node.prototype.updateCache = function (force) {
  4656. if (!force && this.isSynchronized())
  4657. return;
  4658. this._cache.parent = this.parent;
  4659. this._updateCache();
  4660. };
  4661. // override it in derived class if you add new variables to the cache
  4662. // and call the parent class method if !ignoreParentClass
  4663. Node.prototype._updateCache = function (ignoreParentClass) {
  4664. };
  4665. // override it in derived class if you add new variables to the cache
  4666. Node.prototype._isSynchronized = function () {
  4667. return true;
  4668. };
  4669. Node.prototype.isSynchronizedWithParent = function () {
  4670. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4671. };
  4672. Node.prototype.isSynchronized = function (updateCache) {
  4673. var check = this.hasNewParent();
  4674. check = check || !this.isSynchronizedWithParent();
  4675. check = check || !this._isSynchronized();
  4676. if (updateCache)
  4677. this.updateCache(true);
  4678. return !check;
  4679. };
  4680. Node.prototype.hasNewParent = function (update) {
  4681. if (this._cache.parent === this.parent)
  4682. return false;
  4683. if (update)
  4684. this._cache.parent = this.parent;
  4685. return true;
  4686. };
  4687. Node.prototype.isReady = function () {
  4688. return this._isReady;
  4689. };
  4690. Node.prototype.isEnabled = function () {
  4691. if (!this._isEnabled) {
  4692. return false;
  4693. }
  4694. if (this.parent) {
  4695. return this.parent.isEnabled();
  4696. }
  4697. return true;
  4698. };
  4699. Node.prototype.setEnabled = function (value) {
  4700. this._isEnabled = value;
  4701. };
  4702. Node.prototype.isDescendantOf = function (ancestor) {
  4703. if (this.parent) {
  4704. if (this.parent === ancestor) {
  4705. return true;
  4706. }
  4707. return this.parent.isDescendantOf(ancestor);
  4708. }
  4709. return false;
  4710. };
  4711. Node.prototype._getDescendants = function (list, results) {
  4712. for (var index = 0; index < list.length; index++) {
  4713. var item = list[index];
  4714. if (item.isDescendantOf(this)) {
  4715. results.push(item);
  4716. }
  4717. }
  4718. };
  4719. Node.prototype.getDescendants = function () {
  4720. var results = [];
  4721. this._getDescendants(this._scene.meshes, results);
  4722. this._getDescendants(this._scene.lights, results);
  4723. this._getDescendants(this._scene.cameras, results);
  4724. return results;
  4725. };
  4726. Node.prototype._setReady = function (state) {
  4727. if (state == this._isReady) {
  4728. return;
  4729. }
  4730. if (!state) {
  4731. this._isReady = false;
  4732. return;
  4733. }
  4734. this._isReady = true;
  4735. if (this.onReady) {
  4736. this.onReady(this);
  4737. }
  4738. };
  4739. return Node;
  4740. })();
  4741. BABYLON.Node = Node;
  4742. })(BABYLON || (BABYLON = {}));
  4743. //# sourceMappingURL=babylon.node.js.map
  4744. var BABYLON;
  4745. (function (BABYLON) {
  4746. var BoundingSphere = (function () {
  4747. function BoundingSphere(minimum, maximum) {
  4748. this.minimum = minimum;
  4749. this.maximum = maximum;
  4750. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4751. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4752. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4753. this.radius = distance * 0.5;
  4754. this.centerWorld = BABYLON.Vector3.Zero();
  4755. this._update(BABYLON.Matrix.Identity());
  4756. }
  4757. // Methods
  4758. BoundingSphere.prototype._update = function (world) {
  4759. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4760. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4761. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4762. };
  4763. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4764. for (var i = 0; i < 6; i++) {
  4765. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4766. return false;
  4767. }
  4768. return true;
  4769. };
  4770. BoundingSphere.prototype.intersectsPoint = function (point) {
  4771. var x = this.centerWorld.x - point.x;
  4772. var y = this.centerWorld.y - point.y;
  4773. var z = this.centerWorld.z - point.z;
  4774. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4775. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4776. return false;
  4777. return true;
  4778. };
  4779. // Statics
  4780. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4781. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4782. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4783. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4784. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4785. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4786. return false;
  4787. return true;
  4788. };
  4789. return BoundingSphere;
  4790. })();
  4791. BABYLON.BoundingSphere = BoundingSphere;
  4792. })(BABYLON || (BABYLON = {}));
  4793. //# sourceMappingURL=babylon.boundingSphere.js.map
  4794. var BABYLON;
  4795. (function (BABYLON) {
  4796. var BoundingBox = (function () {
  4797. function BoundingBox(minimum, maximum) {
  4798. this.minimum = minimum;
  4799. this.maximum = maximum;
  4800. this.vectors = new Array();
  4801. this.vectorsWorld = new Array();
  4802. // Bounding vectors
  4803. this.vectors.push(this.minimum.clone());
  4804. this.vectors.push(this.maximum.clone());
  4805. this.vectors.push(this.minimum.clone());
  4806. this.vectors[2].x = this.maximum.x;
  4807. this.vectors.push(this.minimum.clone());
  4808. this.vectors[3].y = this.maximum.y;
  4809. this.vectors.push(this.minimum.clone());
  4810. this.vectors[4].z = this.maximum.z;
  4811. this.vectors.push(this.maximum.clone());
  4812. this.vectors[5].z = this.minimum.z;
  4813. this.vectors.push(this.maximum.clone());
  4814. this.vectors[6].x = this.minimum.x;
  4815. this.vectors.push(this.maximum.clone());
  4816. this.vectors[7].y = this.minimum.y;
  4817. // OBB
  4818. this.center = this.maximum.add(this.minimum).scale(0.5);
  4819. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4820. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4821. for (var index = 0; index < this.vectors.length; index++) {
  4822. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4823. }
  4824. this.minimumWorld = BABYLON.Vector3.Zero();
  4825. this.maximumWorld = BABYLON.Vector3.Zero();
  4826. this._update(BABYLON.Matrix.Identity());
  4827. }
  4828. // Methods
  4829. BoundingBox.prototype.getWorldMatrix = function () {
  4830. return this._worldMatrix;
  4831. };
  4832. BoundingBox.prototype._update = function (world) {
  4833. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4834. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4835. for (var index = 0; index < this.vectors.length; index++) {
  4836. var v = this.vectorsWorld[index];
  4837. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4838. if (v.x < this.minimumWorld.x)
  4839. this.minimumWorld.x = v.x;
  4840. if (v.y < this.minimumWorld.y)
  4841. this.minimumWorld.y = v.y;
  4842. if (v.z < this.minimumWorld.z)
  4843. this.minimumWorld.z = v.z;
  4844. if (v.x > this.maximumWorld.x)
  4845. this.maximumWorld.x = v.x;
  4846. if (v.y > this.maximumWorld.y)
  4847. this.maximumWorld.y = v.y;
  4848. if (v.z > this.maximumWorld.z)
  4849. this.maximumWorld.z = v.z;
  4850. }
  4851. // OBB
  4852. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4853. this.center.scaleInPlace(0.5);
  4854. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4855. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4856. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4857. this._worldMatrix = world;
  4858. };
  4859. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4860. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4861. };
  4862. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4863. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4864. };
  4865. BoundingBox.prototype.intersectsPoint = function (point) {
  4866. var delta = BABYLON.Engine.Epsilon;
  4867. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4868. return false;
  4869. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4870. return false;
  4871. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4872. return false;
  4873. return true;
  4874. };
  4875. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4876. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4877. };
  4878. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4879. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4880. return false;
  4881. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4882. return false;
  4883. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4884. return false;
  4885. return true;
  4886. };
  4887. // Statics
  4888. BoundingBox.Intersects = function (box0, box1) {
  4889. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4890. return false;
  4891. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4892. return false;
  4893. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4894. return false;
  4895. return true;
  4896. };
  4897. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4898. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4899. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4900. return (num <= (sphereRadius * sphereRadius));
  4901. };
  4902. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4903. for (var p = 0; p < 6; p++) {
  4904. for (var i = 0; i < 8; i++) {
  4905. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4906. return false;
  4907. }
  4908. }
  4909. }
  4910. return true;
  4911. };
  4912. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4913. for (var p = 0; p < 6; p++) {
  4914. var inCount = 8;
  4915. for (var i = 0; i < 8; i++) {
  4916. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4917. --inCount;
  4918. } else {
  4919. break;
  4920. }
  4921. }
  4922. if (inCount == 0)
  4923. return false;
  4924. }
  4925. return true;
  4926. };
  4927. return BoundingBox;
  4928. })();
  4929. BABYLON.BoundingBox = BoundingBox;
  4930. })(BABYLON || (BABYLON = {}));
  4931. //# sourceMappingURL=babylon.boundingBox.js.map
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var computeBoxExtents = function (axis, box) {
  4935. var p = BABYLON.Vector3.Dot(box.center, axis);
  4936. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4937. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4938. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4939. var r = r0 + r1 + r2;
  4940. return {
  4941. min: p - r,
  4942. max: p + r
  4943. };
  4944. };
  4945. var extentsOverlap = function (min0, max0, min1, max1) {
  4946. return !(min0 > max1 || min1 > max0);
  4947. };
  4948. var axisOverlap = function (axis, box0, box1) {
  4949. var result0 = computeBoxExtents(axis, box0);
  4950. var result1 = computeBoxExtents(axis, box1);
  4951. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4952. };
  4953. var BoundingInfo = (function () {
  4954. function BoundingInfo(minimum, maximum) {
  4955. this.minimum = minimum;
  4956. this.maximum = maximum;
  4957. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4958. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4959. }
  4960. // Methods
  4961. BoundingInfo.prototype._update = function (world) {
  4962. this.boundingBox._update(world);
  4963. this.boundingSphere._update(world);
  4964. };
  4965. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4966. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4967. return false;
  4968. return this.boundingBox.isInFrustum(frustumPlanes);
  4969. };
  4970. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4971. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4972. };
  4973. BoundingInfo.prototype._checkCollision = function (collider) {
  4974. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4975. };
  4976. BoundingInfo.prototype.intersectsPoint = function (point) {
  4977. if (!this.boundingSphere.centerWorld) {
  4978. return false;
  4979. }
  4980. if (!this.boundingSphere.intersectsPoint(point)) {
  4981. return false;
  4982. }
  4983. if (!this.boundingBox.intersectsPoint(point)) {
  4984. return false;
  4985. }
  4986. return true;
  4987. };
  4988. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4989. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4990. return false;
  4991. }
  4992. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4993. return false;
  4994. }
  4995. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4996. return false;
  4997. }
  4998. if (!precise) {
  4999. return true;
  5000. }
  5001. var box0 = this.boundingBox;
  5002. var box1 = boundingInfo.boundingBox;
  5003. if (!axisOverlap(box0.directions[0], box0, box1))
  5004. return false;
  5005. if (!axisOverlap(box0.directions[1], box0, box1))
  5006. return false;
  5007. if (!axisOverlap(box0.directions[2], box0, box1))
  5008. return false;
  5009. if (!axisOverlap(box1.directions[0], box0, box1))
  5010. return false;
  5011. if (!axisOverlap(box1.directions[1], box0, box1))
  5012. return false;
  5013. if (!axisOverlap(box1.directions[2], box0, box1))
  5014. return false;
  5015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5016. return false;
  5017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5018. return false;
  5019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5020. return false;
  5021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5022. return false;
  5023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5024. return false;
  5025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5026. return false;
  5027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5028. return false;
  5029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5030. return false;
  5031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5032. return false;
  5033. return true;
  5034. };
  5035. return BoundingInfo;
  5036. })();
  5037. BABYLON.BoundingInfo = BoundingInfo;
  5038. })(BABYLON || (BABYLON = {}));
  5039. //# sourceMappingURL=babylon.boundingInfo.js.map
  5040. var BABYLON;
  5041. (function (BABYLON) {
  5042. var Light = (function (_super) {
  5043. __extends(Light, _super);
  5044. function Light(name, scene) {
  5045. _super.call(this, name, scene);
  5046. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5047. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5048. this.intensity = 1.0;
  5049. this.range = Number.MAX_VALUE;
  5050. this.includedOnlyMeshes = new Array();
  5051. this.excludedMeshes = new Array();
  5052. this._excludedMeshesIds = new Array();
  5053. this._includedOnlyMeshesIds = new Array();
  5054. scene.lights.push(this);
  5055. }
  5056. Light.prototype.getShadowGenerator = function () {
  5057. return this._shadowGenerator;
  5058. };
  5059. Light.prototype.getAbsolutePosition = function () {
  5060. return BABYLON.Vector3.Zero();
  5061. };
  5062. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5063. };
  5064. Light.prototype._getWorldMatrix = function () {
  5065. return BABYLON.Matrix.Identity();
  5066. };
  5067. Light.prototype.canAffectMesh = function (mesh) {
  5068. if (!mesh) {
  5069. return true;
  5070. }
  5071. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5072. return false;
  5073. }
  5074. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5075. return false;
  5076. }
  5077. return true;
  5078. };
  5079. Light.prototype.getWorldMatrix = function () {
  5080. this._currentRenderId = this.getScene().getRenderId();
  5081. var worldMatrix = this._getWorldMatrix();
  5082. if (this.parent && this.parent.getWorldMatrix) {
  5083. if (!this._parentedWorldMatrix) {
  5084. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5085. }
  5086. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5087. return this._parentedWorldMatrix;
  5088. }
  5089. return worldMatrix;
  5090. };
  5091. Light.prototype.dispose = function () {
  5092. if (this._shadowGenerator) {
  5093. this._shadowGenerator.dispose();
  5094. this._shadowGenerator = null;
  5095. }
  5096. // Remove from scene
  5097. var index = this.getScene().lights.indexOf(this);
  5098. this.getScene().lights.splice(index, 1);
  5099. };
  5100. return Light;
  5101. })(BABYLON.Node);
  5102. BABYLON.Light = Light;
  5103. })(BABYLON || (BABYLON = {}));
  5104. //# sourceMappingURL=babylon.light.js.map
  5105. var BABYLON;
  5106. (function (BABYLON) {
  5107. var PointLight = (function (_super) {
  5108. __extends(PointLight, _super);
  5109. function PointLight(name, position, scene) {
  5110. _super.call(this, name, scene);
  5111. this.position = position;
  5112. }
  5113. PointLight.prototype.getAbsolutePosition = function () {
  5114. return this._transformedPosition ? this._transformedPosition : this.position;
  5115. };
  5116. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5117. if (this.parent && this.parent.getWorldMatrix) {
  5118. if (!this._transformedPosition) {
  5119. this._transformedPosition = BABYLON.Vector3.Zero();
  5120. }
  5121. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5122. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5123. return;
  5124. }
  5125. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5126. };
  5127. PointLight.prototype.getShadowGenerator = function () {
  5128. return null;
  5129. };
  5130. PointLight.prototype._getWorldMatrix = function () {
  5131. if (!this._worldMatrix) {
  5132. this._worldMatrix = BABYLON.Matrix.Identity();
  5133. }
  5134. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5135. return this._worldMatrix;
  5136. };
  5137. return PointLight;
  5138. })(BABYLON.Light);
  5139. BABYLON.PointLight = PointLight;
  5140. })(BABYLON || (BABYLON = {}));
  5141. //# sourceMappingURL=babylon.pointLight.js.map
  5142. var BABYLON;
  5143. (function (BABYLON) {
  5144. var SpotLight = (function (_super) {
  5145. __extends(SpotLight, _super);
  5146. function SpotLight(name, position, direction, angle, exponent, scene) {
  5147. _super.call(this, name, scene);
  5148. this.position = position;
  5149. this.direction = direction;
  5150. this.angle = angle;
  5151. this.exponent = exponent;
  5152. }
  5153. SpotLight.prototype.getAbsolutePosition = function () {
  5154. return this._transformedPosition ? this._transformedPosition : this.position;
  5155. };
  5156. SpotLight.prototype.setDirectionToTarget = function (target) {
  5157. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5158. return this.direction;
  5159. };
  5160. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5161. var normalizeDirection;
  5162. if (this.parent && this.parent.getWorldMatrix) {
  5163. if (!this._transformedDirection) {
  5164. this._transformedDirection = BABYLON.Vector3.Zero();
  5165. }
  5166. if (!this._transformedPosition) {
  5167. this._transformedPosition = BABYLON.Vector3.Zero();
  5168. }
  5169. var parentWorldMatrix = this.parent.getWorldMatrix();
  5170. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5171. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5172. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5173. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5174. } else {
  5175. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5176. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5177. }
  5178. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5179. };
  5180. SpotLight.prototype._getWorldMatrix = function () {
  5181. if (!this._worldMatrix) {
  5182. this._worldMatrix = BABYLON.Matrix.Identity();
  5183. }
  5184. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5185. return this._worldMatrix;
  5186. };
  5187. return SpotLight;
  5188. })(BABYLON.Light);
  5189. BABYLON.SpotLight = SpotLight;
  5190. })(BABYLON || (BABYLON = {}));
  5191. //# sourceMappingURL=babylon.spotLight.js.map
  5192. var BABYLON;
  5193. (function (BABYLON) {
  5194. var DirectionalLight = (function (_super) {
  5195. __extends(DirectionalLight, _super);
  5196. function DirectionalLight(name, direction, scene) {
  5197. _super.call(this, name, scene);
  5198. this.direction = direction;
  5199. this.position = direction.scale(-1);
  5200. }
  5201. DirectionalLight.prototype.getAbsolutePosition = function () {
  5202. return this._transformedPosition ? this._transformedPosition : this.position;
  5203. };
  5204. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5205. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5206. return this.direction;
  5207. };
  5208. DirectionalLight.prototype._computeTransformedPosition = function () {
  5209. if (this.parent && this.parent.getWorldMatrix) {
  5210. if (!this._transformedPosition) {
  5211. this._transformedPosition = BABYLON.Vector3.Zero();
  5212. }
  5213. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5214. return true;
  5215. }
  5216. return false;
  5217. };
  5218. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5219. if (this.parent && this.parent.getWorldMatrix) {
  5220. if (!this._transformedDirection) {
  5221. this._transformedDirection = BABYLON.Vector3.Zero();
  5222. }
  5223. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5224. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5225. return;
  5226. }
  5227. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5228. };
  5229. DirectionalLight.prototype._getWorldMatrix = function () {
  5230. if (!this._worldMatrix) {
  5231. this._worldMatrix = BABYLON.Matrix.Identity();
  5232. }
  5233. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5234. return this._worldMatrix;
  5235. };
  5236. return DirectionalLight;
  5237. })(BABYLON.Light);
  5238. BABYLON.DirectionalLight = DirectionalLight;
  5239. })(BABYLON || (BABYLON = {}));
  5240. //# sourceMappingURL=babylon.directionalLight.js.map
  5241. var BABYLON;
  5242. (function (BABYLON) {
  5243. var ShadowGenerator = (function () {
  5244. function ShadowGenerator(mapSize, light) {
  5245. var _this = this;
  5246. // Members
  5247. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5248. this._darkness = 0;
  5249. this._transparencyShadow = false;
  5250. this._viewMatrix = BABYLON.Matrix.Zero();
  5251. this._projectionMatrix = BABYLON.Matrix.Zero();
  5252. this._transformMatrix = BABYLON.Matrix.Zero();
  5253. this._worldViewProjection = BABYLON.Matrix.Zero();
  5254. this._light = light;
  5255. this._scene = light.getScene();
  5256. light._shadowGenerator = this;
  5257. // Render target
  5258. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5259. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5260. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5261. this._shadowMap.renderParticles = false;
  5262. // Custom render function
  5263. var renderSubMesh = function (subMesh) {
  5264. var mesh = subMesh.getRenderingMesh();
  5265. var scene = _this._scene;
  5266. var engine = scene.getEngine();
  5267. // Culling
  5268. engine.setState(subMesh.getMaterial().backFaceCulling);
  5269. // Managing instances
  5270. var batch = mesh._getInstancesRenderList(subMesh._id);
  5271. if (batch.mustReturn) {
  5272. return;
  5273. }
  5274. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5275. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5276. engine.enableEffect(_this._effect);
  5277. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5278. var material = subMesh.getMaterial();
  5279. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5280. // Alpha test
  5281. if (material && material.needAlphaTesting()) {
  5282. var alphaTexture = material.getAlphaTestTexture();
  5283. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5284. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5285. }
  5286. // Bones
  5287. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5288. if (useBones) {
  5289. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5290. }
  5291. if (hardwareInstancedRendering) {
  5292. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5293. } else {
  5294. if (batch.renderSelf[subMesh._id]) {
  5295. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5296. // Draw
  5297. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5298. }
  5299. if (batch.visibleInstances[subMesh._id]) {
  5300. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5301. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5302. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5303. // Draw
  5304. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5305. }
  5306. }
  5307. }
  5308. } else {
  5309. // Need to reset refresh rate of the shadowMap
  5310. _this._shadowMap.resetRefreshCounter();
  5311. }
  5312. };
  5313. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5314. var index;
  5315. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5316. renderSubMesh(opaqueSubMeshes.data[index]);
  5317. }
  5318. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5319. renderSubMesh(alphaTestSubMeshes.data[index]);
  5320. }
  5321. if (_this._transparencyShadow) {
  5322. for (index = 0; index < transparentSubMeshes.length; index++) {
  5323. renderSubMesh(transparentSubMeshes.data[index]);
  5324. }
  5325. }
  5326. };
  5327. }
  5328. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5329. // Static
  5330. get: function () {
  5331. return ShadowGenerator._FILTER_NONE;
  5332. },
  5333. enumerable: true,
  5334. configurable: true
  5335. });
  5336. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5337. get: function () {
  5338. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5339. },
  5340. enumerable: true,
  5341. configurable: true
  5342. });
  5343. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5344. get: function () {
  5345. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5346. },
  5347. enumerable: true,
  5348. configurable: true
  5349. });
  5350. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5351. get: function () {
  5352. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5353. },
  5354. set: function (value) {
  5355. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5361. get: function () {
  5362. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5363. },
  5364. set: function (value) {
  5365. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5366. },
  5367. enumerable: true,
  5368. configurable: true
  5369. });
  5370. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5371. var defines = [];
  5372. if (this.useVarianceShadowMap) {
  5373. defines.push("#define VSM");
  5374. }
  5375. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5376. var mesh = subMesh.getMesh();
  5377. var scene = mesh.getScene();
  5378. var material = subMesh.getMaterial();
  5379. // Alpha test
  5380. if (material && material.needAlphaTesting()) {
  5381. defines.push("#define ALPHATEST");
  5382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5383. attribs.push(BABYLON.VertexBuffer.UVKind);
  5384. defines.push("#define UV1");
  5385. }
  5386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5388. defines.push("#define UV2");
  5389. }
  5390. }
  5391. // Bones
  5392. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5395. defines.push("#define BONES");
  5396. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5397. }
  5398. // Instances
  5399. if (useInstances) {
  5400. defines.push("#define INSTANCES");
  5401. attribs.push("world0");
  5402. attribs.push("world1");
  5403. attribs.push("world2");
  5404. attribs.push("world3");
  5405. }
  5406. // Get correct effect
  5407. var join = defines.join("\n");
  5408. if (this._cachedDefines != join) {
  5409. this._cachedDefines = join;
  5410. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5411. }
  5412. return this._effect.isReady();
  5413. };
  5414. ShadowGenerator.prototype.getShadowMap = function () {
  5415. return this._shadowMap;
  5416. };
  5417. ShadowGenerator.prototype.getLight = function () {
  5418. return this._light;
  5419. };
  5420. // Methods
  5421. ShadowGenerator.prototype.getTransformMatrix = function () {
  5422. var lightPosition = this._light.position;
  5423. var lightDirection = this._light.direction;
  5424. if (this._light._computeTransformedPosition()) {
  5425. lightPosition = this._light._transformedPosition;
  5426. }
  5427. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5428. this._cachedPosition = lightPosition.clone();
  5429. this._cachedDirection = lightDirection.clone();
  5430. var activeCamera = this._scene.activeCamera;
  5431. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5432. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5433. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5434. }
  5435. return this._transformMatrix;
  5436. };
  5437. ShadowGenerator.prototype.getDarkness = function () {
  5438. return this._darkness;
  5439. };
  5440. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5441. if (darkness >= 1.0)
  5442. this._darkness = 1.0;
  5443. else if (darkness <= 0.0)
  5444. this._darkness = 0.0;
  5445. else
  5446. this._darkness = darkness;
  5447. };
  5448. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5449. this._transparencyShadow = hasShadow;
  5450. };
  5451. ShadowGenerator.prototype.dispose = function () {
  5452. this._shadowMap.dispose();
  5453. };
  5454. ShadowGenerator._FILTER_NONE = 0;
  5455. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5456. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5457. return ShadowGenerator;
  5458. })();
  5459. BABYLON.ShadowGenerator = ShadowGenerator;
  5460. })(BABYLON || (BABYLON = {}));
  5461. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5462. var BABYLON;
  5463. (function (BABYLON) {
  5464. var HemisphericLight = (function (_super) {
  5465. __extends(HemisphericLight, _super);
  5466. function HemisphericLight(name, direction, scene) {
  5467. _super.call(this, name, scene);
  5468. this.direction = direction;
  5469. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5470. }
  5471. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5472. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5473. return this.direction;
  5474. };
  5475. HemisphericLight.prototype.getShadowGenerator = function () {
  5476. return null;
  5477. };
  5478. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5479. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5480. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5481. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5482. };
  5483. HemisphericLight.prototype._getWorldMatrix = function () {
  5484. if (!this._worldMatrix) {
  5485. this._worldMatrix = BABYLON.Matrix.Identity();
  5486. }
  5487. return this._worldMatrix;
  5488. };
  5489. return HemisphericLight;
  5490. })(BABYLON.Light);
  5491. BABYLON.HemisphericLight = HemisphericLight;
  5492. })(BABYLON || (BABYLON = {}));
  5493. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5497. if (boxMin.x > sphereCenter.x + sphereRadius)
  5498. return false;
  5499. if (sphereCenter.x - sphereRadius > boxMax.x)
  5500. return false;
  5501. if (boxMin.y > sphereCenter.y + sphereRadius)
  5502. return false;
  5503. if (sphereCenter.y - sphereRadius > boxMax.y)
  5504. return false;
  5505. if (boxMin.z > sphereCenter.z + sphereRadius)
  5506. return false;
  5507. if (sphereCenter.z - sphereRadius > boxMax.z)
  5508. return false;
  5509. return true;
  5510. };
  5511. var getLowestRoot = function (a, b, c, maxR) {
  5512. var determinant = b * b - 4.0 * a * c;
  5513. var result = { root: 0, found: false };
  5514. if (determinant < 0)
  5515. return result;
  5516. var sqrtD = Math.sqrt(determinant);
  5517. var r1 = (-b - sqrtD) / (2.0 * a);
  5518. var r2 = (-b + sqrtD) / (2.0 * a);
  5519. if (r1 > r2) {
  5520. var temp = r2;
  5521. r2 = r1;
  5522. r1 = temp;
  5523. }
  5524. if (r1 > 0 && r1 < maxR) {
  5525. result.root = r1;
  5526. result.found = true;
  5527. return result;
  5528. }
  5529. if (r2 > 0 && r2 < maxR) {
  5530. result.root = r2;
  5531. result.found = true;
  5532. return result;
  5533. }
  5534. return result;
  5535. };
  5536. var Collider = (function () {
  5537. function Collider() {
  5538. this.radius = new BABYLON.Vector3(1, 1, 1);
  5539. this.retry = 0;
  5540. this.basePointWorld = BABYLON.Vector3.Zero();
  5541. this.velocityWorld = BABYLON.Vector3.Zero();
  5542. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5543. this._collisionPoint = BABYLON.Vector3.Zero();
  5544. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5545. this._tempVector = BABYLON.Vector3.Zero();
  5546. this._tempVector2 = BABYLON.Vector3.Zero();
  5547. this._tempVector3 = BABYLON.Vector3.Zero();
  5548. this._tempVector4 = BABYLON.Vector3.Zero();
  5549. this._edge = BABYLON.Vector3.Zero();
  5550. this._baseToVertex = BABYLON.Vector3.Zero();
  5551. this._destinationPoint = BABYLON.Vector3.Zero();
  5552. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5553. this._displacementVector = BABYLON.Vector3.Zero();
  5554. }
  5555. // Methods
  5556. Collider.prototype._initialize = function (source, dir, e) {
  5557. this.velocity = dir;
  5558. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5559. this.basePoint = source;
  5560. source.multiplyToRef(this.radius, this.basePointWorld);
  5561. dir.multiplyToRef(this.radius, this.velocityWorld);
  5562. this.velocityWorldLength = this.velocityWorld.length();
  5563. this.epsilon = e;
  5564. this.collisionFound = false;
  5565. };
  5566. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5567. pa.subtractToRef(point, this._tempVector);
  5568. pb.subtractToRef(point, this._tempVector2);
  5569. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5570. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5571. if (d < 0)
  5572. return false;
  5573. pc.subtractToRef(point, this._tempVector3);
  5574. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5575. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5576. if (d < 0)
  5577. return false;
  5578. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5579. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5580. return d >= 0;
  5581. };
  5582. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5583. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5584. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5585. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5586. return false;
  5587. }
  5588. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5589. return false;
  5590. return true;
  5591. };
  5592. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5593. var t0;
  5594. var embeddedInPlane = false;
  5595. if (!subMesh._trianglePlanes) {
  5596. subMesh._trianglePlanes = [];
  5597. }
  5598. if (!subMesh._trianglePlanes[faceIndex]) {
  5599. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5600. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5601. }
  5602. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5603. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5604. return;
  5605. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5606. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5607. if (normalDotVelocity == 0) {
  5608. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5609. return;
  5610. embeddedInPlane = true;
  5611. t0 = 0;
  5612. } else {
  5613. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5614. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5615. if (t0 > t1) {
  5616. var temp = t1;
  5617. t1 = t0;
  5618. t0 = temp;
  5619. }
  5620. if (t0 > 1.0 || t1 < 0.0)
  5621. return;
  5622. if (t0 < 0)
  5623. t0 = 0;
  5624. if (t0 > 1.0)
  5625. t0 = 1.0;
  5626. }
  5627. this._collisionPoint.copyFromFloats(0, 0, 0);
  5628. var found = false;
  5629. var t = 1.0;
  5630. if (!embeddedInPlane) {
  5631. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5632. this.velocity.scaleToRef(t0, this._tempVector);
  5633. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5634. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5635. found = true;
  5636. t = t0;
  5637. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5638. }
  5639. }
  5640. if (!found) {
  5641. var velocitySquaredLength = this.velocity.lengthSquared();
  5642. var a = velocitySquaredLength;
  5643. this.basePoint.subtractToRef(p1, this._tempVector);
  5644. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5645. var c = this._tempVector.lengthSquared() - 1.0;
  5646. var lowestRoot = getLowestRoot(a, b, c, t);
  5647. if (lowestRoot.found) {
  5648. t = lowestRoot.root;
  5649. found = true;
  5650. this._collisionPoint.copyFrom(p1);
  5651. }
  5652. this.basePoint.subtractToRef(p2, this._tempVector);
  5653. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5654. c = this._tempVector.lengthSquared() - 1.0;
  5655. lowestRoot = getLowestRoot(a, b, c, t);
  5656. if (lowestRoot.found) {
  5657. t = lowestRoot.root;
  5658. found = true;
  5659. this._collisionPoint.copyFrom(p2);
  5660. }
  5661. this.basePoint.subtractToRef(p3, this._tempVector);
  5662. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5663. c = this._tempVector.lengthSquared() - 1.0;
  5664. lowestRoot = getLowestRoot(a, b, c, t);
  5665. if (lowestRoot.found) {
  5666. t = lowestRoot.root;
  5667. found = true;
  5668. this._collisionPoint.copyFrom(p3);
  5669. }
  5670. p2.subtractToRef(p1, this._edge);
  5671. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5672. var edgeSquaredLength = this._edge.lengthSquared();
  5673. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5674. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5675. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5676. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5677. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5678. lowestRoot = getLowestRoot(a, b, c, t);
  5679. if (lowestRoot.found) {
  5680. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5681. if (f >= 0.0 && f <= 1.0) {
  5682. t = lowestRoot.root;
  5683. found = true;
  5684. this._edge.scaleInPlace(f);
  5685. p1.addToRef(this._edge, this._collisionPoint);
  5686. }
  5687. }
  5688. p3.subtractToRef(p2, this._edge);
  5689. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5690. edgeSquaredLength = this._edge.lengthSquared();
  5691. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5692. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5693. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5694. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5695. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5696. lowestRoot = getLowestRoot(a, b, c, t);
  5697. if (lowestRoot.found) {
  5698. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5699. if (f >= 0.0 && f <= 1.0) {
  5700. t = lowestRoot.root;
  5701. found = true;
  5702. this._edge.scaleInPlace(f);
  5703. p2.addToRef(this._edge, this._collisionPoint);
  5704. }
  5705. }
  5706. p1.subtractToRef(p3, this._edge);
  5707. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5708. edgeSquaredLength = this._edge.lengthSquared();
  5709. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5710. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5711. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5712. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5713. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5714. lowestRoot = getLowestRoot(a, b, c, t);
  5715. if (lowestRoot.found) {
  5716. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5717. if (f >= 0.0 && f <= 1.0) {
  5718. t = lowestRoot.root;
  5719. found = true;
  5720. this._edge.scaleInPlace(f);
  5721. p3.addToRef(this._edge, this._collisionPoint);
  5722. }
  5723. }
  5724. }
  5725. if (found) {
  5726. var distToCollision = t * this.velocity.length();
  5727. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5728. if (!this.intersectionPoint) {
  5729. this.intersectionPoint = this._collisionPoint.clone();
  5730. } else {
  5731. this.intersectionPoint.copyFrom(this._collisionPoint);
  5732. }
  5733. this.nearestDistance = distToCollision;
  5734. this.collisionFound = true;
  5735. this.collidedMesh = subMesh.getMesh();
  5736. }
  5737. }
  5738. };
  5739. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5740. for (var i = indexStart; i < indexEnd; i += 3) {
  5741. var p1 = pts[indices[i] - decal];
  5742. var p2 = pts[indices[i + 1] - decal];
  5743. var p3 = pts[indices[i + 2] - decal];
  5744. this._testTriangle(i, subMesh, p3, p2, p1);
  5745. }
  5746. };
  5747. Collider.prototype._getResponse = function (pos, vel) {
  5748. pos.addToRef(vel, this._destinationPoint);
  5749. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5750. this.basePoint.addToRef(vel, pos);
  5751. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5752. this._slidePlaneNormal.normalize();
  5753. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5754. pos.addInPlace(this._displacementVector);
  5755. this.intersectionPoint.addInPlace(this._displacementVector);
  5756. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5757. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5758. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5759. };
  5760. return Collider;
  5761. })();
  5762. BABYLON.Collider = Collider;
  5763. })(BABYLON || (BABYLON = {}));
  5764. //# sourceMappingURL=babylon.collider.js.map
  5765. var BABYLON;
  5766. (function (BABYLON) {
  5767. var Camera = (function (_super) {
  5768. __extends(Camera, _super);
  5769. function Camera(name, position, scene) {
  5770. _super.call(this, name, scene);
  5771. this.position = position;
  5772. // Members
  5773. this.upVector = BABYLON.Vector3.Up();
  5774. this.orthoLeft = null;
  5775. this.orthoRight = null;
  5776. this.orthoBottom = null;
  5777. this.orthoTop = null;
  5778. this.fov = 0.8;
  5779. this.minZ = 1.0;
  5780. this.maxZ = 10000.0;
  5781. this.inertia = 0.9;
  5782. this.mode = Camera.PERSPECTIVE_CAMERA;
  5783. this.isIntermediate = false;
  5784. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5785. this.subCameras = [];
  5786. this.layerMask = 0xFFFFFFFF;
  5787. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5788. this._projectionMatrix = new BABYLON.Matrix();
  5789. this._postProcesses = new Array();
  5790. this._postProcessesTakenIndices = [];
  5791. scene.cameras.push(this);
  5792. if (!scene.activeCamera) {
  5793. scene.activeCamera = this;
  5794. }
  5795. }
  5796. //Cache
  5797. Camera.prototype._initCache = function () {
  5798. _super.prototype._initCache.call(this);
  5799. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5800. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5801. this._cache.mode = undefined;
  5802. this._cache.minZ = undefined;
  5803. this._cache.maxZ = undefined;
  5804. this._cache.fov = undefined;
  5805. this._cache.aspectRatio = undefined;
  5806. this._cache.orthoLeft = undefined;
  5807. this._cache.orthoRight = undefined;
  5808. this._cache.orthoBottom = undefined;
  5809. this._cache.orthoTop = undefined;
  5810. this._cache.renderWidth = undefined;
  5811. this._cache.renderHeight = undefined;
  5812. };
  5813. Camera.prototype._updateCache = function (ignoreParentClass) {
  5814. if (!ignoreParentClass) {
  5815. _super.prototype._updateCache.call(this);
  5816. }
  5817. var engine = this.getEngine();
  5818. this._cache.position.copyFrom(this.position);
  5819. this._cache.upVector.copyFrom(this.upVector);
  5820. this._cache.mode = this.mode;
  5821. this._cache.minZ = this.minZ;
  5822. this._cache.maxZ = this.maxZ;
  5823. this._cache.fov = this.fov;
  5824. this._cache.aspectRatio = engine.getAspectRatio(this);
  5825. this._cache.orthoLeft = this.orthoLeft;
  5826. this._cache.orthoRight = this.orthoRight;
  5827. this._cache.orthoBottom = this.orthoBottom;
  5828. this._cache.orthoTop = this.orthoTop;
  5829. this._cache.renderWidth = engine.getRenderWidth();
  5830. this._cache.renderHeight = engine.getRenderHeight();
  5831. };
  5832. Camera.prototype._updateFromScene = function () {
  5833. this.updateCache();
  5834. this._update();
  5835. };
  5836. // Synchronized
  5837. Camera.prototype._isSynchronized = function () {
  5838. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5839. };
  5840. Camera.prototype._isSynchronizedViewMatrix = function () {
  5841. if (!_super.prototype._isSynchronized.call(this))
  5842. return false;
  5843. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5844. };
  5845. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5846. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5847. if (!check) {
  5848. return false;
  5849. }
  5850. var engine = this.getEngine();
  5851. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5852. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5853. } else {
  5854. 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();
  5855. }
  5856. return check;
  5857. };
  5858. // Controls
  5859. Camera.prototype.attachControl = function (element) {
  5860. };
  5861. Camera.prototype.detachControl = function (element) {
  5862. };
  5863. Camera.prototype._update = function () {
  5864. };
  5865. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5866. if (typeof insertAt === "undefined") { insertAt = null; }
  5867. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5868. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5869. return 0;
  5870. }
  5871. if (insertAt == null || insertAt < 0) {
  5872. this._postProcesses.push(postProcess);
  5873. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5874. return this._postProcesses.length - 1;
  5875. }
  5876. var add = 0;
  5877. if (this._postProcesses[insertAt]) {
  5878. var start = this._postProcesses.length - 1;
  5879. for (var i = start; i >= insertAt + 1; --i) {
  5880. this._postProcesses[i + 1] = this._postProcesses[i];
  5881. }
  5882. add = 1;
  5883. }
  5884. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5885. if (this._postProcessesTakenIndices[i] < insertAt) {
  5886. continue;
  5887. }
  5888. start = this._postProcessesTakenIndices.length - 1;
  5889. for (var j = start; j >= i; --j) {
  5890. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5891. }
  5892. this._postProcessesTakenIndices[i] = insertAt;
  5893. break;
  5894. }
  5895. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5896. this._postProcessesTakenIndices.push(insertAt);
  5897. }
  5898. var result = insertAt + add;
  5899. this._postProcesses[result] = postProcess;
  5900. return result;
  5901. };
  5902. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5903. if (typeof atIndices === "undefined") { atIndices = null; }
  5904. var result = [];
  5905. if (!atIndices) {
  5906. var length = this._postProcesses.length;
  5907. for (var i = 0; i < length; i++) {
  5908. if (this._postProcesses[i] !== postProcess) {
  5909. continue;
  5910. }
  5911. delete this._postProcesses[i];
  5912. var index = this._postProcessesTakenIndices.indexOf(i);
  5913. this._postProcessesTakenIndices.splice(index, 1);
  5914. }
  5915. } else {
  5916. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5917. for (i = 0; i < atIndices.length; i++) {
  5918. var foundPostProcess = this._postProcesses[atIndices[i]];
  5919. if (foundPostProcess !== postProcess) {
  5920. result.push(i);
  5921. continue;
  5922. }
  5923. delete this._postProcesses[atIndices[i]];
  5924. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5925. this._postProcessesTakenIndices.splice(index, 1);
  5926. }
  5927. }
  5928. return result;
  5929. };
  5930. Camera.prototype.getWorldMatrix = function () {
  5931. if (!this._worldMatrix) {
  5932. this._worldMatrix = BABYLON.Matrix.Identity();
  5933. }
  5934. var viewMatrix = this.getViewMatrix();
  5935. viewMatrix.invertToRef(this._worldMatrix);
  5936. return this._worldMatrix;
  5937. };
  5938. Camera.prototype._getViewMatrix = function () {
  5939. return BABYLON.Matrix.Identity();
  5940. };
  5941. Camera.prototype.getViewMatrix = function () {
  5942. this._computedViewMatrix = this._computeViewMatrix();
  5943. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5944. return this._computedViewMatrix;
  5945. }
  5946. if (!this._worldMatrix) {
  5947. this._worldMatrix = BABYLON.Matrix.Identity();
  5948. }
  5949. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5950. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5951. this._computedViewMatrix.invert();
  5952. this._currentRenderId = this.getScene().getRenderId();
  5953. return this._computedViewMatrix;
  5954. };
  5955. Camera.prototype._computeViewMatrix = function (force) {
  5956. if (!force && this._isSynchronizedViewMatrix()) {
  5957. return this._computedViewMatrix;
  5958. }
  5959. this._computedViewMatrix = this._getViewMatrix();
  5960. if (!this.parent || !this.parent.getWorldMatrix) {
  5961. this._currentRenderId = this.getScene().getRenderId();
  5962. }
  5963. return this._computedViewMatrix;
  5964. };
  5965. Camera.prototype.getProjectionMatrix = function (force) {
  5966. if (!force && this._isSynchronizedProjectionMatrix()) {
  5967. return this._projectionMatrix;
  5968. }
  5969. var engine = this.getEngine();
  5970. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5971. if (this.minZ <= 0) {
  5972. this.minZ = 0.1;
  5973. }
  5974. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5975. return this._projectionMatrix;
  5976. }
  5977. var halfWidth = engine.getRenderWidth() / 2.0;
  5978. var halfHeight = engine.getRenderHeight() / 2.0;
  5979. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5980. return this._projectionMatrix;
  5981. };
  5982. Camera.prototype.dispose = function () {
  5983. // Remove from scene
  5984. var index = this.getScene().cameras.indexOf(this);
  5985. this.getScene().cameras.splice(index, 1);
  5986. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5987. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5988. }
  5989. };
  5990. Camera.PERSPECTIVE_CAMERA = 0;
  5991. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5992. return Camera;
  5993. })(BABYLON.Node);
  5994. BABYLON.Camera = Camera;
  5995. })(BABYLON || (BABYLON = {}));
  5996. //# sourceMappingURL=babylon.camera.js.map
  5997. var BABYLON;
  5998. (function (BABYLON) {
  5999. var TargetCamera = (function (_super) {
  6000. __extends(TargetCamera, _super);
  6001. function TargetCamera(name, position, scene) {
  6002. _super.call(this, name, position, scene);
  6003. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6004. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6005. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6006. this.speed = 2.0;
  6007. this.noRotationConstraint = false;
  6008. this.lockedTarget = null;
  6009. this._currentTarget = BABYLON.Vector3.Zero();
  6010. this._viewMatrix = BABYLON.Matrix.Zero();
  6011. this._camMatrix = BABYLON.Matrix.Zero();
  6012. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6013. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6014. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6015. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6016. this._lookAtTemp = BABYLON.Matrix.Zero();
  6017. this._tempMatrix = BABYLON.Matrix.Zero();
  6018. }
  6019. TargetCamera.prototype._getLockedTargetPosition = function () {
  6020. if (!this.lockedTarget) {
  6021. return null;
  6022. }
  6023. return this.lockedTarget.position || this.lockedTarget;
  6024. };
  6025. // Cache
  6026. TargetCamera.prototype._initCache = function () {
  6027. _super.prototype._initCache.call(this);
  6028. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6029. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6030. };
  6031. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6032. if (!ignoreParentClass) {
  6033. _super.prototype._updateCache.call(this);
  6034. }
  6035. var lockedTargetPosition = this._getLockedTargetPosition();
  6036. if (!lockedTargetPosition) {
  6037. this._cache.lockedTarget = null;
  6038. } else {
  6039. if (!this._cache.lockedTarget) {
  6040. this._cache.lockedTarget = lockedTargetPosition.clone();
  6041. } else {
  6042. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6043. }
  6044. }
  6045. this._cache.rotation.copyFrom(this.rotation);
  6046. };
  6047. // Synchronized
  6048. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6049. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6050. return false;
  6051. }
  6052. var lockedTargetPosition = this._getLockedTargetPosition();
  6053. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6054. };
  6055. // Methods
  6056. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6057. var engine = this.getEngine();
  6058. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6059. };
  6060. // Target
  6061. TargetCamera.prototype.setTarget = function (target) {
  6062. this.upVector.normalize();
  6063. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6064. this._camMatrix.invert();
  6065. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6066. var vDir = target.subtract(this.position);
  6067. if (vDir.x >= 0.0) {
  6068. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6069. } else {
  6070. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6071. }
  6072. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6073. if (isNaN(this.rotation.x)) {
  6074. this.rotation.x = 0;
  6075. }
  6076. if (isNaN(this.rotation.y)) {
  6077. this.rotation.y = 0;
  6078. }
  6079. if (isNaN(this.rotation.z)) {
  6080. this.rotation.z = 0;
  6081. }
  6082. };
  6083. TargetCamera.prototype.getTarget = function () {
  6084. return this._currentTarget;
  6085. };
  6086. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6087. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6088. };
  6089. TargetCamera.prototype._updatePosition = function () {
  6090. this.position.addInPlace(this.cameraDirection);
  6091. };
  6092. TargetCamera.prototype._update = function () {
  6093. var needToMove = this._decideIfNeedsToMove();
  6094. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6095. // Move
  6096. if (needToMove) {
  6097. this._updatePosition();
  6098. }
  6099. // Rotate
  6100. if (needToRotate) {
  6101. this.rotation.x += this.cameraRotation.x;
  6102. this.rotation.y += this.cameraRotation.y;
  6103. if (!this.noRotationConstraint) {
  6104. var limit = (Math.PI / 2) * 0.95;
  6105. if (this.rotation.x > limit)
  6106. this.rotation.x = limit;
  6107. if (this.rotation.x < -limit)
  6108. this.rotation.x = -limit;
  6109. }
  6110. }
  6111. // Inertia
  6112. if (needToMove) {
  6113. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6114. this.cameraDirection.x = 0;
  6115. }
  6116. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6117. this.cameraDirection.y = 0;
  6118. }
  6119. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6120. this.cameraDirection.z = 0;
  6121. }
  6122. this.cameraDirection.scaleInPlace(this.inertia);
  6123. }
  6124. if (needToRotate) {
  6125. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6126. this.cameraRotation.x = 0;
  6127. }
  6128. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6129. this.cameraRotation.y = 0;
  6130. }
  6131. this.cameraRotation.scaleInPlace(this.inertia);
  6132. }
  6133. };
  6134. TargetCamera.prototype._getViewMatrix = function () {
  6135. if (!this.lockedTarget) {
  6136. // Compute
  6137. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6138. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6139. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6140. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6141. this._lookAtTemp.invert();
  6142. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6143. } else {
  6144. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6145. }
  6146. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6147. // Computing target and final matrix
  6148. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6149. } else {
  6150. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6151. }
  6152. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6153. return this._viewMatrix;
  6154. };
  6155. return TargetCamera;
  6156. })(BABYLON.Camera);
  6157. BABYLON.TargetCamera = TargetCamera;
  6158. })(BABYLON || (BABYLON = {}));
  6159. //# sourceMappingURL=babylon.targetCamera.js.map
  6160. var BABYLON;
  6161. (function (BABYLON) {
  6162. var FollowCamera = (function (_super) {
  6163. __extends(FollowCamera, _super);
  6164. function FollowCamera(name, position, scene) {
  6165. _super.call(this, name, position, scene);
  6166. this.radius = 12;
  6167. this.rotationOffset = 0;
  6168. this.heightOffset = 4;
  6169. this.cameraAcceleration = 0.05;
  6170. this.maxCameraSpeed = 20;
  6171. }
  6172. FollowCamera.prototype.getRadians = function (degrees) {
  6173. return degrees * Math.PI / 180;
  6174. };
  6175. FollowCamera.prototype.follow = function (cameraTarget) {
  6176. if (!cameraTarget)
  6177. return;
  6178. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6179. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6180. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6181. var dx = targetX - this.position.x;
  6182. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6183. var dz = (targetZ) - this.position.z;
  6184. var vx = dx * this.cameraAcceleration * 2;
  6185. var vy = dy * this.cameraAcceleration;
  6186. var vz = dz * this.cameraAcceleration * 2;
  6187. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6188. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6189. }
  6190. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6191. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6192. }
  6193. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6194. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6195. }
  6196. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6197. this.setTarget(cameraTarget.position);
  6198. };
  6199. FollowCamera.prototype._update = function () {
  6200. _super.prototype._update.call(this);
  6201. this.follow(this.target);
  6202. };
  6203. return FollowCamera;
  6204. })(BABYLON.TargetCamera);
  6205. BABYLON.FollowCamera = FollowCamera;
  6206. })(BABYLON || (BABYLON = {}));
  6207. //# sourceMappingURL=babylon.followCamera.js.map
  6208. var BABYLON;
  6209. (function (BABYLON) {
  6210. var FreeCamera = (function (_super) {
  6211. __extends(FreeCamera, _super);
  6212. function FreeCamera(name, position, scene) {
  6213. _super.call(this, name, position, scene);
  6214. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6215. this.keysUp = [38];
  6216. this.keysDown = [40];
  6217. this.keysLeft = [37];
  6218. this.keysRight = [39];
  6219. this.checkCollisions = false;
  6220. this.applyGravity = false;
  6221. this.angularSensibility = 2000.0;
  6222. this._keys = [];
  6223. this._collider = new BABYLON.Collider();
  6224. this._needMoveForGravity = true;
  6225. this._oldPosition = BABYLON.Vector3.Zero();
  6226. this._diffPosition = BABYLON.Vector3.Zero();
  6227. this._newPosition = BABYLON.Vector3.Zero();
  6228. }
  6229. // Controls
  6230. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6231. var _this = this;
  6232. var previousPosition;
  6233. var engine = this.getEngine();
  6234. if (this._attachedElement) {
  6235. return;
  6236. }
  6237. this._attachedElement = element;
  6238. if (this._onMouseDown === undefined) {
  6239. this._onMouseDown = function (evt) {
  6240. previousPosition = {
  6241. x: evt.clientX,
  6242. y: evt.clientY
  6243. };
  6244. if (!noPreventDefault) {
  6245. evt.preventDefault();
  6246. }
  6247. };
  6248. this._onMouseUp = function (evt) {
  6249. previousPosition = null;
  6250. if (!noPreventDefault) {
  6251. evt.preventDefault();
  6252. }
  6253. };
  6254. this._onMouseOut = function (evt) {
  6255. previousPosition = null;
  6256. _this._keys = [];
  6257. if (!noPreventDefault) {
  6258. evt.preventDefault();
  6259. }
  6260. };
  6261. this._onMouseMove = function (evt) {
  6262. if (!previousPosition && !engine.isPointerLock) {
  6263. return;
  6264. }
  6265. var offsetX;
  6266. var offsetY;
  6267. if (!engine.isPointerLock) {
  6268. offsetX = evt.clientX - previousPosition.x;
  6269. offsetY = evt.clientY - previousPosition.y;
  6270. } else {
  6271. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6272. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6273. }
  6274. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6275. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6276. previousPosition = {
  6277. x: evt.clientX,
  6278. y: evt.clientY
  6279. };
  6280. if (!noPreventDefault) {
  6281. evt.preventDefault();
  6282. }
  6283. };
  6284. this._onKeyDown = function (evt) {
  6285. 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) {
  6286. var index = _this._keys.indexOf(evt.keyCode);
  6287. if (index === -1) {
  6288. _this._keys.push(evt.keyCode);
  6289. }
  6290. if (!noPreventDefault) {
  6291. evt.preventDefault();
  6292. }
  6293. }
  6294. };
  6295. this._onKeyUp = function (evt) {
  6296. 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) {
  6297. var index = _this._keys.indexOf(evt.keyCode);
  6298. if (index >= 0) {
  6299. _this._keys.splice(index, 1);
  6300. }
  6301. if (!noPreventDefault) {
  6302. evt.preventDefault();
  6303. }
  6304. }
  6305. };
  6306. this._onLostFocus = function () {
  6307. _this._keys = [];
  6308. };
  6309. this._reset = function () {
  6310. _this._keys = [];
  6311. previousPosition = null;
  6312. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6313. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6314. };
  6315. }
  6316. element.addEventListener("mousedown", this._onMouseDown, false);
  6317. element.addEventListener("mouseup", this._onMouseUp, false);
  6318. element.addEventListener("mouseout", this._onMouseOut, false);
  6319. element.addEventListener("mousemove", this._onMouseMove, false);
  6320. BABYLON.Tools.RegisterTopRootEvents([
  6321. { name: "keydown", handler: this._onKeyDown },
  6322. { name: "keyup", handler: this._onKeyUp },
  6323. { name: "blur", handler: this._onLostFocus }
  6324. ]);
  6325. };
  6326. FreeCamera.prototype.detachControl = function (element) {
  6327. if (this._attachedElement != element) {
  6328. return;
  6329. }
  6330. element.removeEventListener("mousedown", this._onMouseDown);
  6331. element.removeEventListener("mouseup", this._onMouseUp);
  6332. element.removeEventListener("mouseout", this._onMouseOut);
  6333. element.removeEventListener("mousemove", this._onMouseMove);
  6334. BABYLON.Tools.UnregisterTopRootEvents([
  6335. { name: "keydown", handler: this._onKeyDown },
  6336. { name: "keyup", handler: this._onKeyUp },
  6337. { name: "blur", handler: this._onLostFocus }
  6338. ]);
  6339. this._attachedElement = null;
  6340. if (this._reset) {
  6341. this._reset();
  6342. }
  6343. };
  6344. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6345. var globalPosition;
  6346. if (this.parent) {
  6347. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6348. } else {
  6349. globalPosition = this.position;
  6350. }
  6351. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6352. this._collider.radius = this.ellipsoid;
  6353. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6354. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6355. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6356. this.position.addInPlace(this._diffPosition);
  6357. if (this.onCollide) {
  6358. this.onCollide(this._collider.collidedMesh);
  6359. }
  6360. }
  6361. };
  6362. FreeCamera.prototype._checkInputs = function () {
  6363. if (!this._localDirection) {
  6364. this._localDirection = BABYLON.Vector3.Zero();
  6365. this._transformedDirection = BABYLON.Vector3.Zero();
  6366. }
  6367. for (var index = 0; index < this._keys.length; index++) {
  6368. var keyCode = this._keys[index];
  6369. var speed = this._computeLocalCameraSpeed();
  6370. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6371. this._localDirection.copyFromFloats(-speed, 0, 0);
  6372. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6373. this._localDirection.copyFromFloats(0, 0, speed);
  6374. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6375. this._localDirection.copyFromFloats(speed, 0, 0);
  6376. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6377. this._localDirection.copyFromFloats(0, 0, -speed);
  6378. }
  6379. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6380. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6381. this.cameraDirection.addInPlace(this._transformedDirection);
  6382. }
  6383. };
  6384. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6385. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6386. };
  6387. FreeCamera.prototype._updatePosition = function () {
  6388. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6389. this._collideWithWorld(this.cameraDirection);
  6390. if (this.applyGravity) {
  6391. var oldPosition = this.position;
  6392. this._collideWithWorld(this.getScene().gravity);
  6393. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6394. }
  6395. } else {
  6396. this.position.addInPlace(this.cameraDirection);
  6397. }
  6398. };
  6399. FreeCamera.prototype._update = function () {
  6400. this._checkInputs();
  6401. _super.prototype._update.call(this);
  6402. };
  6403. return FreeCamera;
  6404. })(BABYLON.TargetCamera);
  6405. BABYLON.FreeCamera = FreeCamera;
  6406. })(BABYLON || (BABYLON = {}));
  6407. //# sourceMappingURL=babylon.freeCamera.js.map
  6408. var BABYLON;
  6409. (function (BABYLON) {
  6410. // We're mainly based on the logic defined into the FreeCamera code
  6411. var TouchCamera = (function (_super) {
  6412. __extends(TouchCamera, _super);
  6413. function TouchCamera(name, position, scene) {
  6414. _super.call(this, name, position, scene);
  6415. this._offsetX = null;
  6416. this._offsetY = null;
  6417. this._pointerCount = 0;
  6418. this._pointerPressed = [];
  6419. this.angularSensibility = 200000.0;
  6420. this.moveSensibility = 500.0;
  6421. }
  6422. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6423. var _this = this;
  6424. var previousPosition;
  6425. if (this._attachedCanvas) {
  6426. return;
  6427. }
  6428. this._attachedCanvas = canvas;
  6429. if (this._onPointerDown === undefined) {
  6430. this._onPointerDown = function (evt) {
  6431. if (!noPreventDefault) {
  6432. evt.preventDefault();
  6433. }
  6434. _this._pointerPressed.push(evt.pointerId);
  6435. if (_this._pointerPressed.length !== 1) {
  6436. return;
  6437. }
  6438. previousPosition = {
  6439. x: evt.clientX,
  6440. y: evt.clientY
  6441. };
  6442. };
  6443. this._onPointerUp = function (evt) {
  6444. if (!noPreventDefault) {
  6445. evt.preventDefault();
  6446. }
  6447. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6448. if (index === -1) {
  6449. return;
  6450. }
  6451. _this._pointerPressed.splice(index, 1);
  6452. if (index != 0) {
  6453. return;
  6454. }
  6455. previousPosition = null;
  6456. _this._offsetX = null;
  6457. _this._offsetY = null;
  6458. };
  6459. this._onPointerMove = function (evt) {
  6460. if (!noPreventDefault) {
  6461. evt.preventDefault();
  6462. }
  6463. if (!previousPosition) {
  6464. return;
  6465. }
  6466. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6467. if (index != 0) {
  6468. return;
  6469. }
  6470. _this._offsetX = evt.clientX - previousPosition.x;
  6471. _this._offsetY = -(evt.clientY - previousPosition.y);
  6472. };
  6473. this._onLostFocus = function () {
  6474. _this._offsetX = null;
  6475. _this._offsetY = null;
  6476. };
  6477. }
  6478. canvas.addEventListener("pointerdown", this._onPointerDown);
  6479. canvas.addEventListener("pointerup", this._onPointerUp);
  6480. canvas.addEventListener("pointerout", this._onPointerUp);
  6481. canvas.addEventListener("pointermove", this._onPointerMove);
  6482. BABYLON.Tools.RegisterTopRootEvents([
  6483. { name: "blur", handler: this._onLostFocus }
  6484. ]);
  6485. };
  6486. TouchCamera.prototype.detachControl = function (canvas) {
  6487. if (this._attachedCanvas != canvas) {
  6488. return;
  6489. }
  6490. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6491. canvas.removeEventListener("pointerup", this._onPointerUp);
  6492. canvas.removeEventListener("pointerout", this._onPointerUp);
  6493. canvas.removeEventListener("pointermove", this._onPointerMove);
  6494. BABYLON.Tools.UnregisterTopRootEvents([
  6495. { name: "blur", handler: this._onLostFocus }
  6496. ]);
  6497. this._attachedCanvas = null;
  6498. };
  6499. TouchCamera.prototype._checkInputs = function () {
  6500. if (!this._offsetX) {
  6501. return;
  6502. }
  6503. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6504. if (this._pointerPressed.length > 1) {
  6505. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6506. } else {
  6507. var speed = this._computeLocalCameraSpeed();
  6508. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6509. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6510. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6511. }
  6512. };
  6513. return TouchCamera;
  6514. })(BABYLON.FreeCamera);
  6515. BABYLON.TouchCamera = TouchCamera;
  6516. })(BABYLON || (BABYLON = {}));
  6517. //# sourceMappingURL=babylon.touchCamera.js.map
  6518. var BABYLON;
  6519. (function (BABYLON) {
  6520. // We're mainly based on the logic defined into the FreeCamera code
  6521. var DeviceOrientationCamera = (function (_super) {
  6522. __extends(DeviceOrientationCamera, _super);
  6523. function DeviceOrientationCamera(name, position, scene) {
  6524. var _this = this;
  6525. _super.call(this, name, position, scene);
  6526. this._offsetX = null;
  6527. this._offsetY = null;
  6528. this._orientationGamma = 0;
  6529. this._orientationBeta = 0;
  6530. this._initialOrientationGamma = 0;
  6531. this._initialOrientationBeta = 0;
  6532. this.angularSensibility = 10000.0;
  6533. this.moveSensibility = 50.0;
  6534. window.addEventListener("resize", function () {
  6535. _this._initialOrientationGamma = null;
  6536. }, false);
  6537. }
  6538. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6539. var _this = this;
  6540. if (this._attachedCanvas) {
  6541. return;
  6542. }
  6543. this._attachedCanvas = canvas;
  6544. if (!this._orientationChanged) {
  6545. this._orientationChanged = function (evt) {
  6546. if (!_this._initialOrientationGamma) {
  6547. _this._initialOrientationGamma = evt.gamma;
  6548. _this._initialOrientationBeta = evt.beta;
  6549. }
  6550. _this._orientationGamma = evt.gamma;
  6551. _this._orientationBeta = evt.beta;
  6552. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6553. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6554. };
  6555. }
  6556. window.addEventListener("deviceorientation", this._orientationChanged);
  6557. };
  6558. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6559. if (this._attachedCanvas != canvas) {
  6560. return;
  6561. }
  6562. window.removeEventListener("deviceorientation", this._orientationChanged);
  6563. this._attachedCanvas = null;
  6564. this._orientationGamma = 0;
  6565. this._orientationBeta = 0;
  6566. this._initialOrientationGamma = 0;
  6567. this._initialOrientationBeta = 0;
  6568. };
  6569. DeviceOrientationCamera.prototype._checkInputs = function () {
  6570. if (!this._offsetX) {
  6571. return;
  6572. }
  6573. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6574. var speed = this._computeLocalCameraSpeed();
  6575. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6576. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6577. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6578. };
  6579. return DeviceOrientationCamera;
  6580. })(BABYLON.FreeCamera);
  6581. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6582. })(BABYLON || (BABYLON = {}));
  6583. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6584. var BABYLON;
  6585. (function (BABYLON) {
  6586. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6587. var ArcRotateCamera = (function (_super) {
  6588. __extends(ArcRotateCamera, _super);
  6589. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6590. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6591. this.alpha = alpha;
  6592. this.beta = beta;
  6593. this.radius = radius;
  6594. this.target = target;
  6595. this.inertialAlphaOffset = 0;
  6596. this.inertialBetaOffset = 0;
  6597. this.inertialRadiusOffset = 0;
  6598. this.lowerAlphaLimit = null;
  6599. this.upperAlphaLimit = null;
  6600. this.lowerBetaLimit = 0.01;
  6601. this.upperBetaLimit = Math.PI;
  6602. this.lowerRadiusLimit = null;
  6603. this.upperRadiusLimit = null;
  6604. this.angularSensibility = 1000.0;
  6605. this.wheelPrecision = 3.0;
  6606. this.keysUp = [38];
  6607. this.keysDown = [40];
  6608. this.keysLeft = [37];
  6609. this.keysRight = [39];
  6610. this.zoomOnFactor = 1;
  6611. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6612. this._keys = [];
  6613. this._viewMatrix = new BABYLON.Matrix();
  6614. this.checkCollisions = false;
  6615. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6616. this._collider = new BABYLON.Collider();
  6617. this._previousPosition = BABYLON.Vector3.Zero();
  6618. this._collisionVelocity = BABYLON.Vector3.Zero();
  6619. this._newPosition = BABYLON.Vector3.Zero();
  6620. // Pinch
  6621. // value for pinch step scaling
  6622. // set to 20 by default
  6623. this.pinchPrecision = 20;
  6624. this.getViewMatrix();
  6625. }
  6626. ArcRotateCamera.prototype._getTargetPosition = function () {
  6627. return this.target.position || this.target;
  6628. };
  6629. // Cache
  6630. ArcRotateCamera.prototype._initCache = function () {
  6631. _super.prototype._initCache.call(this);
  6632. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6633. this._cache.alpha = undefined;
  6634. this._cache.beta = undefined;
  6635. this._cache.radius = undefined;
  6636. this._cache.targetScreenOffset = undefined;
  6637. };
  6638. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6639. if (!ignoreParentClass) {
  6640. _super.prototype._updateCache.call(this);
  6641. }
  6642. this._cache.target.copyFrom(this._getTargetPosition());
  6643. this._cache.alpha = this.alpha;
  6644. this._cache.beta = this.beta;
  6645. this._cache.radius = this.radius;
  6646. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6647. };
  6648. // Synchronized
  6649. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6650. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6651. return false;
  6652. 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);
  6653. };
  6654. // Methods
  6655. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6656. var _this = this;
  6657. var previousPosition;
  6658. var pointerId;
  6659. // to know if pinch started
  6660. var pinchStarted = false;
  6661. // two pinch point on X
  6662. // that will use for find if user action is pinch open or pinch close
  6663. var pinchPointX1, pinchPointX2;
  6664. if (this._attachedElement) {
  6665. return;
  6666. }
  6667. this._attachedElement = element;
  6668. var engine = this.getEngine();
  6669. if (this._onPointerDown === undefined) {
  6670. this._onPointerDown = function (evt) {
  6671. if (pointerId) {
  6672. return;
  6673. }
  6674. pointerId = evt.pointerId;
  6675. previousPosition = {
  6676. x: evt.clientX,
  6677. y: evt.clientY
  6678. };
  6679. if (!noPreventDefault) {
  6680. evt.preventDefault();
  6681. }
  6682. };
  6683. this._onPointerUp = function (evt) {
  6684. previousPosition = null;
  6685. pointerId = null;
  6686. if (!noPreventDefault) {
  6687. evt.preventDefault();
  6688. }
  6689. };
  6690. this._onPointerMove = function (evt) {
  6691. if (!previousPosition) {
  6692. return;
  6693. }
  6694. if (pointerId !== evt.pointerId) {
  6695. return;
  6696. }
  6697. // return pinch is started
  6698. if (pinchStarted) {
  6699. return;
  6700. }
  6701. var offsetX = evt.clientX - previousPosition.x;
  6702. var offsetY = evt.clientY - previousPosition.y;
  6703. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6704. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6705. previousPosition = {
  6706. x: evt.clientX,
  6707. y: evt.clientY
  6708. };
  6709. if (!noPreventDefault) {
  6710. evt.preventDefault();
  6711. }
  6712. };
  6713. this._onMouseMove = function (evt) {
  6714. if (!engine.isPointerLock) {
  6715. return;
  6716. }
  6717. // return pinch is started
  6718. if (pinchStarted) {
  6719. return;
  6720. }
  6721. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6722. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6723. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6724. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6725. if (!noPreventDefault) {
  6726. evt.preventDefault();
  6727. }
  6728. };
  6729. this._wheel = function (event) {
  6730. var delta = 0;
  6731. if (event.wheelDelta) {
  6732. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6733. } else if (event.detail) {
  6734. delta = -event.detail / _this.wheelPrecision;
  6735. }
  6736. if (delta)
  6737. _this.inertialRadiusOffset += delta;
  6738. if (event.preventDefault) {
  6739. if (!noPreventDefault) {
  6740. event.preventDefault();
  6741. }
  6742. }
  6743. };
  6744. this._onKeyDown = function (evt) {
  6745. 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) {
  6746. var index = _this._keys.indexOf(evt.keyCode);
  6747. if (index === -1) {
  6748. _this._keys.push(evt.keyCode);
  6749. }
  6750. if (evt.preventDefault) {
  6751. if (!noPreventDefault) {
  6752. evt.preventDefault();
  6753. }
  6754. }
  6755. }
  6756. };
  6757. this._onKeyUp = function (evt) {
  6758. 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) {
  6759. var index = _this._keys.indexOf(evt.keyCode);
  6760. if (index >= 0) {
  6761. _this._keys.splice(index, 1);
  6762. }
  6763. if (evt.preventDefault) {
  6764. if (!noPreventDefault) {
  6765. evt.preventDefault();
  6766. }
  6767. }
  6768. }
  6769. };
  6770. this._onLostFocus = function () {
  6771. _this._keys = [];
  6772. pointerId = null;
  6773. };
  6774. this._onGestureStart = function (e) {
  6775. if (window.MSGesture === undefined) {
  6776. return;
  6777. }
  6778. if (!_this._MSGestureHandler) {
  6779. _this._MSGestureHandler = new MSGesture();
  6780. _this._MSGestureHandler.target = element;
  6781. }
  6782. _this._MSGestureHandler.addPointer(e.pointerId);
  6783. };
  6784. this._onGesture = function (e) {
  6785. _this.radius *= e.scale;
  6786. if (e.preventDefault) {
  6787. if (!noPreventDefault) {
  6788. e.stopPropagation();
  6789. e.preventDefault();
  6790. }
  6791. }
  6792. };
  6793. this._reset = function () {
  6794. _this._keys = [];
  6795. _this.inertialAlphaOffset = 0;
  6796. _this.inertialBetaOffset = 0;
  6797. _this.inertialRadiusOffset = 0;
  6798. previousPosition = null;
  6799. pointerId = null;
  6800. };
  6801. this._touchStart = function (event) {
  6802. if (event.touches.length == 2) {
  6803. //-- start pinch if two fingers on the screen
  6804. pinchStarted = true;
  6805. _this._pinchStart(event);
  6806. }
  6807. };
  6808. this._touchMove = function (event) {
  6809. if (pinchStarted) {
  6810. //-- make scaling
  6811. _this._pinchMove(event);
  6812. }
  6813. };
  6814. this._touchEnd = function (event) {
  6815. if (pinchStarted) {
  6816. //-- end of pinch
  6817. _this._pinchEnd(event);
  6818. }
  6819. };
  6820. this._pinchStart = function (event) {
  6821. // save origin touch point
  6822. pinchPointX1 = event.touches[0].clientX;
  6823. pinchPointX2 = event.touches[1].clientX;
  6824. // block the camera
  6825. // if not it rotate around target during pinch
  6826. pinchStarted = true;
  6827. };
  6828. this._pinchMove = function (event) {
  6829. // variable for new camera's radius
  6830. var delta = 0;
  6831. // variables to know if pinch open or pinch close
  6832. var direction = 1;
  6833. var distanceXOrigine, distanceXNow;
  6834. if (event.touches.length != 2)
  6835. return;
  6836. // calculate absolute distances of the two fingers
  6837. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6838. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6839. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6840. if (distanceXNow < distanceXOrigine) {
  6841. direction = -1;
  6842. }
  6843. // calculate new radius
  6844. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6845. // set new radius
  6846. _this.inertialRadiusOffset += delta;
  6847. // save origin touch point
  6848. pinchPointX1 = event.touches[0].clientX;
  6849. pinchPointX2 = event.touches[1].clientX;
  6850. };
  6851. this._pinchEnd = function (event) {
  6852. // cancel pinch and deblock camera rotation
  6853. pinchStarted = false;
  6854. };
  6855. }
  6856. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6857. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6858. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6859. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6860. element.addEventListener("mousemove", this._onMouseMove, false);
  6861. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6862. element.addEventListener("MSGestureChange", this._onGesture, false);
  6863. element.addEventListener('mousewheel', this._wheel, false);
  6864. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6865. // pinch
  6866. element.addEventListener('touchstart', this._touchStart, false);
  6867. element.addEventListener('touchmove', this._touchMove, false);
  6868. element.addEventListener('touchend', this._touchEnd, false);
  6869. BABYLON.Tools.RegisterTopRootEvents([
  6870. { name: "keydown", handler: this._onKeyDown },
  6871. { name: "keyup", handler: this._onKeyUp },
  6872. { name: "blur", handler: this._onLostFocus }
  6873. ]);
  6874. };
  6875. ArcRotateCamera.prototype.detachControl = function (element) {
  6876. if (this._attachedElement != element) {
  6877. return;
  6878. }
  6879. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6880. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6881. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6882. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6883. element.removeEventListener("mousemove", this._onMouseMove);
  6884. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6885. element.removeEventListener("MSGestureChange", this._onGesture);
  6886. element.removeEventListener('mousewheel', this._wheel);
  6887. element.removeEventListener('DOMMouseScroll', this._wheel);
  6888. // pinch
  6889. element.removeEventListener('touchstart', this._touchStart);
  6890. element.removeEventListener('touchmove', this._touchMove);
  6891. element.removeEventListener('touchend', this._touchEnd);
  6892. BABYLON.Tools.UnregisterTopRootEvents([
  6893. { name: "keydown", handler: this._onKeyDown },
  6894. { name: "keyup", handler: this._onKeyUp },
  6895. { name: "blur", handler: this._onLostFocus }
  6896. ]);
  6897. this._MSGestureHandler = null;
  6898. this._attachedElement = null;
  6899. if (this._reset) {
  6900. this._reset();
  6901. }
  6902. };
  6903. ArcRotateCamera.prototype._update = function () {
  6904. for (var index = 0; index < this._keys.length; index++) {
  6905. var keyCode = this._keys[index];
  6906. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6907. this.inertialAlphaOffset -= 0.01;
  6908. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6909. this.inertialBetaOffset -= 0.01;
  6910. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6911. this.inertialAlphaOffset += 0.01;
  6912. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6913. this.inertialBetaOffset += 0.01;
  6914. }
  6915. }
  6916. // Inertia
  6917. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6918. this.alpha += this.inertialAlphaOffset;
  6919. this.beta += this.inertialBetaOffset;
  6920. this.radius -= this.inertialRadiusOffset;
  6921. this.inertialAlphaOffset *= this.inertia;
  6922. this.inertialBetaOffset *= this.inertia;
  6923. this.inertialRadiusOffset *= this.inertia;
  6924. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6925. this.inertialAlphaOffset = 0;
  6926. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6927. this.inertialBetaOffset = 0;
  6928. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6929. this.inertialRadiusOffset = 0;
  6930. }
  6931. // Limits
  6932. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6933. this.alpha = this.lowerAlphaLimit;
  6934. }
  6935. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6936. this.alpha = this.upperAlphaLimit;
  6937. }
  6938. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6939. this.beta = this.lowerBetaLimit;
  6940. }
  6941. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6942. this.beta = this.upperBetaLimit;
  6943. }
  6944. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6945. this.radius = this.lowerRadiusLimit;
  6946. }
  6947. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6948. this.radius = this.upperRadiusLimit;
  6949. }
  6950. };
  6951. ArcRotateCamera.prototype.setPosition = function (position) {
  6952. var radiusv3 = position.subtract(this._getTargetPosition());
  6953. this.radius = radiusv3.length();
  6954. // Alpha
  6955. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6956. if (radiusv3.z < 0) {
  6957. this.alpha = 2 * Math.PI - this.alpha;
  6958. }
  6959. // Beta
  6960. this.beta = Math.acos(radiusv3.y / this.radius);
  6961. };
  6962. ArcRotateCamera.prototype._getViewMatrix = function () {
  6963. // Compute
  6964. var cosa = Math.cos(this.alpha);
  6965. var sina = Math.sin(this.alpha);
  6966. var cosb = Math.cos(this.beta);
  6967. var sinb = Math.sin(this.beta);
  6968. var target = this._getTargetPosition();
  6969. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6970. if (this.checkCollisions) {
  6971. this._collider.radius = this.collisionRadius;
  6972. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6973. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6974. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6975. this.position.copyFrom(this._previousPosition);
  6976. this.alpha = this._previousAlpha;
  6977. this.beta = this._previousBeta;
  6978. this.radius = this._previousRadius;
  6979. if (this.onCollide) {
  6980. this.onCollide(this._collider.collidedMesh);
  6981. }
  6982. }
  6983. }
  6984. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6985. this._previousAlpha = this.alpha;
  6986. this._previousBeta = this.beta;
  6987. this._previousRadius = this.radius;
  6988. this._previousPosition.copyFrom(this.position);
  6989. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6990. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6991. return this._viewMatrix;
  6992. };
  6993. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6994. meshes = meshes || this.getScene().meshes;
  6995. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6996. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6997. this.radius = distance * this.zoomOnFactor;
  6998. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6999. };
  7000. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7001. var meshesOrMinMaxVector;
  7002. var distance;
  7003. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7004. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7005. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7006. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7007. } else {
  7008. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7009. distance = meshesOrMinMaxVectorAndDistance.distance;
  7010. }
  7011. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7012. this.maxZ = distance * 2;
  7013. };
  7014. return ArcRotateCamera;
  7015. })(BABYLON.Camera);
  7016. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7017. })(BABYLON || (BABYLON = {}));
  7018. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7019. var BABYLON;
  7020. (function (BABYLON) {
  7021. var Scene = (function () {
  7022. // Constructor
  7023. function Scene(engine) {
  7024. // Members
  7025. this.autoClear = true;
  7026. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7027. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7028. this.forceWireframe = false;
  7029. this.forcePointsCloud = false;
  7030. this.forceShowBoundingBoxes = false;
  7031. this.animationsEnabled = true;
  7032. this.cameraToUseForPointers = null;
  7033. // Fog
  7034. this.fogEnabled = true;
  7035. this.fogMode = Scene.FOGMODE_NONE;
  7036. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7037. this.fogDensity = 0.1;
  7038. this.fogStart = 0;
  7039. this.fogEnd = 1000.0;
  7040. // Lights
  7041. this.shadowsEnabled = true;
  7042. this.lightsEnabled = true;
  7043. this.lights = new Array();
  7044. // Cameras
  7045. this.cameras = new Array();
  7046. this.activeCameras = new Array();
  7047. // Meshes
  7048. this.meshes = new Array();
  7049. // Geometries
  7050. this._geometries = new Array();
  7051. this.materials = new Array();
  7052. this.multiMaterials = new Array();
  7053. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7054. // Textures
  7055. this.texturesEnabled = true;
  7056. this.textures = new Array();
  7057. // Particles
  7058. this.particlesEnabled = true;
  7059. this.particleSystems = new Array();
  7060. // Sprites
  7061. this.spriteManagers = new Array();
  7062. // Layers
  7063. this.layers = new Array();
  7064. // Skeletons
  7065. this.skeletonsEnabled = true;
  7066. this.skeletons = new Array();
  7067. // Lens flares
  7068. this.lensFlaresEnabled = true;
  7069. this.lensFlareSystems = new Array();
  7070. // Collisions
  7071. this.collisionsEnabled = true;
  7072. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7073. // Postprocesses
  7074. this.postProcessesEnabled = true;
  7075. // Customs render targets
  7076. this.renderTargetsEnabled = true;
  7077. this.customRenderTargets = new Array();
  7078. // Imported meshes
  7079. this.importedMeshesFiles = new Array();
  7080. this._actionManagers = new Array();
  7081. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7082. // Procedural textures
  7083. this.proceduralTexturesEnabled = true;
  7084. this._proceduralTextures = new Array();
  7085. this.soundTracks = new Array();
  7086. this._totalVertices = 0;
  7087. this._activeVertices = 0;
  7088. this._activeParticles = 0;
  7089. this._lastFrameDuration = 0;
  7090. this._evaluateActiveMeshesDuration = 0;
  7091. this._renderTargetsDuration = 0;
  7092. this._particlesDuration = 0;
  7093. this._renderDuration = 0;
  7094. this._spritesDuration = 0;
  7095. this._animationRatio = 0;
  7096. this._renderId = 0;
  7097. this._executeWhenReadyTimeoutId = -1;
  7098. this._toBeDisposed = new BABYLON.SmartArray(256);
  7099. this._onReadyCallbacks = new Array();
  7100. this._pendingData = [];
  7101. this._onBeforeRenderCallbacks = new Array();
  7102. this._onAfterRenderCallbacks = new Array();
  7103. this._activeMeshes = new BABYLON.SmartArray(256);
  7104. this._processedMaterials = new BABYLON.SmartArray(256);
  7105. this._renderTargets = new BABYLON.SmartArray(256);
  7106. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7107. this._activeSkeletons = new BABYLON.SmartArray(32);
  7108. this._activeBones = 0;
  7109. this._activeAnimatables = new Array();
  7110. this._transformMatrix = BABYLON.Matrix.Zero();
  7111. this._scaledPosition = BABYLON.Vector3.Zero();
  7112. this._scaledVelocity = BABYLON.Vector3.Zero();
  7113. this._engine = engine;
  7114. engine.scenes.push(this);
  7115. this._renderingManager = new BABYLON.RenderingManager(this);
  7116. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7117. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7118. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7119. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7120. this.attachControl();
  7121. this._debugLayer = new BABYLON.DebugLayer(this);
  7122. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7123. }
  7124. Object.defineProperty(Scene.prototype, "debugLayer", {
  7125. // Properties
  7126. get: function () {
  7127. return this._debugLayer;
  7128. },
  7129. enumerable: true,
  7130. configurable: true
  7131. });
  7132. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7133. get: function () {
  7134. return this._meshUnderPointer;
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. Object.defineProperty(Scene.prototype, "pointerX", {
  7140. get: function () {
  7141. return this._pointerX;
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Object.defineProperty(Scene.prototype, "pointerY", {
  7147. get: function () {
  7148. return this._pointerY;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. Scene.prototype.getCachedMaterial = function () {
  7154. return this._cachedMaterial;
  7155. };
  7156. Scene.prototype.getBoundingBoxRenderer = function () {
  7157. return this._boundingBoxRenderer;
  7158. };
  7159. Scene.prototype.getOutlineRenderer = function () {
  7160. return this._outlineRenderer;
  7161. };
  7162. Scene.prototype.getEngine = function () {
  7163. return this._engine;
  7164. };
  7165. Scene.prototype.getTotalVertices = function () {
  7166. return this._totalVertices;
  7167. };
  7168. Scene.prototype.getActiveVertices = function () {
  7169. return this._activeVertices;
  7170. };
  7171. Scene.prototype.getActiveParticles = function () {
  7172. return this._activeParticles;
  7173. };
  7174. Scene.prototype.getActiveBones = function () {
  7175. return this._activeBones;
  7176. };
  7177. // Stats
  7178. Scene.prototype.getLastFrameDuration = function () {
  7179. return this._lastFrameDuration;
  7180. };
  7181. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7182. return this._evaluateActiveMeshesDuration;
  7183. };
  7184. Scene.prototype.getActiveMeshes = function () {
  7185. return this._activeMeshes;
  7186. };
  7187. Scene.prototype.getRenderTargetsDuration = function () {
  7188. return this._renderTargetsDuration;
  7189. };
  7190. Scene.prototype.getRenderDuration = function () {
  7191. return this._renderDuration;
  7192. };
  7193. Scene.prototype.getParticlesDuration = function () {
  7194. return this._particlesDuration;
  7195. };
  7196. Scene.prototype.getSpritesDuration = function () {
  7197. return this._spritesDuration;
  7198. };
  7199. Scene.prototype.getAnimationRatio = function () {
  7200. return this._animationRatio;
  7201. };
  7202. Scene.prototype.getRenderId = function () {
  7203. return this._renderId;
  7204. };
  7205. Scene.prototype._updatePointerPosition = function (evt) {
  7206. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7207. this._pointerX = evt.clientX - canvasRect.left;
  7208. this._pointerY = evt.clientY - canvasRect.top;
  7209. if (this.cameraToUseForPointers) {
  7210. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7211. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7212. }
  7213. };
  7214. // Pointers handling
  7215. Scene.prototype.attachControl = function () {
  7216. var _this = this;
  7217. this._onPointerMove = function (evt) {
  7218. var canvas = _this._engine.getRenderingCanvas();
  7219. _this._updatePointerPosition(evt);
  7220. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7221. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7222. }, false, _this.cameraToUseForPointers);
  7223. if (pickResult.hit) {
  7224. _this._meshUnderPointer = pickResult.pickedMesh;
  7225. _this.setPointerOverMesh(pickResult.pickedMesh);
  7226. canvas.style.cursor = "pointer";
  7227. } else {
  7228. _this.setPointerOverMesh(null);
  7229. canvas.style.cursor = "";
  7230. _this._meshUnderPointer = null;
  7231. }
  7232. };
  7233. this._onPointerDown = function (evt) {
  7234. var predicate = null;
  7235. if (!_this.onPointerDown) {
  7236. predicate = function (mesh) {
  7237. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7238. };
  7239. }
  7240. _this._updatePointerPosition(evt);
  7241. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7242. if (pickResult.hit) {
  7243. if (pickResult.pickedMesh.actionManager) {
  7244. switch (evt.button) {
  7245. case 0:
  7246. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7247. break;
  7248. case 1:
  7249. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7250. break;
  7251. case 2:
  7252. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7253. break;
  7254. }
  7255. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7256. }
  7257. }
  7258. if (_this.onPointerDown) {
  7259. _this.onPointerDown(evt, pickResult);
  7260. }
  7261. };
  7262. this._onKeyDown = function (evt) {
  7263. if (_this.actionManager) {
  7264. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7265. }
  7266. };
  7267. this._onKeyUp = function (evt) {
  7268. if (_this.actionManager) {
  7269. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7270. }
  7271. };
  7272. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7273. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7274. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7275. window.addEventListener("keydown", this._onKeyDown, false);
  7276. window.addEventListener("keyup", this._onKeyUp, false);
  7277. };
  7278. Scene.prototype.detachControl = function () {
  7279. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7280. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7281. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7282. window.removeEventListener("keydown", this._onKeyDown);
  7283. window.removeEventListener("keyup", this._onKeyUp);
  7284. };
  7285. // Ready
  7286. Scene.prototype.isReady = function () {
  7287. if (this._pendingData.length > 0) {
  7288. return false;
  7289. }
  7290. for (var index = 0; index < this._geometries.length; index++) {
  7291. var geometry = this._geometries[index];
  7292. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7293. return false;
  7294. }
  7295. }
  7296. for (index = 0; index < this.meshes.length; index++) {
  7297. var mesh = this.meshes[index];
  7298. if (!mesh.isReady()) {
  7299. return false;
  7300. }
  7301. var mat = mesh.material;
  7302. if (mat) {
  7303. if (!mat.isReady(mesh)) {
  7304. return false;
  7305. }
  7306. }
  7307. }
  7308. return true;
  7309. };
  7310. Scene.prototype.resetCachedMaterial = function () {
  7311. this._cachedMaterial = null;
  7312. };
  7313. Scene.prototype.registerBeforeRender = function (func) {
  7314. this._onBeforeRenderCallbacks.push(func);
  7315. };
  7316. Scene.prototype.unregisterBeforeRender = function (func) {
  7317. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7318. if (index > -1) {
  7319. this._onBeforeRenderCallbacks.splice(index, 1);
  7320. }
  7321. };
  7322. Scene.prototype.registerAfterRender = function (func) {
  7323. this._onAfterRenderCallbacks.push(func);
  7324. };
  7325. Scene.prototype.unregisterAfterRender = function (func) {
  7326. var index = this._onAfterRenderCallbacks.indexOf(func);
  7327. if (index > -1) {
  7328. this._onAfterRenderCallbacks.splice(index, 1);
  7329. }
  7330. };
  7331. Scene.prototype._addPendingData = function (data) {
  7332. this._pendingData.push(data);
  7333. };
  7334. Scene.prototype._removePendingData = function (data) {
  7335. var index = this._pendingData.indexOf(data);
  7336. if (index !== -1) {
  7337. this._pendingData.splice(index, 1);
  7338. }
  7339. };
  7340. Scene.prototype.getWaitingItemsCount = function () {
  7341. return this._pendingData.length;
  7342. };
  7343. Scene.prototype.executeWhenReady = function (func) {
  7344. var _this = this;
  7345. this._onReadyCallbacks.push(func);
  7346. if (this._executeWhenReadyTimeoutId !== -1) {
  7347. return;
  7348. }
  7349. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7350. _this._checkIsReady();
  7351. }, 150);
  7352. };
  7353. Scene.prototype._checkIsReady = function () {
  7354. var _this = this;
  7355. if (this.isReady()) {
  7356. this._onReadyCallbacks.forEach(function (func) {
  7357. func();
  7358. });
  7359. this._onReadyCallbacks = [];
  7360. this._executeWhenReadyTimeoutId = -1;
  7361. return;
  7362. }
  7363. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7364. _this._checkIsReady();
  7365. }, 150);
  7366. };
  7367. // Animations
  7368. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7369. if (speedRatio === undefined) {
  7370. speedRatio = 1.0;
  7371. }
  7372. this.stopAnimation(target);
  7373. if (!animatable) {
  7374. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7375. }
  7376. // Local animations
  7377. if (target.animations) {
  7378. animatable.appendAnimations(target, target.animations);
  7379. }
  7380. // Children animations
  7381. if (target.getAnimatables) {
  7382. var animatables = target.getAnimatables();
  7383. for (var index = 0; index < animatables.length; index++) {
  7384. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7385. }
  7386. }
  7387. return animatable;
  7388. };
  7389. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7390. if (speedRatio === undefined) {
  7391. speedRatio = 1.0;
  7392. }
  7393. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7394. return animatable;
  7395. };
  7396. Scene.prototype.getAnimatableByTarget = function (target) {
  7397. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7398. if (this._activeAnimatables[index].target === target) {
  7399. return this._activeAnimatables[index];
  7400. }
  7401. }
  7402. return null;
  7403. };
  7404. Scene.prototype.stopAnimation = function (target) {
  7405. var animatable = this.getAnimatableByTarget(target);
  7406. if (animatable) {
  7407. animatable.stop();
  7408. }
  7409. };
  7410. Scene.prototype._animate = function () {
  7411. if (!this.animationsEnabled) {
  7412. return;
  7413. }
  7414. if (!this._animationStartDate) {
  7415. this._animationStartDate = BABYLON.Tools.Now;
  7416. }
  7417. // Getting time
  7418. var now = BABYLON.Tools.Now;
  7419. var delay = now - this._animationStartDate;
  7420. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7421. if (!this._activeAnimatables[index]._animate(delay)) {
  7422. this._activeAnimatables.splice(index, 1);
  7423. index--;
  7424. }
  7425. }
  7426. };
  7427. // Matrix
  7428. Scene.prototype.getViewMatrix = function () {
  7429. return this._viewMatrix;
  7430. };
  7431. Scene.prototype.getProjectionMatrix = function () {
  7432. return this._projectionMatrix;
  7433. };
  7434. Scene.prototype.getTransformMatrix = function () {
  7435. return this._transformMatrix;
  7436. };
  7437. Scene.prototype.setTransformMatrix = function (view, projection) {
  7438. this._viewMatrix = view;
  7439. this._projectionMatrix = projection;
  7440. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7441. };
  7442. // Methods
  7443. Scene.prototype.setActiveCameraByID = function (id) {
  7444. var camera = this.getCameraByID(id);
  7445. if (camera) {
  7446. this.activeCamera = camera;
  7447. return camera;
  7448. }
  7449. return null;
  7450. };
  7451. Scene.prototype.setActiveCameraByName = function (name) {
  7452. var camera = this.getCameraByName(name);
  7453. if (camera) {
  7454. this.activeCamera = camera;
  7455. return camera;
  7456. }
  7457. return null;
  7458. };
  7459. Scene.prototype.getMaterialByID = function (id) {
  7460. for (var index = 0; index < this.materials.length; index++) {
  7461. if (this.materials[index].id === id) {
  7462. return this.materials[index];
  7463. }
  7464. }
  7465. return null;
  7466. };
  7467. Scene.prototype.getMaterialByName = function (name) {
  7468. for (var index = 0; index < this.materials.length; index++) {
  7469. if (this.materials[index].name === name) {
  7470. return this.materials[index];
  7471. }
  7472. }
  7473. return null;
  7474. };
  7475. Scene.prototype.getCameraByID = function (id) {
  7476. for (var index = 0; index < this.cameras.length; index++) {
  7477. if (this.cameras[index].id === id) {
  7478. return this.cameras[index];
  7479. }
  7480. }
  7481. return null;
  7482. };
  7483. Scene.prototype.getCameraByName = function (name) {
  7484. for (var index = 0; index < this.cameras.length; index++) {
  7485. if (this.cameras[index].name === name) {
  7486. return this.cameras[index];
  7487. }
  7488. }
  7489. return null;
  7490. };
  7491. Scene.prototype.getLightByName = function (name) {
  7492. for (var index = 0; index < this.lights.length; index++) {
  7493. if (this.lights[index].name === name) {
  7494. return this.lights[index];
  7495. }
  7496. }
  7497. return null;
  7498. };
  7499. Scene.prototype.getLightByID = function (id) {
  7500. for (var index = 0; index < this.lights.length; index++) {
  7501. if (this.lights[index].id === id) {
  7502. return this.lights[index];
  7503. }
  7504. }
  7505. return null;
  7506. };
  7507. Scene.prototype.getGeometryByID = function (id) {
  7508. for (var index = 0; index < this._geometries.length; index++) {
  7509. if (this._geometries[index].id === id) {
  7510. return this._geometries[index];
  7511. }
  7512. }
  7513. return null;
  7514. };
  7515. Scene.prototype.pushGeometry = function (geometry, force) {
  7516. if (!force && this.getGeometryByID(geometry.id)) {
  7517. return false;
  7518. }
  7519. this._geometries.push(geometry);
  7520. return true;
  7521. };
  7522. Scene.prototype.getGeometries = function () {
  7523. return this._geometries;
  7524. };
  7525. Scene.prototype.getMeshByID = function (id) {
  7526. for (var index = 0; index < this.meshes.length; index++) {
  7527. if (this.meshes[index].id === id) {
  7528. return this.meshes[index];
  7529. }
  7530. }
  7531. return null;
  7532. };
  7533. Scene.prototype.getLastMeshByID = function (id) {
  7534. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7535. if (this.meshes[index].id === id) {
  7536. return this.meshes[index];
  7537. }
  7538. }
  7539. return null;
  7540. };
  7541. Scene.prototype.getLastEntryByID = function (id) {
  7542. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7543. if (this.meshes[index].id === id) {
  7544. return this.meshes[index];
  7545. }
  7546. }
  7547. for (index = this.cameras.length - 1; index >= 0; index--) {
  7548. if (this.cameras[index].id === id) {
  7549. return this.cameras[index];
  7550. }
  7551. }
  7552. for (index = this.lights.length - 1; index >= 0; index--) {
  7553. if (this.lights[index].id === id) {
  7554. return this.lights[index];
  7555. }
  7556. }
  7557. return null;
  7558. };
  7559. Scene.prototype.getMeshByName = function (name) {
  7560. for (var index = 0; index < this.meshes.length; index++) {
  7561. if (this.meshes[index].name === name) {
  7562. return this.meshes[index];
  7563. }
  7564. }
  7565. return null;
  7566. };
  7567. Scene.prototype.getLastSkeletonByID = function (id) {
  7568. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7569. if (this.skeletons[index].id === id) {
  7570. return this.skeletons[index];
  7571. }
  7572. }
  7573. return null;
  7574. };
  7575. Scene.prototype.getSkeletonById = function (id) {
  7576. for (var index = 0; index < this.skeletons.length; index++) {
  7577. if (this.skeletons[index].id === id) {
  7578. return this.skeletons[index];
  7579. }
  7580. }
  7581. return null;
  7582. };
  7583. Scene.prototype.getSkeletonByName = function (name) {
  7584. for (var index = 0; index < this.skeletons.length; index++) {
  7585. if (this.skeletons[index].name === name) {
  7586. return this.skeletons[index];
  7587. }
  7588. }
  7589. return null;
  7590. };
  7591. Scene.prototype.isActiveMesh = function (mesh) {
  7592. return (this._activeMeshes.indexOf(mesh) !== -1);
  7593. };
  7594. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7595. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7596. var material = subMesh.getMaterial();
  7597. if (mesh.showSubMeshesBoundingBox) {
  7598. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7599. }
  7600. if (material) {
  7601. // Render targets
  7602. if (material.getRenderTargetTextures) {
  7603. if (this._processedMaterials.indexOf(material) === -1) {
  7604. this._processedMaterials.push(material);
  7605. this._renderTargets.concat(material.getRenderTargetTextures());
  7606. }
  7607. }
  7608. // Dispatch
  7609. this._activeVertices += subMesh.indexCount;
  7610. this._renderingManager.dispatch(subMesh);
  7611. }
  7612. }
  7613. };
  7614. Scene.prototype._evaluateActiveMeshes = function () {
  7615. this._activeMeshes.reset();
  7616. this._renderingManager.reset();
  7617. this._processedMaterials.reset();
  7618. this._activeParticleSystems.reset();
  7619. this._activeSkeletons.reset();
  7620. this._boundingBoxRenderer.reset();
  7621. if (!this._frustumPlanes) {
  7622. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7623. } else {
  7624. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7625. }
  7626. // Meshes
  7627. var meshes;
  7628. var len;
  7629. if (this._selectionOctree) {
  7630. var selection = this._selectionOctree.select(this._frustumPlanes);
  7631. meshes = selection.data;
  7632. len = selection.length;
  7633. } else {
  7634. len = this.meshes.length;
  7635. meshes = this.meshes;
  7636. }
  7637. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7638. var mesh = meshes[meshIndex];
  7639. if (mesh.isBlocked) {
  7640. continue;
  7641. }
  7642. this._totalVertices += mesh.getTotalVertices();
  7643. if (!mesh.isReady()) {
  7644. continue;
  7645. }
  7646. mesh.computeWorldMatrix();
  7647. // Intersections
  7648. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7649. this._meshesForIntersections.pushNoDuplicate(mesh);
  7650. }
  7651. // Switch to current LOD
  7652. var meshLOD = mesh.getLOD(this.activeCamera);
  7653. if (!meshLOD) {
  7654. continue;
  7655. }
  7656. mesh._preActivate();
  7657. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7658. this._activeMeshes.push(mesh);
  7659. mesh._activate(this._renderId);
  7660. this._activeMesh(meshLOD);
  7661. }
  7662. }
  7663. // Particle systems
  7664. var beforeParticlesDate = BABYLON.Tools.Now;
  7665. if (this.particlesEnabled) {
  7666. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7667. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7668. var particleSystem = this.particleSystems[particleIndex];
  7669. if (!particleSystem.isStarted()) {
  7670. continue;
  7671. }
  7672. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7673. this._activeParticleSystems.push(particleSystem);
  7674. particleSystem.animate();
  7675. }
  7676. }
  7677. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7678. }
  7679. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7680. };
  7681. Scene.prototype._activeMesh = function (mesh) {
  7682. if (mesh.skeleton && this.skeletonsEnabled) {
  7683. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7684. }
  7685. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7686. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7687. }
  7688. if (mesh && mesh.subMeshes) {
  7689. // Submeshes Octrees
  7690. var len;
  7691. var subMeshes;
  7692. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7693. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7694. len = intersections.length;
  7695. subMeshes = intersections.data;
  7696. } else {
  7697. subMeshes = mesh.subMeshes;
  7698. len = subMeshes.length;
  7699. }
  7700. for (var subIndex = 0; subIndex < len; subIndex++) {
  7701. var subMesh = subMeshes[subIndex];
  7702. this._evaluateSubMesh(subMesh, mesh);
  7703. }
  7704. }
  7705. };
  7706. Scene.prototype.updateTransformMatrix = function (force) {
  7707. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7708. };
  7709. Scene.prototype._renderForCamera = function (camera) {
  7710. var engine = this._engine;
  7711. this.activeCamera = camera;
  7712. if (!this.activeCamera)
  7713. throw new Error("Active camera not set");
  7714. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7715. // Viewport
  7716. engine.setViewport(this.activeCamera.viewport);
  7717. // Camera
  7718. this._renderId++;
  7719. this.updateTransformMatrix();
  7720. if (this.beforeCameraRender) {
  7721. this.beforeCameraRender(this.activeCamera);
  7722. }
  7723. // Meshes
  7724. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7725. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7726. this._evaluateActiveMeshes();
  7727. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7728. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7729. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7730. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7731. skeleton.prepare();
  7732. this._activeBones += skeleton.bones.length;
  7733. }
  7734. // Render targets
  7735. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7736. if (this.renderTargetsEnabled) {
  7737. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7738. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7739. var renderTarget = this._renderTargets.data[renderIndex];
  7740. if (renderTarget._shouldRender()) {
  7741. this._renderId++;
  7742. renderTarget.render();
  7743. }
  7744. }
  7745. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7746. this._renderId++;
  7747. }
  7748. if (this._renderTargets.length > 0) {
  7749. engine.restoreDefaultFramebuffer();
  7750. }
  7751. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7752. // Prepare Frame
  7753. this.postProcessManager._prepareFrame();
  7754. var beforeRenderDate = BABYLON.Tools.Now;
  7755. // Backgrounds
  7756. if (this.layers.length) {
  7757. engine.setDepthBuffer(false);
  7758. var layerIndex;
  7759. var layer;
  7760. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7761. layer = this.layers[layerIndex];
  7762. if (layer.isBackground) {
  7763. layer.render();
  7764. }
  7765. }
  7766. engine.setDepthBuffer(true);
  7767. }
  7768. // Render
  7769. BABYLON.Tools.StartPerformanceCounter("Main render");
  7770. this._renderingManager.render(null, null, true, true);
  7771. BABYLON.Tools.EndPerformanceCounter("Main render");
  7772. // Bounding boxes
  7773. this._boundingBoxRenderer.render();
  7774. // Lens flares
  7775. if (this.lensFlaresEnabled) {
  7776. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7777. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7778. this.lensFlareSystems[lensFlareSystemIndex].render();
  7779. }
  7780. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7781. }
  7782. // Foregrounds
  7783. if (this.layers.length) {
  7784. engine.setDepthBuffer(false);
  7785. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7786. layer = this.layers[layerIndex];
  7787. if (!layer.isBackground) {
  7788. layer.render();
  7789. }
  7790. }
  7791. engine.setDepthBuffer(true);
  7792. }
  7793. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7794. // Finalize frame
  7795. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7796. // Update camera
  7797. this.activeCamera._updateFromScene();
  7798. // Reset some special arrays
  7799. this._renderTargets.reset();
  7800. if (this.afterCameraRender) {
  7801. this.afterCameraRender(this.activeCamera);
  7802. }
  7803. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7804. };
  7805. Scene.prototype._processSubCameras = function (camera) {
  7806. if (camera.subCameras.length === 0) {
  7807. this._renderForCamera(camera);
  7808. return;
  7809. }
  7810. for (var index = 0; index < camera.subCameras.length; index++) {
  7811. this._renderForCamera(camera.subCameras[index]);
  7812. }
  7813. this.activeCamera = camera;
  7814. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7815. // Update camera
  7816. this.activeCamera._updateFromScene();
  7817. };
  7818. Scene.prototype._checkIntersections = function () {
  7819. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7820. var sourceMesh = this._meshesForIntersections.data[index];
  7821. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7822. var action = sourceMesh.actionManager.actions[actionIndex];
  7823. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7824. var otherMesh = action.getTriggerParameter();
  7825. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7826. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7827. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7828. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7829. sourceMesh._intersectionsInProgress.push(otherMesh);
  7830. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7831. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7832. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7833. if (indexOfOther > -1) {
  7834. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7835. }
  7836. }
  7837. }
  7838. }
  7839. }
  7840. };
  7841. Scene.prototype.render = function () {
  7842. var startDate = BABYLON.Tools.Now;
  7843. this._particlesDuration = 0;
  7844. this._spritesDuration = 0;
  7845. this._activeParticles = 0;
  7846. this._renderDuration = 0;
  7847. this._renderTargetsDuration = 0;
  7848. this._evaluateActiveMeshesDuration = 0;
  7849. this._totalVertices = 0;
  7850. this._activeVertices = 0;
  7851. this._activeBones = 0;
  7852. this.getEngine().resetDrawCalls();
  7853. this._meshesForIntersections.reset();
  7854. this.resetCachedMaterial();
  7855. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7856. // Actions
  7857. if (this.actionManager) {
  7858. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7859. }
  7860. // Before render
  7861. if (this.beforeRender) {
  7862. this.beforeRender();
  7863. }
  7864. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7865. this._onBeforeRenderCallbacks[callbackIndex]();
  7866. }
  7867. // Animations
  7868. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7869. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7870. this._animate();
  7871. // Physics
  7872. if (this._physicsEngine) {
  7873. BABYLON.Tools.StartPerformanceCounter("Physics");
  7874. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7875. BABYLON.Tools.EndPerformanceCounter("Physics");
  7876. }
  7877. // Customs render targets
  7878. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7879. var engine = this.getEngine();
  7880. if (this.renderTargetsEnabled) {
  7881. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7882. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7883. var renderTarget = this.customRenderTargets[customIndex];
  7884. if (renderTarget._shouldRender()) {
  7885. this._renderId++;
  7886. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7887. if (!this.activeCamera)
  7888. throw new Error("Active camera not set");
  7889. // Viewport
  7890. engine.setViewport(this.activeCamera.viewport);
  7891. // Camera
  7892. this.updateTransformMatrix();
  7893. renderTarget.render();
  7894. }
  7895. }
  7896. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7897. this._renderId++;
  7898. }
  7899. if (this.customRenderTargets.length > 0) {
  7900. engine.restoreDefaultFramebuffer();
  7901. }
  7902. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7903. // Procedural textures
  7904. if (this.proceduralTexturesEnabled) {
  7905. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7906. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7907. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7908. if (proceduralTexture._shouldRender()) {
  7909. proceduralTexture.render();
  7910. }
  7911. }
  7912. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7913. }
  7914. // Clear
  7915. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7916. // Shadows
  7917. if (this.shadowsEnabled) {
  7918. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7919. var light = this.lights[lightIndex];
  7920. var shadowGenerator = light.getShadowGenerator();
  7921. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7922. this._renderTargets.push(shadowGenerator.getShadowMap());
  7923. }
  7924. }
  7925. }
  7926. // RenderPipeline
  7927. this.postProcessRenderPipelineManager.update();
  7928. // Multi-cameras?
  7929. if (this.activeCameras.length > 0) {
  7930. var currentRenderId = this._renderId;
  7931. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7932. this._renderId = currentRenderId;
  7933. this._processSubCameras(this.activeCameras[cameraIndex]);
  7934. }
  7935. } else {
  7936. if (!this.activeCamera) {
  7937. throw new Error("No camera defined");
  7938. }
  7939. this._processSubCameras(this.activeCamera);
  7940. }
  7941. // Intersection checks
  7942. this._checkIntersections();
  7943. // Update the audio listener attached to the camera
  7944. this._updateAudioParameters();
  7945. // After render
  7946. if (this.afterRender) {
  7947. this.afterRender();
  7948. }
  7949. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7950. this._onAfterRenderCallbacks[callbackIndex]();
  7951. }
  7952. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7953. this._toBeDisposed.data[index].dispose();
  7954. this._toBeDisposed[index] = null;
  7955. }
  7956. this._toBeDisposed.reset();
  7957. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7958. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7959. };
  7960. Scene.prototype._updateAudioParameters = function () {
  7961. var listeningCamera;
  7962. var audioEngine = this._engine.getAudioEngine();
  7963. if (this.activeCameras.length > 0) {
  7964. listeningCamera = this.activeCameras[0];
  7965. } else {
  7966. listeningCamera = this.activeCamera;
  7967. }
  7968. if (listeningCamera && audioEngine.canUseWebAudio) {
  7969. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7970. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7971. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7972. cameraDirection.normalize();
  7973. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7974. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7975. var sound = this.mainSoundTrack.soundCollection[i];
  7976. if (sound.useCustomAttenuation) {
  7977. sound.updateDistanceFromListener();
  7978. }
  7979. }
  7980. for (var i = 0; i < this.soundTracks.length; i++) {
  7981. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7982. var sound = this.soundTracks[i].soundCollection[j];
  7983. if (sound.useCustomAttenuation) {
  7984. sound.updateDistanceFromListener();
  7985. }
  7986. }
  7987. }
  7988. }
  7989. };
  7990. Scene.prototype.dispose = function () {
  7991. this.beforeRender = null;
  7992. this.afterRender = null;
  7993. this.skeletons = [];
  7994. this._boundingBoxRenderer.dispose();
  7995. // Debug layer
  7996. this.debugLayer.hide();
  7997. // Events
  7998. if (this.onDispose) {
  7999. this.onDispose();
  8000. }
  8001. this._onBeforeRenderCallbacks = [];
  8002. this._onAfterRenderCallbacks = [];
  8003. this.detachControl();
  8004. // Detach cameras
  8005. var canvas = this._engine.getRenderingCanvas();
  8006. var index;
  8007. for (index = 0; index < this.cameras.length; index++) {
  8008. this.cameras[index].detachControl(canvas);
  8009. }
  8010. while (this.lights.length) {
  8011. this.lights[0].dispose();
  8012. }
  8013. while (this.meshes.length) {
  8014. this.meshes[0].dispose(true);
  8015. }
  8016. while (this.cameras.length) {
  8017. this.cameras[0].dispose();
  8018. }
  8019. while (this.materials.length) {
  8020. this.materials[0].dispose();
  8021. }
  8022. while (this.particleSystems.length) {
  8023. this.particleSystems[0].dispose();
  8024. }
  8025. while (this.spriteManagers.length) {
  8026. this.spriteManagers[0].dispose();
  8027. }
  8028. while (this.layers.length) {
  8029. this.layers[0].dispose();
  8030. }
  8031. while (this.textures.length) {
  8032. this.textures[0].dispose();
  8033. }
  8034. // Post-processes
  8035. this.postProcessManager.dispose();
  8036. // Physics
  8037. if (this._physicsEngine) {
  8038. this.disablePhysicsEngine();
  8039. }
  8040. // Remove from engine
  8041. index = this._engine.scenes.indexOf(this);
  8042. if (index > -1) {
  8043. this._engine.scenes.splice(index, 1);
  8044. }
  8045. this._engine.wipeCaches();
  8046. };
  8047. // Collisions
  8048. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8049. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8050. position.divideToRef(collider.radius, this._scaledPosition);
  8051. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8052. collider.retry = 0;
  8053. collider.initialVelocity = this._scaledVelocity;
  8054. collider.initialPosition = this._scaledPosition;
  8055. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8056. finalPosition.multiplyInPlace(collider.radius);
  8057. };
  8058. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8059. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8060. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8061. if (collider.retry >= maximumRetry) {
  8062. finalPosition.copyFrom(position);
  8063. return;
  8064. }
  8065. collider._initialize(position, velocity, closeDistance);
  8066. for (var index = 0; index < this.meshes.length; index++) {
  8067. var mesh = this.meshes[index];
  8068. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8069. mesh._checkCollision(collider);
  8070. }
  8071. }
  8072. if (!collider.collisionFound) {
  8073. position.addToRef(velocity, finalPosition);
  8074. return;
  8075. }
  8076. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8077. collider._getResponse(position, velocity);
  8078. }
  8079. if (velocity.length() <= closeDistance) {
  8080. finalPosition.copyFrom(position);
  8081. return;
  8082. }
  8083. collider.retry++;
  8084. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8085. };
  8086. // Octrees
  8087. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8088. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8089. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8090. if (!this._selectionOctree) {
  8091. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8092. }
  8093. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8094. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8095. for (var index = 0; index < this.meshes.length; index++) {
  8096. var mesh = this.meshes[index];
  8097. mesh.computeWorldMatrix(true);
  8098. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8099. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8100. BABYLON.Tools.CheckExtends(minBox, min, max);
  8101. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8102. }
  8103. // Update octree
  8104. this._selectionOctree.update(min, max, this.meshes);
  8105. return this._selectionOctree;
  8106. };
  8107. // Picking
  8108. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8109. var engine = this._engine;
  8110. if (!camera) {
  8111. if (!this.activeCamera)
  8112. throw new Error("Active camera not set");
  8113. camera = this.activeCamera;
  8114. }
  8115. var cameraViewport = camera.viewport;
  8116. var viewport = cameraViewport.toGlobal(engine);
  8117. // Moving coordinates to local viewport world
  8118. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8119. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8120. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8121. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8122. };
  8123. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8124. var pickingInfo = null;
  8125. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8126. var mesh = this.meshes[meshIndex];
  8127. if (predicate) {
  8128. if (!predicate(mesh)) {
  8129. continue;
  8130. }
  8131. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8132. continue;
  8133. }
  8134. var world = mesh.getWorldMatrix();
  8135. var ray = rayFunction(world);
  8136. var result = mesh.intersects(ray, fastCheck);
  8137. if (!result || !result.hit)
  8138. continue;
  8139. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8140. continue;
  8141. pickingInfo = result;
  8142. if (fastCheck) {
  8143. break;
  8144. }
  8145. }
  8146. return pickingInfo || new BABYLON.PickingInfo();
  8147. };
  8148. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8149. var _this = this;
  8150. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8151. /// <param name="x">X position on screen</param>
  8152. /// <param name="y">Y position on screen</param>
  8153. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  8154. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8155. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  8156. return this._internalPick(function (world) {
  8157. return _this.createPickingRay(x, y, world, camera);
  8158. }, predicate, fastCheck);
  8159. };
  8160. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8161. var _this = this;
  8162. return this._internalPick(function (world) {
  8163. if (!_this._pickWithRayInverseMatrix) {
  8164. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8165. }
  8166. world.invertToRef(_this._pickWithRayInverseMatrix);
  8167. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8168. }, predicate, fastCheck);
  8169. };
  8170. Scene.prototype.setPointerOverMesh = function (mesh) {
  8171. if (this._pointerOverMesh === mesh) {
  8172. return;
  8173. }
  8174. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8175. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8176. }
  8177. this._pointerOverMesh = mesh;
  8178. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8179. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8180. }
  8181. };
  8182. Scene.prototype.getPointerOverMesh = function () {
  8183. return this._pointerOverMesh;
  8184. };
  8185. // Physics
  8186. Scene.prototype.getPhysicsEngine = function () {
  8187. return this._physicsEngine;
  8188. };
  8189. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8190. if (this._physicsEngine) {
  8191. return true;
  8192. }
  8193. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8194. if (!this._physicsEngine.isSupported()) {
  8195. this._physicsEngine = null;
  8196. return false;
  8197. }
  8198. this._physicsEngine._initialize(gravity);
  8199. return true;
  8200. };
  8201. Scene.prototype.disablePhysicsEngine = function () {
  8202. if (!this._physicsEngine) {
  8203. return;
  8204. }
  8205. this._physicsEngine.dispose();
  8206. this._physicsEngine = undefined;
  8207. };
  8208. Scene.prototype.isPhysicsEnabled = function () {
  8209. return this._physicsEngine !== undefined;
  8210. };
  8211. Scene.prototype.setGravity = function (gravity) {
  8212. if (!this._physicsEngine) {
  8213. return;
  8214. }
  8215. this._physicsEngine._setGravity(gravity);
  8216. };
  8217. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8218. if (parts.parts) {
  8219. options = parts;
  8220. parts = parts.parts;
  8221. }
  8222. if (!this._physicsEngine) {
  8223. return null;
  8224. }
  8225. for (var index = 0; index < parts.length; index++) {
  8226. var mesh = parts[index].mesh;
  8227. mesh._physicImpostor = parts[index].impostor;
  8228. mesh._physicsMass = options.mass / parts.length;
  8229. mesh._physicsFriction = options.friction;
  8230. mesh._physicRestitution = options.restitution;
  8231. }
  8232. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8233. };
  8234. //ANY
  8235. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8236. for (var index = 0; index < compound.parts.length; index++) {
  8237. var mesh = compound.parts[index].mesh;
  8238. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8239. this._physicsEngine._unregisterMesh(mesh);
  8240. }
  8241. };
  8242. // Tags
  8243. Scene.prototype._getByTags = function (list, tagsQuery) {
  8244. if (tagsQuery === undefined) {
  8245. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8246. return list;
  8247. }
  8248. var listByTags = [];
  8249. for (var i in list) {
  8250. var item = list[i];
  8251. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8252. listByTags.push(item);
  8253. }
  8254. }
  8255. return listByTags;
  8256. };
  8257. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8258. return this._getByTags(this.meshes, tagsQuery);
  8259. };
  8260. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8261. return this._getByTags(this.cameras, tagsQuery);
  8262. };
  8263. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8264. return this._getByTags(this.lights, tagsQuery);
  8265. };
  8266. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8267. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8268. };
  8269. Scene.FOGMODE_NONE = 0;
  8270. Scene.FOGMODE_EXP = 1;
  8271. Scene.FOGMODE_EXP2 = 2;
  8272. Scene.FOGMODE_LINEAR = 3;
  8273. Scene.MinDeltaTime = 1.0;
  8274. Scene.MaxDeltaTime = 1000.0;
  8275. return Scene;
  8276. })();
  8277. BABYLON.Scene = Scene;
  8278. })(BABYLON || (BABYLON = {}));
  8279. //# sourceMappingURL=babylon.scene.js.map
  8280. var BABYLON;
  8281. (function (BABYLON) {
  8282. var VertexBuffer = (function () {
  8283. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8284. if (engine instanceof BABYLON.Mesh) {
  8285. this._engine = engine.getScene().getEngine();
  8286. } else {
  8287. this._engine = engine;
  8288. }
  8289. this._updatable = updatable;
  8290. this._data = data;
  8291. if (!postponeInternalCreation) {
  8292. this.create();
  8293. }
  8294. this._kind = kind;
  8295. if (stride) {
  8296. this._strideSize = stride;
  8297. return;
  8298. }
  8299. switch (kind) {
  8300. case VertexBuffer.PositionKind:
  8301. this._strideSize = 3;
  8302. break;
  8303. case VertexBuffer.NormalKind:
  8304. this._strideSize = 3;
  8305. break;
  8306. case VertexBuffer.UVKind:
  8307. this._strideSize = 2;
  8308. break;
  8309. case VertexBuffer.UV2Kind:
  8310. this._strideSize = 2;
  8311. break;
  8312. case VertexBuffer.ColorKind:
  8313. this._strideSize = 4;
  8314. break;
  8315. case VertexBuffer.MatricesIndicesKind:
  8316. this._strideSize = 4;
  8317. break;
  8318. case VertexBuffer.MatricesWeightsKind:
  8319. this._strideSize = 4;
  8320. break;
  8321. }
  8322. }
  8323. // Properties
  8324. VertexBuffer.prototype.isUpdatable = function () {
  8325. return this._updatable;
  8326. };
  8327. VertexBuffer.prototype.getData = function () {
  8328. return this._data;
  8329. };
  8330. VertexBuffer.prototype.getBuffer = function () {
  8331. return this._buffer;
  8332. };
  8333. VertexBuffer.prototype.getStrideSize = function () {
  8334. return this._strideSize;
  8335. };
  8336. // Methods
  8337. VertexBuffer.prototype.create = function (data) {
  8338. if (!data && this._buffer) {
  8339. return;
  8340. }
  8341. data = data || this._data;
  8342. if (!this._buffer) {
  8343. if (this._updatable) {
  8344. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8345. } else {
  8346. this._buffer = this._engine.createVertexBuffer(data);
  8347. }
  8348. }
  8349. if (this._updatable) {
  8350. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8351. this._data = data;
  8352. }
  8353. };
  8354. VertexBuffer.prototype.update = function (data) {
  8355. this.create(data);
  8356. };
  8357. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8358. if (!this._buffer) {
  8359. return;
  8360. }
  8361. if (this._updatable) {
  8362. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8363. this._data = null;
  8364. }
  8365. };
  8366. VertexBuffer.prototype.dispose = function () {
  8367. if (!this._buffer) {
  8368. return;
  8369. }
  8370. if (this._engine._releaseBuffer(this._buffer)) {
  8371. this._buffer = null;
  8372. }
  8373. };
  8374. Object.defineProperty(VertexBuffer, "PositionKind", {
  8375. get: function () {
  8376. return VertexBuffer._PositionKind;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(VertexBuffer, "NormalKind", {
  8382. get: function () {
  8383. return VertexBuffer._NormalKind;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(VertexBuffer, "UVKind", {
  8389. get: function () {
  8390. return VertexBuffer._UVKind;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8396. get: function () {
  8397. return VertexBuffer._UV2Kind;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(VertexBuffer, "ColorKind", {
  8403. get: function () {
  8404. return VertexBuffer._ColorKind;
  8405. },
  8406. enumerable: true,
  8407. configurable: true
  8408. });
  8409. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8410. get: function () {
  8411. return VertexBuffer._MatricesIndicesKind;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8417. get: function () {
  8418. return VertexBuffer._MatricesWeightsKind;
  8419. },
  8420. enumerable: true,
  8421. configurable: true
  8422. });
  8423. VertexBuffer._PositionKind = "position";
  8424. VertexBuffer._NormalKind = "normal";
  8425. VertexBuffer._UVKind = "uv";
  8426. VertexBuffer._UV2Kind = "uv2";
  8427. VertexBuffer._ColorKind = "color";
  8428. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8429. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8430. return VertexBuffer;
  8431. })();
  8432. BABYLON.VertexBuffer = VertexBuffer;
  8433. })(BABYLON || (BABYLON = {}));
  8434. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8435. var BABYLON;
  8436. (function (BABYLON) {
  8437. var AbstractMesh = (function (_super) {
  8438. __extends(AbstractMesh, _super);
  8439. function AbstractMesh(name, scene) {
  8440. _super.call(this, name, scene);
  8441. // Properties
  8442. this.position = new BABYLON.Vector3(0, 0, 0);
  8443. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8444. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8445. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8446. this.visibility = 1.0;
  8447. this.alphaIndex = Number.MAX_VALUE;
  8448. this.infiniteDistance = false;
  8449. this.isVisible = true;
  8450. this.isPickable = true;
  8451. this.showBoundingBox = false;
  8452. this.showSubMeshesBoundingBox = false;
  8453. this.onDispose = null;
  8454. this.checkCollisions = false;
  8455. this.isBlocker = false;
  8456. this.renderingGroupId = 0;
  8457. this.receiveShadows = false;
  8458. this.renderOutline = false;
  8459. this.outlineColor = BABYLON.Color3.Red();
  8460. this.outlineWidth = 0.02;
  8461. this.renderOverlay = false;
  8462. this.overlayColor = BABYLON.Color3.Red();
  8463. this.overlayAlpha = 0.5;
  8464. this.hasVertexAlpha = false;
  8465. this.useVertexColors = true;
  8466. this.applyFog = true;
  8467. this.useOctreeForRenderingSelection = true;
  8468. this.useOctreeForPicking = true;
  8469. this.useOctreeForCollisions = true;
  8470. this.layerMask = 0xFFFFFFFF;
  8471. // Physics
  8472. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8473. // Collisions
  8474. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8475. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8476. this._collider = new BABYLON.Collider();
  8477. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8478. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8479. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8480. // Cache
  8481. this._localScaling = BABYLON.Matrix.Zero();
  8482. this._localRotation = BABYLON.Matrix.Zero();
  8483. this._localTranslation = BABYLON.Matrix.Zero();
  8484. this._localBillboard = BABYLON.Matrix.Zero();
  8485. this._localPivotScaling = BABYLON.Matrix.Zero();
  8486. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8487. this._localWorld = BABYLON.Matrix.Zero();
  8488. this._worldMatrix = BABYLON.Matrix.Zero();
  8489. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8490. this._absolutePosition = BABYLON.Vector3.Zero();
  8491. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8492. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8493. this._isDirty = false;
  8494. this._pivotMatrix = BABYLON.Matrix.Identity();
  8495. this._isDisposed = false;
  8496. this._renderId = 0;
  8497. this._intersectionsInProgress = new Array();
  8498. this._onAfterWorldMatrixUpdate = new Array();
  8499. scene.meshes.push(this);
  8500. }
  8501. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8502. get: function () {
  8503. return AbstractMesh._BILLBOARDMODE_NONE;
  8504. },
  8505. enumerable: true,
  8506. configurable: true
  8507. });
  8508. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8509. get: function () {
  8510. return AbstractMesh._BILLBOARDMODE_X;
  8511. },
  8512. enumerable: true,
  8513. configurable: true
  8514. });
  8515. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8516. get: function () {
  8517. return AbstractMesh._BILLBOARDMODE_Y;
  8518. },
  8519. enumerable: true,
  8520. configurable: true
  8521. });
  8522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8523. get: function () {
  8524. return AbstractMesh._BILLBOARDMODE_Z;
  8525. },
  8526. enumerable: true,
  8527. configurable: true
  8528. });
  8529. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8530. get: function () {
  8531. return AbstractMesh._BILLBOARDMODE_ALL;
  8532. },
  8533. enumerable: true,
  8534. configurable: true
  8535. });
  8536. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8537. // Methods
  8538. get: function () {
  8539. return false;
  8540. },
  8541. enumerable: true,
  8542. configurable: true
  8543. });
  8544. AbstractMesh.prototype.getLOD = function (camera) {
  8545. return this;
  8546. };
  8547. AbstractMesh.prototype.getTotalVertices = function () {
  8548. return 0;
  8549. };
  8550. AbstractMesh.prototype.getIndices = function () {
  8551. return null;
  8552. };
  8553. AbstractMesh.prototype.getVerticesData = function (kind) {
  8554. return null;
  8555. };
  8556. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8557. return false;
  8558. };
  8559. AbstractMesh.prototype.getBoundingInfo = function () {
  8560. if (this._masterMesh) {
  8561. return this._masterMesh.getBoundingInfo();
  8562. }
  8563. if (!this._boundingInfo) {
  8564. this._updateBoundingInfo();
  8565. }
  8566. return this._boundingInfo;
  8567. };
  8568. AbstractMesh.prototype._preActivate = function () {
  8569. };
  8570. AbstractMesh.prototype._activate = function (renderId) {
  8571. this._renderId = renderId;
  8572. };
  8573. AbstractMesh.prototype.getWorldMatrix = function () {
  8574. if (this._masterMesh) {
  8575. return this._masterMesh.getWorldMatrix();
  8576. }
  8577. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8578. this.computeWorldMatrix();
  8579. }
  8580. return this._worldMatrix;
  8581. };
  8582. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8583. get: function () {
  8584. return this._worldMatrix;
  8585. },
  8586. enumerable: true,
  8587. configurable: true
  8588. });
  8589. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8590. get: function () {
  8591. return this._absolutePosition;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8597. if (!this.rotationQuaternion) {
  8598. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8599. this.rotation = BABYLON.Vector3.Zero();
  8600. }
  8601. if (!space || space == 0 /* LOCAL */) {
  8602. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8603. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8604. } else {
  8605. if (this.parent) {
  8606. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8607. invertParentWorldMatrix.invert();
  8608. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8609. }
  8610. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8611. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8612. }
  8613. };
  8614. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8615. var displacementVector = axis.scale(distance);
  8616. if (!space || space == 0 /* LOCAL */) {
  8617. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8618. this.setPositionWithLocalVector(tempV3);
  8619. } else {
  8620. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8621. }
  8622. };
  8623. AbstractMesh.prototype.getAbsolutePosition = function () {
  8624. this.computeWorldMatrix();
  8625. return this._absolutePosition;
  8626. };
  8627. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8628. if (!absolutePosition) {
  8629. return;
  8630. }
  8631. var absolutePositionX;
  8632. var absolutePositionY;
  8633. var absolutePositionZ;
  8634. if (absolutePosition.x === undefined) {
  8635. if (arguments.length < 3) {
  8636. return;
  8637. }
  8638. absolutePositionX = arguments[0];
  8639. absolutePositionY = arguments[1];
  8640. absolutePositionZ = arguments[2];
  8641. } else {
  8642. absolutePositionX = absolutePosition.x;
  8643. absolutePositionY = absolutePosition.y;
  8644. absolutePositionZ = absolutePosition.z;
  8645. }
  8646. if (this.parent) {
  8647. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8648. invertParentWorldMatrix.invert();
  8649. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8650. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8651. } else {
  8652. this.position.x = absolutePositionX;
  8653. this.position.y = absolutePositionY;
  8654. this.position.z = absolutePositionZ;
  8655. }
  8656. };
  8657. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8658. this._pivotMatrix = matrix;
  8659. this._cache.pivotMatrixUpdated = true;
  8660. };
  8661. AbstractMesh.prototype.getPivotMatrix = function () {
  8662. return this._pivotMatrix;
  8663. };
  8664. AbstractMesh.prototype._isSynchronized = function () {
  8665. if (this._isDirty) {
  8666. return false;
  8667. }
  8668. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8669. return false;
  8670. if (this._cache.pivotMatrixUpdated) {
  8671. return false;
  8672. }
  8673. if (this.infiniteDistance) {
  8674. return false;
  8675. }
  8676. if (!this._cache.position.equals(this.position))
  8677. return false;
  8678. if (this.rotationQuaternion) {
  8679. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8680. return false;
  8681. } else {
  8682. if (!this._cache.rotation.equals(this.rotation))
  8683. return false;
  8684. }
  8685. if (!this._cache.scaling.equals(this.scaling))
  8686. return false;
  8687. return true;
  8688. };
  8689. AbstractMesh.prototype._initCache = function () {
  8690. _super.prototype._initCache.call(this);
  8691. this._cache.localMatrixUpdated = false;
  8692. this._cache.position = BABYLON.Vector3.Zero();
  8693. this._cache.scaling = BABYLON.Vector3.Zero();
  8694. this._cache.rotation = BABYLON.Vector3.Zero();
  8695. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8696. };
  8697. AbstractMesh.prototype.markAsDirty = function (property) {
  8698. if (property === "rotation") {
  8699. this.rotationQuaternion = null;
  8700. }
  8701. this._currentRenderId = Number.MAX_VALUE;
  8702. this._isDirty = true;
  8703. };
  8704. AbstractMesh.prototype._updateBoundingInfo = function () {
  8705. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8706. this._boundingInfo._update(this.worldMatrixFromCache);
  8707. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8708. };
  8709. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8710. if (!this.subMeshes) {
  8711. return;
  8712. }
  8713. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8714. var subMesh = this.subMeshes[subIndex];
  8715. subMesh.updateBoundingInfo(matrix);
  8716. }
  8717. };
  8718. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8719. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8720. return this._worldMatrix;
  8721. }
  8722. this._cache.position.copyFrom(this.position);
  8723. this._cache.scaling.copyFrom(this.scaling);
  8724. this._cache.pivotMatrixUpdated = false;
  8725. this._currentRenderId = this.getScene().getRenderId();
  8726. this._isDirty = false;
  8727. // Scaling
  8728. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8729. // Rotation
  8730. if (this.rotationQuaternion) {
  8731. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8732. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8733. } else {
  8734. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8735. this._cache.rotation.copyFrom(this.rotation);
  8736. }
  8737. // Translation
  8738. if (this.infiniteDistance && !this.parent) {
  8739. var camera = this.getScene().activeCamera;
  8740. var cameraWorldMatrix = camera.getWorldMatrix();
  8741. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8742. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8743. } else {
  8744. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8745. }
  8746. // Composing transformations
  8747. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8748. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8749. // Billboarding
  8750. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8751. var localPosition = this.position.clone();
  8752. var zero = this.getScene().activeCamera.position.clone();
  8753. if (this.parent && this.parent.position) {
  8754. localPosition.addInPlace(this.parent.position);
  8755. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8756. }
  8757. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8758. zero = this.getScene().activeCamera.position;
  8759. } else {
  8760. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8761. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8762. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8763. zero.y = localPosition.y + 0.001;
  8764. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8765. zero.z = localPosition.z + 0.001;
  8766. }
  8767. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8768. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8769. this._localBillboard.invert();
  8770. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8771. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8772. }
  8773. // Local world
  8774. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8775. // Parent
  8776. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8777. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8778. } else {
  8779. this._worldMatrix.copyFrom(this._localWorld);
  8780. }
  8781. // Bounding info
  8782. this._updateBoundingInfo();
  8783. // Absolute position
  8784. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8785. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8786. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8787. }
  8788. return this._worldMatrix;
  8789. };
  8790. /**
  8791. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8792. * @param func: callback function to add
  8793. */
  8794. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8795. this._onAfterWorldMatrixUpdate.push(func);
  8796. };
  8797. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8798. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8799. if (index > -1) {
  8800. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8801. }
  8802. };
  8803. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8804. this.computeWorldMatrix();
  8805. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8806. };
  8807. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8808. this.computeWorldMatrix();
  8809. var invLocalWorldMatrix = this._localWorld.clone();
  8810. invLocalWorldMatrix.invert();
  8811. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8812. };
  8813. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8814. this.computeWorldMatrix();
  8815. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8816. };
  8817. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8818. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8819. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8820. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8821. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8822. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8823. /// <returns>Mesh oriented towards targetMesh</returns>
  8824. yawCor = yawCor || 0; // default to zero if undefined
  8825. pitchCor = pitchCor || 0;
  8826. rollCor = rollCor || 0;
  8827. var dv = targetPoint.subtract(this.position);
  8828. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8829. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8830. var pitch = Math.atan2(dv.y, len);
  8831. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8832. };
  8833. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8834. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8835. return false;
  8836. }
  8837. return true;
  8838. };
  8839. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8840. if (!camera) {
  8841. camera = this.getScene().activeCamera;
  8842. }
  8843. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8844. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8845. return false;
  8846. }
  8847. return true;
  8848. };
  8849. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8850. if (!this._boundingInfo || !mesh._boundingInfo) {
  8851. return false;
  8852. }
  8853. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8854. };
  8855. AbstractMesh.prototype.intersectsPoint = function (point) {
  8856. if (!this._boundingInfo) {
  8857. return false;
  8858. }
  8859. return this._boundingInfo.intersectsPoint(point);
  8860. };
  8861. // Physics
  8862. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8863. var physicsEngine = this.getScene().getPhysicsEngine();
  8864. if (!physicsEngine) {
  8865. return;
  8866. }
  8867. if (impostor.impostor) {
  8868. // Old API
  8869. options = impostor;
  8870. impostor = impostor.impostor;
  8871. }
  8872. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8873. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8874. physicsEngine._unregisterMesh(this);
  8875. return;
  8876. }
  8877. options.mass = options.mass || 0;
  8878. options.friction = options.friction || 0.2;
  8879. options.restitution = options.restitution || 0.2;
  8880. this._physicImpostor = impostor;
  8881. this._physicsMass = options.mass;
  8882. this._physicsFriction = options.friction;
  8883. this._physicRestitution = options.restitution;
  8884. return physicsEngine._registerMesh(this, impostor, options);
  8885. };
  8886. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8887. if (!this._physicImpostor) {
  8888. return BABYLON.PhysicsEngine.NoImpostor;
  8889. }
  8890. return this._physicImpostor;
  8891. };
  8892. AbstractMesh.prototype.getPhysicsMass = function () {
  8893. if (!this._physicsMass) {
  8894. return 0;
  8895. }
  8896. return this._physicsMass;
  8897. };
  8898. AbstractMesh.prototype.getPhysicsFriction = function () {
  8899. if (!this._physicsFriction) {
  8900. return 0;
  8901. }
  8902. return this._physicsFriction;
  8903. };
  8904. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8905. if (!this._physicRestitution) {
  8906. return 0;
  8907. }
  8908. return this._physicRestitution;
  8909. };
  8910. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8911. if (!camera) {
  8912. camera = this.getScene().activeCamera;
  8913. }
  8914. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8915. };
  8916. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8917. if (!camera) {
  8918. camera = this.getScene().activeCamera;
  8919. }
  8920. return this.absolutePosition.subtract(camera.position).length();
  8921. };
  8922. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8923. if (!this._physicImpostor) {
  8924. return;
  8925. }
  8926. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8927. };
  8928. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8929. if (!this._physicImpostor) {
  8930. return;
  8931. }
  8932. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8933. };
  8934. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8935. if (!this._physicImpostor) {
  8936. return;
  8937. }
  8938. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8939. };
  8940. // Collisions
  8941. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8942. var globalPosition = this.getAbsolutePosition();
  8943. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8944. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8945. this._collider.radius = this.ellipsoid;
  8946. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8947. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8948. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8949. this.position.addInPlace(this._diffPositionForCollisions);
  8950. }
  8951. };
  8952. // Submeshes octree
  8953. /**
  8954. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8955. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8956. */
  8957. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8958. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8959. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8960. if (!this._submeshesOctree) {
  8961. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8962. }
  8963. this.computeWorldMatrix(true);
  8964. // Update octree
  8965. var bbox = this.getBoundingInfo().boundingBox;
  8966. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8967. return this._submeshesOctree;
  8968. };
  8969. // Collisions
  8970. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8971. this._generatePointsArray();
  8972. // Transformation
  8973. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8974. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8975. subMesh._lastColliderWorldVertices = [];
  8976. subMesh._trianglePlanes = [];
  8977. var start = subMesh.verticesStart;
  8978. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8979. for (var i = start; i < end; i++) {
  8980. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8981. }
  8982. }
  8983. // Collide
  8984. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8985. };
  8986. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8987. var subMeshes;
  8988. var len;
  8989. // Octrees
  8990. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8991. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8992. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8993. len = intersections.length;
  8994. subMeshes = intersections.data;
  8995. } else {
  8996. subMeshes = this.subMeshes;
  8997. len = subMeshes.length;
  8998. }
  8999. for (var index = 0; index < len; index++) {
  9000. var subMesh = subMeshes[index];
  9001. // Bounding test
  9002. if (len > 1 && !subMesh._checkCollision(collider))
  9003. continue;
  9004. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9005. }
  9006. };
  9007. AbstractMesh.prototype._checkCollision = function (collider) {
  9008. // Bounding box test
  9009. if (!this._boundingInfo._checkCollision(collider))
  9010. return;
  9011. // Transformation matrix
  9012. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9013. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9014. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9015. };
  9016. // Picking
  9017. AbstractMesh.prototype._generatePointsArray = function () {
  9018. return false;
  9019. };
  9020. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9021. var pickingInfo = new BABYLON.PickingInfo();
  9022. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9023. return pickingInfo;
  9024. }
  9025. if (!this._generatePointsArray()) {
  9026. return pickingInfo;
  9027. }
  9028. var intersectInfo = null;
  9029. // Octrees
  9030. var subMeshes;
  9031. var len;
  9032. if (this._submeshesOctree && this.useOctreeForPicking) {
  9033. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9034. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9035. len = intersections.length;
  9036. subMeshes = intersections.data;
  9037. } else {
  9038. subMeshes = this.subMeshes;
  9039. len = subMeshes.length;
  9040. }
  9041. for (var index = 0; index < len; index++) {
  9042. var subMesh = subMeshes[index];
  9043. // Bounding test
  9044. if (len > 1 && !subMesh.canIntersects(ray))
  9045. continue;
  9046. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9047. if (currentIntersectInfo) {
  9048. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9049. intersectInfo = currentIntersectInfo;
  9050. if (fastCheck) {
  9051. break;
  9052. }
  9053. }
  9054. }
  9055. }
  9056. if (intersectInfo) {
  9057. // Get picked point
  9058. var world = this.getWorldMatrix();
  9059. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9060. var direction = ray.direction.clone();
  9061. direction.normalize();
  9062. direction = direction.scale(intersectInfo.distance);
  9063. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9064. var pickedPoint = worldOrigin.add(worldDirection);
  9065. // Return result
  9066. pickingInfo.hit = true;
  9067. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9068. pickingInfo.pickedPoint = pickedPoint;
  9069. pickingInfo.pickedMesh = this;
  9070. pickingInfo.bu = intersectInfo.bu;
  9071. pickingInfo.bv = intersectInfo.bv;
  9072. pickingInfo.faceId = intersectInfo.faceId;
  9073. return pickingInfo;
  9074. }
  9075. return pickingInfo;
  9076. };
  9077. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9078. return null;
  9079. };
  9080. AbstractMesh.prototype.releaseSubMeshes = function () {
  9081. if (this.subMeshes) {
  9082. while (this.subMeshes.length) {
  9083. this.subMeshes[0].dispose();
  9084. }
  9085. } else {
  9086. this.subMeshes = new Array();
  9087. }
  9088. };
  9089. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9090. // Physics
  9091. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9092. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9093. }
  9094. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9095. var other = this._intersectionsInProgress[index];
  9096. var pos = other._intersectionsInProgress.indexOf(this);
  9097. other._intersectionsInProgress.splice(pos, 1);
  9098. }
  9099. this._intersectionsInProgress = [];
  9100. // SubMeshes
  9101. this.releaseSubMeshes();
  9102. // Remove from scene
  9103. var index = this.getScene().meshes.indexOf(this);
  9104. if (index != -1) {
  9105. // Remove from the scene if mesh found
  9106. this.getScene().meshes.splice(index, 1);
  9107. }
  9108. if (!doNotRecurse) {
  9109. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9110. if (this.getScene().particleSystems[index].emitter == this) {
  9111. this.getScene().particleSystems[index].dispose();
  9112. index--;
  9113. }
  9114. }
  9115. // Children
  9116. var objects = this.getScene().meshes.slice(0);
  9117. for (index = 0; index < objects.length; index++) {
  9118. if (objects[index].parent == this) {
  9119. objects[index].dispose();
  9120. }
  9121. }
  9122. } else {
  9123. for (index = 0; index < this.getScene().meshes.length; index++) {
  9124. var obj = this.getScene().meshes[index];
  9125. if (obj.parent === this) {
  9126. obj.parent = null;
  9127. obj.computeWorldMatrix(true);
  9128. }
  9129. }
  9130. }
  9131. this._onAfterWorldMatrixUpdate = [];
  9132. this._isDisposed = true;
  9133. // Callback
  9134. if (this.onDispose) {
  9135. this.onDispose();
  9136. }
  9137. };
  9138. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9139. AbstractMesh._BILLBOARDMODE_X = 1;
  9140. AbstractMesh._BILLBOARDMODE_Y = 2;
  9141. AbstractMesh._BILLBOARDMODE_Z = 4;
  9142. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9143. return AbstractMesh;
  9144. })(BABYLON.Node);
  9145. BABYLON.AbstractMesh = AbstractMesh;
  9146. })(BABYLON || (BABYLON = {}));
  9147. //# sourceMappingURL=babylon.abstractMesh.js.map
  9148. var BABYLON;
  9149. (function (BABYLON) {
  9150. var _InstancesBatch = (function () {
  9151. function _InstancesBatch() {
  9152. this.mustReturn = false;
  9153. this.visibleInstances = new Array();
  9154. this.renderSelf = new Array();
  9155. }
  9156. return _InstancesBatch;
  9157. })();
  9158. BABYLON._InstancesBatch = _InstancesBatch;
  9159. var Mesh = (function (_super) {
  9160. __extends(Mesh, _super);
  9161. /**
  9162. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9163. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9164. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9165. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9166. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9167. * When false, achieved by calling a clone(), also passing False.
  9168. * This will make creation of children, recursive.
  9169. */
  9170. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9171. if (typeof parent === "undefined") { parent = null; }
  9172. _super.call(this, name, scene);
  9173. // Members
  9174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9175. this.instances = new Array();
  9176. this._LODLevels = new Array();
  9177. this._onBeforeRenderCallbacks = new Array();
  9178. this._onAfterRenderCallbacks = new Array();
  9179. this._visibleInstances = {};
  9180. this._renderIdForInstances = new Array();
  9181. this._batchCache = new _InstancesBatch();
  9182. this._instancesBufferSize = 32 * 16 * 4;
  9183. if (source) {
  9184. // Geometry
  9185. if (source._geometry) {
  9186. source._geometry.applyToMesh(this);
  9187. }
  9188. // Deep copy
  9189. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9190. // Material
  9191. this.material = source.material;
  9192. if (!doNotCloneChildren) {
  9193. for (var index = 0; index < scene.meshes.length; index++) {
  9194. var mesh = scene.meshes[index];
  9195. if (mesh.parent === source) {
  9196. // doNotCloneChildren is always going to be False
  9197. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9198. }
  9199. }
  9200. }
  9201. for (index = 0; index < scene.particleSystems.length; index++) {
  9202. var system = scene.particleSystems[index];
  9203. if (system.emitter === source) {
  9204. system.clone(system.name, this);
  9205. }
  9206. }
  9207. this.computeWorldMatrix(true);
  9208. }
  9209. // Parent
  9210. if (parent !== null) {
  9211. this.parent = parent;
  9212. }
  9213. }
  9214. Mesh.prototype._clone = function () {
  9215. };
  9216. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9217. // Methods
  9218. get: function () {
  9219. return this._LODLevels.length > 0;
  9220. },
  9221. enumerable: true,
  9222. configurable: true
  9223. });
  9224. Mesh.prototype._sortLODLevels = function () {
  9225. this._LODLevels.sort(function (a, b) {
  9226. if (a.distance < b.distance) {
  9227. return 1;
  9228. }
  9229. if (a.distance > b.distance) {
  9230. return -1;
  9231. }
  9232. return 0;
  9233. });
  9234. };
  9235. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9236. if (mesh && mesh._masterMesh) {
  9237. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9238. return this;
  9239. }
  9240. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9241. this._LODLevels.push(level);
  9242. if (mesh) {
  9243. mesh._masterMesh = this;
  9244. }
  9245. this._sortLODLevels();
  9246. return this;
  9247. };
  9248. Mesh.prototype.removeLODLevel = function (mesh) {
  9249. for (var index = 0; index < this._LODLevels.length; index++) {
  9250. if (this._LODLevels[index].mesh === mesh) {
  9251. this._LODLevels.splice(index, 1);
  9252. if (mesh) {
  9253. mesh._masterMesh = null;
  9254. }
  9255. }
  9256. }
  9257. this._sortLODLevels();
  9258. return this;
  9259. };
  9260. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9261. if (!this._LODLevels || this._LODLevels.length === 0) {
  9262. return this;
  9263. }
  9264. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9265. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9266. return this;
  9267. }
  9268. for (var index = 0; index < this._LODLevels.length; index++) {
  9269. var level = this._LODLevels[index];
  9270. if (level.distance < distanceToCamera) {
  9271. if (level.mesh) {
  9272. level.mesh._preActivate();
  9273. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9274. }
  9275. return level.mesh;
  9276. }
  9277. }
  9278. return this;
  9279. };
  9280. Object.defineProperty(Mesh.prototype, "geometry", {
  9281. get: function () {
  9282. return this._geometry;
  9283. },
  9284. enumerable: true,
  9285. configurable: true
  9286. });
  9287. Mesh.prototype.getTotalVertices = function () {
  9288. if (!this._geometry) {
  9289. return 0;
  9290. }
  9291. return this._geometry.getTotalVertices();
  9292. };
  9293. Mesh.prototype.getVerticesData = function (kind) {
  9294. if (!this._geometry) {
  9295. return null;
  9296. }
  9297. return this._geometry.getVerticesData(kind);
  9298. };
  9299. Mesh.prototype.getVertexBuffer = function (kind) {
  9300. if (!this._geometry) {
  9301. return undefined;
  9302. }
  9303. return this._geometry.getVertexBuffer(kind);
  9304. };
  9305. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9306. if (!this._geometry) {
  9307. if (this._delayInfo) {
  9308. return this._delayInfo.indexOf(kind) !== -1;
  9309. }
  9310. return false;
  9311. }
  9312. return this._geometry.isVerticesDataPresent(kind);
  9313. };
  9314. Mesh.prototype.getVerticesDataKinds = function () {
  9315. if (!this._geometry) {
  9316. var result = [];
  9317. if (this._delayInfo) {
  9318. for (var kind in this._delayInfo) {
  9319. result.push(kind);
  9320. }
  9321. }
  9322. return result;
  9323. }
  9324. return this._geometry.getVerticesDataKinds();
  9325. };
  9326. Mesh.prototype.getTotalIndices = function () {
  9327. if (!this._geometry) {
  9328. return 0;
  9329. }
  9330. return this._geometry.getTotalIndices();
  9331. };
  9332. Mesh.prototype.getIndices = function () {
  9333. if (!this._geometry) {
  9334. return [];
  9335. }
  9336. return this._geometry.getIndices();
  9337. };
  9338. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9339. get: function () {
  9340. return this._masterMesh !== null && this._masterMesh !== undefined;
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. Mesh.prototype.isReady = function () {
  9346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9347. return false;
  9348. }
  9349. return _super.prototype.isReady.call(this);
  9350. };
  9351. Mesh.prototype.isDisposed = function () {
  9352. return this._isDisposed;
  9353. };
  9354. // Methods
  9355. Mesh.prototype._preActivate = function () {
  9356. var sceneRenderId = this.getScene().getRenderId();
  9357. if (this._preActivateId == sceneRenderId) {
  9358. return;
  9359. }
  9360. this._preActivateId = sceneRenderId;
  9361. this._visibleInstances = null;
  9362. };
  9363. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9364. if (!this._visibleInstances) {
  9365. this._visibleInstances = {};
  9366. this._visibleInstances.defaultRenderId = renderId;
  9367. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9368. }
  9369. if (!this._visibleInstances[renderId]) {
  9370. this._visibleInstances[renderId] = new Array();
  9371. }
  9372. this._visibleInstances[renderId].push(instance);
  9373. };
  9374. Mesh.prototype.refreshBoundingInfo = function () {
  9375. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9376. if (data) {
  9377. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9378. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9379. }
  9380. if (this.subMeshes) {
  9381. for (var index = 0; index < this.subMeshes.length; index++) {
  9382. this.subMeshes[index].refreshBoundingInfo();
  9383. }
  9384. }
  9385. this._updateBoundingInfo();
  9386. };
  9387. Mesh.prototype._createGlobalSubMesh = function () {
  9388. var totalVertices = this.getTotalVertices();
  9389. if (!totalVertices || !this.getIndices()) {
  9390. return null;
  9391. }
  9392. this.releaseSubMeshes();
  9393. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9394. };
  9395. Mesh.prototype.subdivide = function (count) {
  9396. if (count < 1) {
  9397. return;
  9398. }
  9399. var totalIndices = this.getTotalIndices();
  9400. var subdivisionSize = (totalIndices / count) | 0;
  9401. var offset = 0;
  9402. while (subdivisionSize % 3 != 0) {
  9403. subdivisionSize++;
  9404. }
  9405. this.releaseSubMeshes();
  9406. for (var index = 0; index < count; index++) {
  9407. if (offset >= totalIndices) {
  9408. break;
  9409. }
  9410. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9411. offset += subdivisionSize;
  9412. }
  9413. this.synchronizeInstances();
  9414. };
  9415. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9416. if (kind instanceof Array) {
  9417. var temp = data;
  9418. data = kind;
  9419. kind = temp;
  9420. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9421. }
  9422. if (!this._geometry) {
  9423. var vertexData = new BABYLON.VertexData();
  9424. vertexData.set(data, kind);
  9425. var scene = this.getScene();
  9426. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9427. } else {
  9428. this._geometry.setVerticesData(kind, data, updatable, stride);
  9429. }
  9430. };
  9431. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9432. if (!this._geometry) {
  9433. return;
  9434. }
  9435. if (!makeItUnique) {
  9436. this._geometry.updateVerticesData(kind, data, updateExtends);
  9437. } else {
  9438. this.makeGeometryUnique();
  9439. this.updateVerticesData(kind, data, updateExtends, false);
  9440. }
  9441. };
  9442. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9443. if (!this._geometry) {
  9444. return;
  9445. }
  9446. if (!makeItUnique) {
  9447. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9448. } else {
  9449. this.makeGeometryUnique();
  9450. this.updateVerticesDataDirectly(kind, data, offset, false);
  9451. }
  9452. };
  9453. Mesh.prototype.makeGeometryUnique = function () {
  9454. if (!this._geometry) {
  9455. return;
  9456. }
  9457. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9458. geometry.applyToMesh(this);
  9459. };
  9460. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9461. if (!this._geometry) {
  9462. var vertexData = new BABYLON.VertexData();
  9463. vertexData.indices = indices;
  9464. var scene = this.getScene();
  9465. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9466. } else {
  9467. this._geometry.setIndices(indices, totalVertices);
  9468. }
  9469. };
  9470. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9471. var engine = this.getScene().getEngine();
  9472. // Wireframe
  9473. var indexToBind;
  9474. switch (fillMode) {
  9475. case BABYLON.Material.PointFillMode:
  9476. indexToBind = null;
  9477. break;
  9478. case BABYLON.Material.WireFrameFillMode:
  9479. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9480. break;
  9481. default:
  9482. case BABYLON.Material.TriangleFillMode:
  9483. indexToBind = this._geometry.getIndexBuffer();
  9484. break;
  9485. }
  9486. // VBOs
  9487. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9488. };
  9489. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9490. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9491. return;
  9492. }
  9493. var engine = this.getScene().getEngine();
  9494. switch (fillMode) {
  9495. case BABYLON.Material.PointFillMode:
  9496. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9497. break;
  9498. case BABYLON.Material.WireFrameFillMode:
  9499. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9500. break;
  9501. default:
  9502. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9503. }
  9504. };
  9505. Mesh.prototype.registerBeforeRender = function (func) {
  9506. this._onBeforeRenderCallbacks.push(func);
  9507. };
  9508. Mesh.prototype.unregisterBeforeRender = function (func) {
  9509. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9510. if (index > -1) {
  9511. this._onBeforeRenderCallbacks.splice(index, 1);
  9512. }
  9513. };
  9514. Mesh.prototype.registerAfterRender = function (func) {
  9515. this._onAfterRenderCallbacks.push(func);
  9516. };
  9517. Mesh.prototype.unregisterAfterRender = function (func) {
  9518. var index = this._onAfterRenderCallbacks.indexOf(func);
  9519. if (index > -1) {
  9520. this._onAfterRenderCallbacks.splice(index, 1);
  9521. }
  9522. };
  9523. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9524. var scene = this.getScene();
  9525. this._batchCache.mustReturn = false;
  9526. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9527. this._batchCache.visibleInstances[subMeshId] = null;
  9528. if (this._visibleInstances) {
  9529. var currentRenderId = scene.getRenderId();
  9530. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9531. var selfRenderId = this._renderId;
  9532. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9533. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9534. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9535. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9536. }
  9537. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9538. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9539. this._batchCache.mustReturn = true;
  9540. return this._batchCache;
  9541. }
  9542. if (currentRenderId !== selfRenderId) {
  9543. this._batchCache.renderSelf[subMeshId] = false;
  9544. }
  9545. }
  9546. this._renderIdForInstances[subMeshId] = currentRenderId;
  9547. }
  9548. return this._batchCache;
  9549. };
  9550. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9551. var visibleInstances = batch.visibleInstances[subMesh._id];
  9552. var matricesCount = visibleInstances.length + 1;
  9553. var bufferSize = matricesCount * 16 * 4;
  9554. while (this._instancesBufferSize < bufferSize) {
  9555. this._instancesBufferSize *= 2;
  9556. }
  9557. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9558. if (this._worldMatricesInstancesBuffer) {
  9559. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9560. }
  9561. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9562. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9563. }
  9564. var offset = 0;
  9565. var instancesCount = 0;
  9566. var world = this.getWorldMatrix();
  9567. if (batch.renderSelf[subMesh._id]) {
  9568. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9569. offset += 16;
  9570. instancesCount++;
  9571. }
  9572. if (visibleInstances) {
  9573. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9574. var instance = visibleInstances[instanceIndex];
  9575. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9576. offset += 16;
  9577. instancesCount++;
  9578. }
  9579. }
  9580. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9581. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9582. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9583. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9584. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9585. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9586. this._draw(subMesh, fillMode, instancesCount);
  9587. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9588. };
  9589. Mesh.prototype.render = function (subMesh) {
  9590. var scene = this.getScene();
  9591. // Managing instances
  9592. var batch = this._getInstancesRenderList(subMesh._id);
  9593. if (batch.mustReturn) {
  9594. return;
  9595. }
  9596. // Checking geometry state
  9597. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9598. return;
  9599. }
  9600. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9601. this._onBeforeRenderCallbacks[callbackIndex]();
  9602. }
  9603. var engine = scene.getEngine();
  9604. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9605. // Material
  9606. var effectiveMaterial = subMesh.getMaterial();
  9607. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9608. return;
  9609. }
  9610. // Outline - step 1
  9611. var savedDepthWrite = engine.getDepthWrite();
  9612. if (this.renderOutline) {
  9613. engine.setDepthWrite(false);
  9614. scene.getOutlineRenderer().render(subMesh, batch);
  9615. engine.setDepthWrite(savedDepthWrite);
  9616. }
  9617. effectiveMaterial._preBind();
  9618. var effect = effectiveMaterial.getEffect();
  9619. // Bind
  9620. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9621. this._bind(subMesh, effect, fillMode);
  9622. var world = this.getWorldMatrix();
  9623. effectiveMaterial.bind(world, this);
  9624. // Instances rendering
  9625. if (hardwareInstancedRendering) {
  9626. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9627. } else {
  9628. if (batch.renderSelf[subMesh._id]) {
  9629. // Draw
  9630. this._draw(subMesh, fillMode);
  9631. }
  9632. if (batch.visibleInstances[subMesh._id]) {
  9633. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9634. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9635. // World
  9636. world = instance.getWorldMatrix();
  9637. effectiveMaterial.bindOnlyWorldMatrix(world);
  9638. // Draw
  9639. this._draw(subMesh, fillMode);
  9640. }
  9641. }
  9642. }
  9643. // Unbind
  9644. effectiveMaterial.unbind();
  9645. // Outline - step 2
  9646. if (this.renderOutline && savedDepthWrite) {
  9647. engine.setDepthWrite(true);
  9648. engine.setColorWrite(false);
  9649. scene.getOutlineRenderer().render(subMesh, batch);
  9650. engine.setColorWrite(true);
  9651. }
  9652. // Overlay
  9653. if (this.renderOverlay) {
  9654. var currentMode = engine.getAlphaMode();
  9655. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9656. scene.getOutlineRenderer().render(subMesh, batch, true);
  9657. engine.setAlphaMode(currentMode);
  9658. }
  9659. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9660. this._onAfterRenderCallbacks[callbackIndex]();
  9661. }
  9662. };
  9663. Mesh.prototype.getEmittedParticleSystems = function () {
  9664. var results = new Array();
  9665. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9666. var particleSystem = this.getScene().particleSystems[index];
  9667. if (particleSystem.emitter === this) {
  9668. results.push(particleSystem);
  9669. }
  9670. }
  9671. return results;
  9672. };
  9673. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9674. var results = new Array();
  9675. var descendants = this.getDescendants();
  9676. descendants.push(this);
  9677. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9678. var particleSystem = this.getScene().particleSystems[index];
  9679. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9680. results.push(particleSystem);
  9681. }
  9682. }
  9683. return results;
  9684. };
  9685. Mesh.prototype.getChildren = function () {
  9686. var results = [];
  9687. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9688. var mesh = this.getScene().meshes[index];
  9689. if (mesh.parent == this) {
  9690. results.push(mesh);
  9691. }
  9692. }
  9693. return results;
  9694. };
  9695. Mesh.prototype._checkDelayState = function () {
  9696. var _this = this;
  9697. var that = this;
  9698. var scene = this.getScene();
  9699. if (this._geometry) {
  9700. this._geometry.load(scene);
  9701. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9702. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9703. scene._addPendingData(that);
  9704. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9705. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9706. if (data instanceof ArrayBuffer) {
  9707. _this._delayLoadingFunction(data, _this);
  9708. } else {
  9709. _this._delayLoadingFunction(JSON.parse(data), _this);
  9710. }
  9711. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9712. scene._removePendingData(_this);
  9713. }, function () {
  9714. }, scene.database, getBinaryData);
  9715. }
  9716. };
  9717. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9718. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9719. return false;
  9720. }
  9721. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9722. return false;
  9723. }
  9724. this._checkDelayState();
  9725. return true;
  9726. };
  9727. Mesh.prototype.setMaterialByID = function (id) {
  9728. var materials = this.getScene().materials;
  9729. for (var index = 0; index < materials.length; index++) {
  9730. if (materials[index].id == id) {
  9731. this.material = materials[index];
  9732. return;
  9733. }
  9734. }
  9735. // Multi
  9736. var multiMaterials = this.getScene().multiMaterials;
  9737. for (index = 0; index < multiMaterials.length; index++) {
  9738. if (multiMaterials[index].id == id) {
  9739. this.material = multiMaterials[index];
  9740. return;
  9741. }
  9742. }
  9743. };
  9744. Mesh.prototype.getAnimatables = function () {
  9745. var results = [];
  9746. if (this.material) {
  9747. results.push(this.material);
  9748. }
  9749. if (this.skeleton) {
  9750. results.push(this.skeleton);
  9751. }
  9752. return results;
  9753. };
  9754. // Geometry
  9755. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9756. // Position
  9757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9758. return;
  9759. }
  9760. this._resetPointsArrayCache();
  9761. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9762. var temp = [];
  9763. for (var index = 0; index < data.length; index += 3) {
  9764. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9765. }
  9766. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9767. // Normals
  9768. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9769. return;
  9770. }
  9771. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9772. for (index = 0; index < data.length; index += 3) {
  9773. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9774. }
  9775. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9776. };
  9777. // Cache
  9778. Mesh.prototype._resetPointsArrayCache = function () {
  9779. this._positions = null;
  9780. };
  9781. Mesh.prototype._generatePointsArray = function () {
  9782. if (this._positions)
  9783. return true;
  9784. this._positions = [];
  9785. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9786. if (!data) {
  9787. return false;
  9788. }
  9789. for (var index = 0; index < data.length; index += 3) {
  9790. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9791. }
  9792. return true;
  9793. };
  9794. // Clone
  9795. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9796. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9797. };
  9798. // Dispose
  9799. Mesh.prototype.dispose = function (doNotRecurse) {
  9800. if (this._geometry) {
  9801. this._geometry.releaseForMesh(this, true);
  9802. }
  9803. // Instances
  9804. if (this._worldMatricesInstancesBuffer) {
  9805. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9806. this._worldMatricesInstancesBuffer = null;
  9807. }
  9808. while (this.instances.length) {
  9809. this.instances[0].dispose();
  9810. }
  9811. _super.prototype.dispose.call(this, doNotRecurse);
  9812. };
  9813. // Geometric tools
  9814. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9815. var _this = this;
  9816. var scene = this.getScene();
  9817. var onload = function (img) {
  9818. // Getting height map data
  9819. var canvas = document.createElement("canvas");
  9820. var context = canvas.getContext("2d");
  9821. var heightMapWidth = img.width;
  9822. var heightMapHeight = img.height;
  9823. canvas.width = heightMapWidth;
  9824. canvas.height = heightMapHeight;
  9825. context.drawImage(img, 0, 0);
  9826. // Create VertexData from map data
  9827. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9828. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9829. };
  9830. BABYLON.Tools.LoadImage(url, onload, function () {
  9831. }, scene.database);
  9832. };
  9833. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9834. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9835. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9836. return;
  9837. }
  9838. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9839. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9840. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9841. var position = BABYLON.Vector3.Zero();
  9842. var normal = BABYLON.Vector3.Zero();
  9843. var uv = BABYLON.Vector2.Zero();
  9844. for (var index = 0; index < positions.length; index += 3) {
  9845. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9846. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9847. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9848. // Compute height
  9849. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9850. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9851. var pos = (u + v * heightMapWidth) * 4;
  9852. var r = buffer[pos] / 255.0;
  9853. var g = buffer[pos + 1] / 255.0;
  9854. var b = buffer[pos + 2] / 255.0;
  9855. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9856. normal.normalize();
  9857. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9858. position = position.add(normal);
  9859. position.toArray(positions, index);
  9860. }
  9861. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9862. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9863. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9864. };
  9865. Mesh.prototype.convertToFlatShadedMesh = function () {
  9866. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9867. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9868. var kinds = this.getVerticesDataKinds();
  9869. var vbs = [];
  9870. var data = [];
  9871. var newdata = [];
  9872. var updatableNormals = false;
  9873. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9874. var kind = kinds[kindIndex];
  9875. var vertexBuffer = this.getVertexBuffer(kind);
  9876. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9877. updatableNormals = vertexBuffer.isUpdatable();
  9878. kinds.splice(kindIndex, 1);
  9879. kindIndex--;
  9880. continue;
  9881. }
  9882. vbs[kind] = vertexBuffer;
  9883. data[kind] = vbs[kind].getData();
  9884. newdata[kind] = [];
  9885. }
  9886. // Save previous submeshes
  9887. var previousSubmeshes = this.subMeshes.slice(0);
  9888. var indices = this.getIndices();
  9889. var totalIndices = this.getTotalIndices();
  9890. for (index = 0; index < totalIndices; index++) {
  9891. var vertexIndex = indices[index];
  9892. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9893. kind = kinds[kindIndex];
  9894. var stride = vbs[kind].getStrideSize();
  9895. for (var offset = 0; offset < stride; offset++) {
  9896. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9897. }
  9898. }
  9899. }
  9900. // Updating faces & normal
  9901. var normals = [];
  9902. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9903. for (var index = 0; index < totalIndices; index += 3) {
  9904. indices[index] = index;
  9905. indices[index + 1] = index + 1;
  9906. indices[index + 2] = index + 2;
  9907. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9908. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9909. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9910. var p1p2 = p1.subtract(p2);
  9911. var p3p2 = p3.subtract(p2);
  9912. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9913. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9914. normals.push(normal.x);
  9915. normals.push(normal.y);
  9916. normals.push(normal.z);
  9917. }
  9918. }
  9919. this.setIndices(indices);
  9920. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9922. kind = kinds[kindIndex];
  9923. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9924. }
  9925. // Updating submeshes
  9926. this.releaseSubMeshes();
  9927. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9928. var previousOne = previousSubmeshes[submeshIndex];
  9929. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9930. }
  9931. this.synchronizeInstances();
  9932. };
  9933. // Instances
  9934. Mesh.prototype.createInstance = function (name) {
  9935. return new BABYLON.InstancedMesh(name, this);
  9936. };
  9937. Mesh.prototype.synchronizeInstances = function () {
  9938. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9939. var instance = this.instances[instanceIndex];
  9940. instance._syncSubMeshes();
  9941. }
  9942. };
  9943. // Statics
  9944. Mesh.CreateBox = function (name, size, scene, updatable) {
  9945. var box = new BABYLON.Mesh(name, scene);
  9946. var vertexData = BABYLON.VertexData.CreateBox(size);
  9947. vertexData.applyToMesh(box, updatable);
  9948. return box;
  9949. };
  9950. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9951. var sphere = new BABYLON.Mesh(name, scene);
  9952. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9953. vertexData.applyToMesh(sphere, updatable);
  9954. return sphere;
  9955. };
  9956. // Cylinder and cone (Code inspired by SharpDX.org)
  9957. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9958. // subdivisions is a new parameter, we need to support old signature
  9959. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9960. if (scene !== undefined) {
  9961. updatable = scene;
  9962. }
  9963. scene = subdivisions;
  9964. subdivisions = 1;
  9965. }
  9966. var cylinder = new BABYLON.Mesh(name, scene);
  9967. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9968. vertexData.applyToMesh(cylinder, updatable);
  9969. return cylinder;
  9970. };
  9971. // Torus (Code from SharpDX.org)
  9972. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9973. var torus = new BABYLON.Mesh(name, scene);
  9974. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9975. vertexData.applyToMesh(torus, updatable);
  9976. return torus;
  9977. };
  9978. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9979. var torusKnot = new BABYLON.Mesh(name, scene);
  9980. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9981. vertexData.applyToMesh(torusKnot, updatable);
  9982. return torusKnot;
  9983. };
  9984. // Lines
  9985. Mesh.CreateLines = function (name, points, scene, updatable) {
  9986. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9987. var vertexData = BABYLON.VertexData.CreateLines(points);
  9988. vertexData.applyToMesh(lines, updatable);
  9989. return lines;
  9990. };
  9991. // Plane & ground
  9992. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9993. var plane = new BABYLON.Mesh(name, scene);
  9994. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9995. vertexData.applyToMesh(plane, updatable);
  9996. return plane;
  9997. };
  9998. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9999. var ground = new BABYLON.GroundMesh(name, scene);
  10000. ground._setReady(false);
  10001. ground._subdivisions = subdivisions;
  10002. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10003. vertexData.applyToMesh(ground, updatable);
  10004. ground._setReady(true);
  10005. return ground;
  10006. };
  10007. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10008. var tiledGround = new BABYLON.Mesh(name, scene);
  10009. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10010. vertexData.applyToMesh(tiledGround, updatable);
  10011. return tiledGround;
  10012. };
  10013. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10014. var ground = new BABYLON.GroundMesh(name, scene);
  10015. ground._subdivisions = subdivisions;
  10016. ground._setReady(false);
  10017. var onload = function (img) {
  10018. // Getting height map data
  10019. var canvas = document.createElement("canvas");
  10020. var context = canvas.getContext("2d");
  10021. var heightMapWidth = img.width;
  10022. var heightMapHeight = img.height;
  10023. canvas.width = heightMapWidth;
  10024. canvas.height = heightMapHeight;
  10025. context.drawImage(img, 0, 0);
  10026. // Create VertexData from map data
  10027. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10028. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10029. vertexData.applyToMesh(ground, updatable);
  10030. ground._setReady(true);
  10031. };
  10032. BABYLON.Tools.LoadImage(url, onload, function () {
  10033. }, scene.database);
  10034. return ground;
  10035. };
  10036. // Tools
  10037. Mesh.MinMax = function (meshes) {
  10038. var minVector = null;
  10039. var maxVector = null;
  10040. for (var i in meshes) {
  10041. var mesh = meshes[i];
  10042. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10043. if (!minVector) {
  10044. minVector = boundingBox.minimumWorld;
  10045. maxVector = boundingBox.maximumWorld;
  10046. continue;
  10047. }
  10048. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10049. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10050. }
  10051. return {
  10052. min: minVector,
  10053. max: maxVector
  10054. };
  10055. };
  10056. Mesh.Center = function (meshesOrMinMaxVector) {
  10057. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10058. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10059. };
  10060. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10061. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10062. var source = meshes[0];
  10063. var material = source.material;
  10064. var scene = source.getScene();
  10065. if (!allow32BitsIndices) {
  10066. var totalVertices = 0;
  10067. for (var index = 0; index < meshes.length; index++) {
  10068. totalVertices += meshes[index].getTotalVertices();
  10069. if (totalVertices > 65536) {
  10070. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10071. return null;
  10072. }
  10073. }
  10074. }
  10075. // Merge
  10076. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10077. vertexData.transform(source.getWorldMatrix());
  10078. for (index = 1; index < meshes.length; index++) {
  10079. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10080. otherVertexData.transform(meshes[index].getWorldMatrix());
  10081. vertexData.merge(otherVertexData);
  10082. }
  10083. var newMesh = new Mesh(source.name + "_merged", scene);
  10084. vertexData.applyToMesh(newMesh);
  10085. // Setting properties
  10086. newMesh.material = material;
  10087. newMesh.checkCollisions = source.checkCollisions;
  10088. // Cleaning
  10089. if (disposeSource) {
  10090. for (index = 0; index < meshes.length; index++) {
  10091. meshes[index].dispose();
  10092. }
  10093. }
  10094. return newMesh;
  10095. };
  10096. return Mesh;
  10097. })(BABYLON.AbstractMesh);
  10098. BABYLON.Mesh = Mesh;
  10099. })(BABYLON || (BABYLON = {}));
  10100. //# sourceMappingURL=babylon.mesh.js.map
  10101. var BABYLON;
  10102. (function (BABYLON) {
  10103. var GroundMesh = (function (_super) {
  10104. __extends(GroundMesh, _super);
  10105. function GroundMesh(name, scene) {
  10106. _super.call(this, name, scene);
  10107. this.generateOctree = false;
  10108. this._worldInverse = new BABYLON.Matrix();
  10109. }
  10110. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10111. get: function () {
  10112. return this._subdivisions;
  10113. },
  10114. enumerable: true,
  10115. configurable: true
  10116. });
  10117. GroundMesh.prototype.optimize = function (chunksCount) {
  10118. this.subdivide(this._subdivisions);
  10119. this.createOrUpdateSubmeshesOctree(32);
  10120. };
  10121. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10122. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10123. this.getWorldMatrix().invertToRef(this._worldInverse);
  10124. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10125. var pickInfo = this.intersects(ray);
  10126. if (pickInfo.hit) {
  10127. return pickInfo.pickedPoint.y;
  10128. }
  10129. return 0;
  10130. };
  10131. return GroundMesh;
  10132. })(BABYLON.Mesh);
  10133. BABYLON.GroundMesh = GroundMesh;
  10134. })(BABYLON || (BABYLON = {}));
  10135. //# sourceMappingURL=babylon.groundMesh.js.map
  10136. var BABYLON;
  10137. (function (BABYLON) {
  10138. var InstancedMesh = (function (_super) {
  10139. __extends(InstancedMesh, _super);
  10140. function InstancedMesh(name, source) {
  10141. _super.call(this, name, source.getScene());
  10142. source.instances.push(this);
  10143. this._sourceMesh = source;
  10144. this.position.copyFrom(source.position);
  10145. this.rotation.copyFrom(source.rotation);
  10146. this.scaling.copyFrom(source.scaling);
  10147. if (source.rotationQuaternion) {
  10148. this.rotationQuaternion = source.rotationQuaternion.clone();
  10149. }
  10150. this.infiniteDistance = source.infiniteDistance;
  10151. this.setPivotMatrix(source.getPivotMatrix());
  10152. this.refreshBoundingInfo();
  10153. this._syncSubMeshes();
  10154. }
  10155. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10156. // Methods
  10157. get: function () {
  10158. return this._sourceMesh.receiveShadows;
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. Object.defineProperty(InstancedMesh.prototype, "material", {
  10164. get: function () {
  10165. return this._sourceMesh.material;
  10166. },
  10167. enumerable: true,
  10168. configurable: true
  10169. });
  10170. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10171. get: function () {
  10172. return this._sourceMesh.visibility;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10178. get: function () {
  10179. return this._sourceMesh.skeleton;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. InstancedMesh.prototype.getTotalVertices = function () {
  10185. return this._sourceMesh.getTotalVertices();
  10186. };
  10187. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10188. get: function () {
  10189. return this._sourceMesh;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. InstancedMesh.prototype.getVerticesData = function (kind) {
  10195. return this._sourceMesh.getVerticesData(kind);
  10196. };
  10197. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10198. return this._sourceMesh.isVerticesDataPresent(kind);
  10199. };
  10200. InstancedMesh.prototype.getIndices = function () {
  10201. return this._sourceMesh.getIndices();
  10202. };
  10203. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10204. get: function () {
  10205. return this._sourceMesh._positions;
  10206. },
  10207. enumerable: true,
  10208. configurable: true
  10209. });
  10210. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10211. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10212. if (data) {
  10213. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10214. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10215. }
  10216. this._updateBoundingInfo();
  10217. };
  10218. InstancedMesh.prototype._preActivate = function () {
  10219. if (this._currentLOD) {
  10220. this._currentLOD._preActivate();
  10221. }
  10222. };
  10223. InstancedMesh.prototype._activate = function (renderId) {
  10224. if (this._currentLOD) {
  10225. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10226. }
  10227. };
  10228. InstancedMesh.prototype.getLOD = function (camera) {
  10229. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10230. return this._currentLOD;
  10231. };
  10232. InstancedMesh.prototype._syncSubMeshes = function () {
  10233. this.releaseSubMeshes();
  10234. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10235. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10236. }
  10237. };
  10238. InstancedMesh.prototype._generatePointsArray = function () {
  10239. return this._sourceMesh._generatePointsArray();
  10240. };
  10241. // Clone
  10242. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10243. var result = this._sourceMesh.createInstance(name);
  10244. // Deep copy
  10245. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10246. // Bounding info
  10247. this.refreshBoundingInfo();
  10248. // Parent
  10249. if (newParent) {
  10250. result.parent = newParent;
  10251. }
  10252. if (!doNotCloneChildren) {
  10253. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10254. var mesh = this.getScene().meshes[index];
  10255. if (mesh.parent == this) {
  10256. mesh.clone(mesh.name, result);
  10257. }
  10258. }
  10259. }
  10260. result.computeWorldMatrix(true);
  10261. return result;
  10262. };
  10263. // Dispoe
  10264. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10265. // Remove from mesh
  10266. var index = this._sourceMesh.instances.indexOf(this);
  10267. this._sourceMesh.instances.splice(index, 1);
  10268. _super.prototype.dispose.call(this, doNotRecurse);
  10269. };
  10270. return InstancedMesh;
  10271. })(BABYLON.AbstractMesh);
  10272. BABYLON.InstancedMesh = InstancedMesh;
  10273. })(BABYLON || (BABYLON = {}));
  10274. //# sourceMappingURL=babylon.instancedMesh.js.map
  10275. var BABYLON;
  10276. (function (BABYLON) {
  10277. var SubMesh = (function () {
  10278. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10279. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10280. this.materialIndex = materialIndex;
  10281. this.verticesStart = verticesStart;
  10282. this.verticesCount = verticesCount;
  10283. this.indexStart = indexStart;
  10284. this.indexCount = indexCount;
  10285. this._renderId = 0;
  10286. this._mesh = mesh;
  10287. this._renderingMesh = renderingMesh || mesh;
  10288. mesh.subMeshes.push(this);
  10289. this._id = mesh.subMeshes.length - 1;
  10290. if (createBoundingBox) {
  10291. this.refreshBoundingInfo();
  10292. }
  10293. }
  10294. SubMesh.prototype.getBoundingInfo = function () {
  10295. return this._boundingInfo;
  10296. };
  10297. SubMesh.prototype.getMesh = function () {
  10298. return this._mesh;
  10299. };
  10300. SubMesh.prototype.getRenderingMesh = function () {
  10301. return this._renderingMesh;
  10302. };
  10303. SubMesh.prototype.getMaterial = function () {
  10304. var rootMaterial = this._renderingMesh.material;
  10305. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10306. var multiMaterial = rootMaterial;
  10307. return multiMaterial.getSubMaterial(this.materialIndex);
  10308. }
  10309. if (!rootMaterial) {
  10310. return this._mesh.getScene().defaultMaterial;
  10311. }
  10312. return rootMaterial;
  10313. };
  10314. // Methods
  10315. SubMesh.prototype.refreshBoundingInfo = function () {
  10316. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10317. if (!data) {
  10318. this._boundingInfo = this._mesh._boundingInfo;
  10319. return;
  10320. }
  10321. var indices = this._renderingMesh.getIndices();
  10322. var extend;
  10323. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10324. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10325. } else {
  10326. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10327. }
  10328. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10329. };
  10330. SubMesh.prototype._checkCollision = function (collider) {
  10331. return this._boundingInfo._checkCollision(collider);
  10332. };
  10333. SubMesh.prototype.updateBoundingInfo = function (world) {
  10334. if (!this._boundingInfo) {
  10335. this.refreshBoundingInfo();
  10336. }
  10337. this._boundingInfo._update(world);
  10338. };
  10339. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10340. return this._boundingInfo.isInFrustum(frustumPlanes);
  10341. };
  10342. SubMesh.prototype.render = function () {
  10343. this._renderingMesh.render(this);
  10344. };
  10345. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10346. if (!this._linesIndexBuffer) {
  10347. var linesIndices = [];
  10348. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10349. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10350. }
  10351. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10352. this.linesIndexCount = linesIndices.length;
  10353. }
  10354. return this._linesIndexBuffer;
  10355. };
  10356. SubMesh.prototype.canIntersects = function (ray) {
  10357. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10358. };
  10359. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10360. var intersectInfo = null;
  10361. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10362. var p0 = positions[indices[index]];
  10363. var p1 = positions[indices[index + 1]];
  10364. var p2 = positions[indices[index + 2]];
  10365. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10366. if (currentIntersectInfo) {
  10367. if (currentIntersectInfo.distance < 0) {
  10368. continue;
  10369. }
  10370. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10371. intersectInfo = currentIntersectInfo;
  10372. intersectInfo.faceId = index / 3;
  10373. if (fastCheck) {
  10374. break;
  10375. }
  10376. }
  10377. }
  10378. }
  10379. return intersectInfo;
  10380. };
  10381. // Clone
  10382. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10383. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10384. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10385. return result;
  10386. };
  10387. // Dispose
  10388. SubMesh.prototype.dispose = function () {
  10389. if (this._linesIndexBuffer) {
  10390. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10391. this._linesIndexBuffer = null;
  10392. }
  10393. // Remove from mesh
  10394. var index = this._mesh.subMeshes.indexOf(this);
  10395. this._mesh.subMeshes.splice(index, 1);
  10396. };
  10397. // Statics
  10398. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10399. var minVertexIndex = Number.MAX_VALUE;
  10400. var maxVertexIndex = -Number.MAX_VALUE;
  10401. renderingMesh = renderingMesh || mesh;
  10402. var indices = renderingMesh.getIndices();
  10403. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10404. var vertexIndex = indices[index];
  10405. if (vertexIndex < minVertexIndex)
  10406. minVertexIndex = vertexIndex;
  10407. if (vertexIndex > maxVertexIndex)
  10408. maxVertexIndex = vertexIndex;
  10409. }
  10410. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10411. };
  10412. return SubMesh;
  10413. })();
  10414. BABYLON.SubMesh = SubMesh;
  10415. })(BABYLON || (BABYLON = {}));
  10416. //# sourceMappingURL=babylon.subMesh.js.map
  10417. var BABYLON;
  10418. (function (BABYLON) {
  10419. var BaseTexture = (function () {
  10420. function BaseTexture(scene) {
  10421. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10422. this.hasAlpha = false;
  10423. this.getAlphaFromRGB = false;
  10424. this.level = 1;
  10425. this.isCube = false;
  10426. this.isRenderTarget = false;
  10427. this.animations = new Array();
  10428. this.coordinatesIndex = 0;
  10429. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10430. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10431. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10432. this.anisotropicFilteringLevel = 4;
  10433. this._scene = scene;
  10434. this._scene.textures.push(this);
  10435. }
  10436. BaseTexture.prototype.getScene = function () {
  10437. return this._scene;
  10438. };
  10439. BaseTexture.prototype.getTextureMatrix = function () {
  10440. return null;
  10441. };
  10442. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10443. return null;
  10444. };
  10445. BaseTexture.prototype.getInternalTexture = function () {
  10446. return this._texture;
  10447. };
  10448. BaseTexture.prototype.isReady = function () {
  10449. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10450. return true;
  10451. }
  10452. if (this._texture) {
  10453. return this._texture.isReady;
  10454. }
  10455. return false;
  10456. };
  10457. BaseTexture.prototype.getSize = function () {
  10458. if (this._texture._width) {
  10459. return { width: this._texture._width, height: this._texture._height };
  10460. }
  10461. if (this._texture._size) {
  10462. return { width: this._texture._size, height: this._texture._size };
  10463. }
  10464. return { width: 0, height: 0 };
  10465. };
  10466. BaseTexture.prototype.getBaseSize = function () {
  10467. if (!this.isReady())
  10468. return { width: 0, height: 0 };
  10469. if (this._texture._size) {
  10470. return { width: this._texture._size, height: this._texture._size };
  10471. }
  10472. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10473. };
  10474. BaseTexture.prototype.scale = function (ratio) {
  10475. };
  10476. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10477. get: function () {
  10478. return false;
  10479. },
  10480. enumerable: true,
  10481. configurable: true
  10482. });
  10483. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10484. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10485. for (var index = 0; index < texturesCache.length; index++) {
  10486. var texturesCacheEntry = texturesCache[index];
  10487. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10488. texturesCache.splice(index, 1);
  10489. return;
  10490. }
  10491. }
  10492. };
  10493. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10494. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10495. for (var index = 0; index < texturesCache.length; index++) {
  10496. var texturesCacheEntry = texturesCache[index];
  10497. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10498. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10499. texturesCacheEntry.references++;
  10500. return texturesCacheEntry;
  10501. }
  10502. }
  10503. }
  10504. return null;
  10505. };
  10506. BaseTexture.prototype.delayLoad = function () {
  10507. };
  10508. BaseTexture.prototype.releaseInternalTexture = function () {
  10509. if (!this._texture) {
  10510. return;
  10511. }
  10512. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10513. this._texture.references--;
  10514. // Final reference ?
  10515. if (this._texture.references === 0) {
  10516. var index = texturesCache.indexOf(this._texture);
  10517. texturesCache.splice(index, 1);
  10518. this._scene.getEngine()._releaseTexture(this._texture);
  10519. delete this._texture;
  10520. }
  10521. };
  10522. BaseTexture.prototype.clone = function () {
  10523. return null;
  10524. };
  10525. BaseTexture.prototype.dispose = function () {
  10526. // Remove from scene
  10527. var index = this._scene.textures.indexOf(this);
  10528. if (index >= 0) {
  10529. this._scene.textures.splice(index, 1);
  10530. }
  10531. if (this._texture === undefined) {
  10532. return;
  10533. }
  10534. this.releaseInternalTexture();
  10535. // Callback
  10536. if (this.onDispose) {
  10537. this.onDispose();
  10538. }
  10539. };
  10540. return BaseTexture;
  10541. })();
  10542. BABYLON.BaseTexture = BaseTexture;
  10543. })(BABYLON || (BABYLON = {}));
  10544. //# sourceMappingURL=babylon.baseTexture.js.map
  10545. var BABYLON;
  10546. (function (BABYLON) {
  10547. var RenderingGroup = (function () {
  10548. function RenderingGroup(index, scene) {
  10549. this.index = index;
  10550. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10551. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10552. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10553. this._scene = scene;
  10554. }
  10555. RenderingGroup.prototype.render = function (customRenderFunction) {
  10556. if (customRenderFunction) {
  10557. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10558. return true;
  10559. }
  10560. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10561. return false;
  10562. }
  10563. var engine = this._scene.getEngine();
  10564. // Opaque
  10565. var subIndex;
  10566. var submesh;
  10567. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10568. submesh = this._opaqueSubMeshes.data[subIndex];
  10569. submesh.render();
  10570. }
  10571. // Alpha test
  10572. engine.setAlphaTesting(true);
  10573. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10574. submesh = this._alphaTestSubMeshes.data[subIndex];
  10575. submesh.render();
  10576. }
  10577. engine.setAlphaTesting(false);
  10578. // Transparent
  10579. if (this._transparentSubMeshes.length) {
  10580. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10581. submesh = this._transparentSubMeshes.data[subIndex];
  10582. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10583. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10584. }
  10585. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10586. sortedArray.sort(function (a, b) {
  10587. // Alpha index first
  10588. if (a._alphaIndex > b._alphaIndex) {
  10589. return 1;
  10590. }
  10591. if (a._alphaIndex < b._alphaIndex) {
  10592. return -1;
  10593. }
  10594. // Then distance to camera
  10595. if (a._distanceToCamera < b._distanceToCamera) {
  10596. return 1;
  10597. }
  10598. if (a._distanceToCamera > b._distanceToCamera) {
  10599. return -1;
  10600. }
  10601. return 0;
  10602. });
  10603. // Rendering
  10604. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10605. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10606. submesh = sortedArray[subIndex];
  10607. submesh.render();
  10608. }
  10609. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10610. }
  10611. return true;
  10612. };
  10613. RenderingGroup.prototype.prepare = function () {
  10614. this._opaqueSubMeshes.reset();
  10615. this._transparentSubMeshes.reset();
  10616. this._alphaTestSubMeshes.reset();
  10617. };
  10618. RenderingGroup.prototype.dispatch = function (subMesh) {
  10619. var material = subMesh.getMaterial();
  10620. var mesh = subMesh.getMesh();
  10621. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10622. this._transparentSubMeshes.push(subMesh);
  10623. } else if (material.needAlphaTesting()) {
  10624. this._alphaTestSubMeshes.push(subMesh);
  10625. } else {
  10626. this._opaqueSubMeshes.push(subMesh); // Opaque
  10627. }
  10628. };
  10629. return RenderingGroup;
  10630. })();
  10631. BABYLON.RenderingGroup = RenderingGroup;
  10632. })(BABYLON || (BABYLON = {}));
  10633. //# sourceMappingURL=babylon.renderingGroup.js.map
  10634. var BABYLON;
  10635. (function (BABYLON) {
  10636. var RenderingManager = (function () {
  10637. function RenderingManager(scene) {
  10638. this._renderingGroups = new Array();
  10639. this._scene = scene;
  10640. }
  10641. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10642. if (this._scene._activeParticleSystems.length === 0) {
  10643. return;
  10644. }
  10645. // Particles
  10646. var beforeParticlesDate = BABYLON.Tools.Now;
  10647. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10648. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10649. if (particleSystem.renderingGroupId !== index) {
  10650. continue;
  10651. }
  10652. this._clearDepthBuffer();
  10653. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10654. this._scene._activeParticles += particleSystem.render();
  10655. }
  10656. }
  10657. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10658. };
  10659. RenderingManager.prototype._renderSprites = function (index) {
  10660. if (this._scene.spriteManagers.length === 0) {
  10661. return;
  10662. }
  10663. // Sprites
  10664. var beforeSpritessDate = BABYLON.Tools.Now;
  10665. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10666. var spriteManager = this._scene.spriteManagers[id];
  10667. if (spriteManager.renderingGroupId === index) {
  10668. this._clearDepthBuffer();
  10669. spriteManager.render();
  10670. }
  10671. }
  10672. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10673. };
  10674. RenderingManager.prototype._clearDepthBuffer = function () {
  10675. if (this._depthBufferAlreadyCleaned) {
  10676. return;
  10677. }
  10678. this._scene.getEngine().clear(0, false, true);
  10679. this._depthBufferAlreadyCleaned = true;
  10680. };
  10681. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10682. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10683. this._depthBufferAlreadyCleaned = false;
  10684. var renderingGroup = this._renderingGroups[index];
  10685. if (renderingGroup) {
  10686. this._clearDepthBuffer();
  10687. if (!renderingGroup.render(customRenderFunction)) {
  10688. this._renderingGroups.splice(index, 1);
  10689. }
  10690. }
  10691. this._renderSprites(index);
  10692. if (renderParticles) {
  10693. this._renderParticles(index, activeMeshes);
  10694. }
  10695. }
  10696. };
  10697. RenderingManager.prototype.reset = function () {
  10698. for (var index in this._renderingGroups) {
  10699. var renderingGroup = this._renderingGroups[index];
  10700. renderingGroup.prepare();
  10701. }
  10702. };
  10703. RenderingManager.prototype.dispatch = function (subMesh) {
  10704. var mesh = subMesh.getMesh();
  10705. var renderingGroupId = mesh.renderingGroupId || 0;
  10706. if (!this._renderingGroups[renderingGroupId]) {
  10707. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10708. }
  10709. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10710. };
  10711. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10712. return RenderingManager;
  10713. })();
  10714. BABYLON.RenderingManager = RenderingManager;
  10715. })(BABYLON || (BABYLON = {}));
  10716. //# sourceMappingURL=babylon.renderingManager.js.map
  10717. var BABYLON;
  10718. (function (BABYLON) {
  10719. var Texture = (function (_super) {
  10720. __extends(Texture, _super);
  10721. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10722. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10723. if (typeof onLoad === "undefined") { onLoad = null; }
  10724. if (typeof onError === "undefined") { onError = null; }
  10725. if (typeof buffer === "undefined") { buffer = null; }
  10726. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10727. _super.call(this, scene);
  10728. this.uOffset = 0;
  10729. this.vOffset = 0;
  10730. this.uScale = 1.0;
  10731. this.vScale = 1.0;
  10732. this.uAng = 0;
  10733. this.vAng = 0;
  10734. this.wAng = 0;
  10735. this.name = url;
  10736. this.url = url;
  10737. this._noMipmap = noMipmap;
  10738. this._invertY = invertY;
  10739. this._samplingMode = samplingMode;
  10740. this._buffer = buffer;
  10741. this._deleteBuffer = deleteBuffer;
  10742. if (!url) {
  10743. return;
  10744. }
  10745. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10746. if (!this._texture) {
  10747. if (!scene.useDelayedTextureLoading) {
  10748. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10749. if (deleteBuffer) {
  10750. delete this._buffer;
  10751. }
  10752. } else {
  10753. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10754. }
  10755. }
  10756. }
  10757. Texture.prototype.delayLoad = function () {
  10758. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10759. return;
  10760. }
  10761. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10762. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10763. if (!this._texture) {
  10764. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10765. if (this._deleteBuffer) {
  10766. delete this._buffer;
  10767. }
  10768. }
  10769. };
  10770. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10771. x -= this.uOffset + 0.5;
  10772. y -= this.vOffset + 0.5;
  10773. z -= 0.5;
  10774. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10775. t.x *= this.uScale;
  10776. t.y *= this.vScale;
  10777. t.x += 0.5;
  10778. t.y += 0.5;
  10779. t.z += 0.5;
  10780. };
  10781. Texture.prototype.getTextureMatrix = function () {
  10782. 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) {
  10783. return this._cachedTextureMatrix;
  10784. }
  10785. this._cachedUOffset = this.uOffset;
  10786. this._cachedVOffset = this.vOffset;
  10787. this._cachedUScale = this.uScale;
  10788. this._cachedVScale = this.vScale;
  10789. this._cachedUAng = this.uAng;
  10790. this._cachedVAng = this.vAng;
  10791. this._cachedWAng = this.wAng;
  10792. if (!this._cachedTextureMatrix) {
  10793. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10794. this._rowGenerationMatrix = new BABYLON.Matrix();
  10795. this._t0 = BABYLON.Vector3.Zero();
  10796. this._t1 = BABYLON.Vector3.Zero();
  10797. this._t2 = BABYLON.Vector3.Zero();
  10798. }
  10799. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10800. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10801. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10802. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10803. this._t1.subtractInPlace(this._t0);
  10804. this._t2.subtractInPlace(this._t0);
  10805. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10806. this._cachedTextureMatrix.m[0] = this._t1.x;
  10807. this._cachedTextureMatrix.m[1] = this._t1.y;
  10808. this._cachedTextureMatrix.m[2] = this._t1.z;
  10809. this._cachedTextureMatrix.m[4] = this._t2.x;
  10810. this._cachedTextureMatrix.m[5] = this._t2.y;
  10811. this._cachedTextureMatrix.m[6] = this._t2.z;
  10812. this._cachedTextureMatrix.m[8] = this._t0.x;
  10813. this._cachedTextureMatrix.m[9] = this._t0.y;
  10814. this._cachedTextureMatrix.m[10] = this._t0.z;
  10815. return this._cachedTextureMatrix;
  10816. };
  10817. Texture.prototype.getReflectionTextureMatrix = function () {
  10818. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10819. return this._cachedTextureMatrix;
  10820. }
  10821. if (!this._cachedTextureMatrix) {
  10822. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10823. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10824. }
  10825. this._cachedCoordinatesMode = this.coordinatesMode;
  10826. switch (this.coordinatesMode) {
  10827. case BABYLON.Texture.SPHERICAL_MODE:
  10828. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10829. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10830. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10831. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10832. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10833. break;
  10834. case BABYLON.Texture.PLANAR_MODE:
  10835. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10836. this._cachedTextureMatrix[0] = this.uScale;
  10837. this._cachedTextureMatrix[5] = this.vScale;
  10838. this._cachedTextureMatrix[12] = this.uOffset;
  10839. this._cachedTextureMatrix[13] = this.vOffset;
  10840. break;
  10841. case BABYLON.Texture.PROJECTION_MODE:
  10842. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10843. this._projectionModeMatrix.m[0] = 0.5;
  10844. this._projectionModeMatrix.m[5] = -0.5;
  10845. this._projectionModeMatrix.m[10] = 0.0;
  10846. this._projectionModeMatrix.m[12] = 0.5;
  10847. this._projectionModeMatrix.m[13] = 0.5;
  10848. this._projectionModeMatrix.m[14] = 1.0;
  10849. this._projectionModeMatrix.m[15] = 1.0;
  10850. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10851. break;
  10852. default:
  10853. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10854. break;
  10855. }
  10856. return this._cachedTextureMatrix;
  10857. };
  10858. Texture.prototype.clone = function () {
  10859. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10860. // Base texture
  10861. newTexture.hasAlpha = this.hasAlpha;
  10862. newTexture.level = this.level;
  10863. newTexture.wrapU = this.wrapU;
  10864. newTexture.wrapV = this.wrapV;
  10865. newTexture.coordinatesIndex = this.coordinatesIndex;
  10866. newTexture.coordinatesMode = this.coordinatesMode;
  10867. // Texture
  10868. newTexture.uOffset = this.uOffset;
  10869. newTexture.vOffset = this.vOffset;
  10870. newTexture.uScale = this.uScale;
  10871. newTexture.vScale = this.vScale;
  10872. newTexture.uAng = this.uAng;
  10873. newTexture.vAng = this.vAng;
  10874. newTexture.wAng = this.wAng;
  10875. return newTexture;
  10876. };
  10877. // Statics
  10878. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10879. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10880. if (typeof onLoad === "undefined") { onLoad = null; }
  10881. if (typeof onError === "undefined") { onError = null; }
  10882. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10883. };
  10884. Texture.NEAREST_SAMPLINGMODE = 1;
  10885. Texture.BILINEAR_SAMPLINGMODE = 2;
  10886. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10887. Texture.EXPLICIT_MODE = 0;
  10888. Texture.SPHERICAL_MODE = 1;
  10889. Texture.PLANAR_MODE = 2;
  10890. Texture.CUBIC_MODE = 3;
  10891. Texture.PROJECTION_MODE = 4;
  10892. Texture.SKYBOX_MODE = 5;
  10893. Texture.CLAMP_ADDRESSMODE = 0;
  10894. Texture.WRAP_ADDRESSMODE = 1;
  10895. Texture.MIRROR_ADDRESSMODE = 2;
  10896. return Texture;
  10897. })(BABYLON.BaseTexture);
  10898. BABYLON.Texture = Texture;
  10899. })(BABYLON || (BABYLON = {}));
  10900. //# sourceMappingURL=babylon.texture.js.map
  10901. var BABYLON;
  10902. (function (BABYLON) {
  10903. var CubeTexture = (function (_super) {
  10904. __extends(CubeTexture, _super);
  10905. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10906. _super.call(this, scene);
  10907. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10908. this.name = rootUrl;
  10909. this.url = rootUrl;
  10910. this._noMipmap = noMipmap;
  10911. this.hasAlpha = false;
  10912. this._texture = this._getFromCache(rootUrl, noMipmap);
  10913. if (!extensions) {
  10914. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10915. }
  10916. this._extensions = extensions;
  10917. if (!this._texture) {
  10918. if (!scene.useDelayedTextureLoading) {
  10919. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10920. } else {
  10921. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10922. }
  10923. }
  10924. this.isCube = true;
  10925. this._textureMatrix = BABYLON.Matrix.Identity();
  10926. }
  10927. CubeTexture.prototype.clone = function () {
  10928. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10929. // Base texture
  10930. newTexture.level = this.level;
  10931. newTexture.wrapU = this.wrapU;
  10932. newTexture.wrapV = this.wrapV;
  10933. newTexture.coordinatesIndex = this.coordinatesIndex;
  10934. newTexture.coordinatesMode = this.coordinatesMode;
  10935. return newTexture;
  10936. };
  10937. // Methods
  10938. CubeTexture.prototype.delayLoad = function () {
  10939. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10940. return;
  10941. }
  10942. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10943. this._texture = this._getFromCache(this.url, this._noMipmap);
  10944. if (!this._texture) {
  10945. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10946. }
  10947. };
  10948. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10949. return this._textureMatrix;
  10950. };
  10951. return CubeTexture;
  10952. })(BABYLON.BaseTexture);
  10953. BABYLON.CubeTexture = CubeTexture;
  10954. })(BABYLON || (BABYLON = {}));
  10955. //# sourceMappingURL=babylon.cubeTexture.js.map
  10956. var BABYLON;
  10957. (function (BABYLON) {
  10958. var RenderTargetTexture = (function (_super) {
  10959. __extends(RenderTargetTexture, _super);
  10960. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10961. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10962. _super.call(this, null, scene, !generateMipMaps);
  10963. this.renderList = new Array();
  10964. this.renderParticles = true;
  10965. this.renderSprites = false;
  10966. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10967. this._currentRefreshId = -1;
  10968. this._refreshRate = 1;
  10969. this.name = name;
  10970. this.isRenderTarget = true;
  10971. this._size = size;
  10972. this._generateMipMaps = generateMipMaps;
  10973. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10974. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10975. // Rendering groups
  10976. this._renderingManager = new BABYLON.RenderingManager(scene);
  10977. }
  10978. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10979. this._currentRefreshId = -1;
  10980. };
  10981. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10982. get: function () {
  10983. return this._refreshRate;
  10984. },
  10985. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10986. set: function (value) {
  10987. this._refreshRate = value;
  10988. this.resetRefreshCounter();
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. RenderTargetTexture.prototype._shouldRender = function () {
  10994. if (this._currentRefreshId === -1) {
  10995. this._currentRefreshId = 1;
  10996. return true;
  10997. }
  10998. if (this.refreshRate == this._currentRefreshId) {
  10999. this._currentRefreshId = 1;
  11000. return true;
  11001. }
  11002. this._currentRefreshId++;
  11003. return false;
  11004. };
  11005. RenderTargetTexture.prototype.isReady = function () {
  11006. if (!this.getScene().renderTargetsEnabled) {
  11007. return false;
  11008. }
  11009. return _super.prototype.isReady.call(this);
  11010. };
  11011. RenderTargetTexture.prototype.getRenderSize = function () {
  11012. return this._size;
  11013. };
  11014. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11015. get: function () {
  11016. return true;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. RenderTargetTexture.prototype.scale = function (ratio) {
  11022. var newSize = this._size * ratio;
  11023. this.resize(newSize, this._generateMipMaps);
  11024. };
  11025. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11026. this.releaseInternalTexture();
  11027. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11028. };
  11029. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11030. var scene = this.getScene();
  11031. var engine = scene.getEngine();
  11032. if (this._waitingRenderList) {
  11033. this.renderList = [];
  11034. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11035. var id = this._waitingRenderList[index];
  11036. this.renderList.push(scene.getMeshByID(id));
  11037. }
  11038. delete this._waitingRenderList;
  11039. }
  11040. if (!this.renderList) {
  11041. return;
  11042. }
  11043. // Bind
  11044. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11045. engine.bindFramebuffer(this._texture);
  11046. }
  11047. // Clear
  11048. engine.clear(scene.clearColor, true, true);
  11049. this._renderingManager.reset();
  11050. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11051. var mesh = this.renderList[meshIndex];
  11052. if (mesh) {
  11053. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11054. // Reset _currentRefreshId
  11055. this.resetRefreshCounter();
  11056. continue;
  11057. }
  11058. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11059. mesh._activate(scene.getRenderId());
  11060. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11061. var subMesh = mesh.subMeshes[subIndex];
  11062. scene._activeVertices += subMesh.indexCount;
  11063. this._renderingManager.dispatch(subMesh);
  11064. }
  11065. }
  11066. }
  11067. }
  11068. if (!this._doNotChangeAspectRatio) {
  11069. scene.updateTransformMatrix(true);
  11070. }
  11071. if (this.onBeforeRender) {
  11072. this.onBeforeRender();
  11073. }
  11074. // Render
  11075. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11076. if (useCameraPostProcess) {
  11077. scene.postProcessManager._finalizeFrame(false, this._texture);
  11078. }
  11079. if (this.onAfterRender) {
  11080. this.onAfterRender();
  11081. }
  11082. // Unbind
  11083. engine.unBindFramebuffer(this._texture);
  11084. if (!this._doNotChangeAspectRatio) {
  11085. scene.updateTransformMatrix(true);
  11086. }
  11087. };
  11088. RenderTargetTexture.prototype.clone = function () {
  11089. var textureSize = this.getSize();
  11090. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11091. // Base texture
  11092. newTexture.hasAlpha = this.hasAlpha;
  11093. newTexture.level = this.level;
  11094. // RenderTarget Texture
  11095. newTexture.coordinatesMode = this.coordinatesMode;
  11096. newTexture.renderList = this.renderList.slice(0);
  11097. return newTexture;
  11098. };
  11099. return RenderTargetTexture;
  11100. })(BABYLON.Texture);
  11101. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11102. })(BABYLON || (BABYLON = {}));
  11103. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11104. var BABYLON;
  11105. (function (BABYLON) {
  11106. var ProceduralTexture = (function (_super) {
  11107. __extends(ProceduralTexture, _super);
  11108. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11109. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11110. _super.call(this, null, scene, !generateMipMaps);
  11111. this._currentRefreshId = -1;
  11112. this._refreshRate = 1;
  11113. this._vertexDeclaration = [2];
  11114. this._vertexStrideSize = 2 * 4;
  11115. this._uniforms = new Array();
  11116. this._samplers = new Array();
  11117. this._textures = new Array();
  11118. this._floats = new Array();
  11119. this._floatsArrays = {};
  11120. this._colors3 = new Array();
  11121. this._colors4 = new Array();
  11122. this._vectors2 = new Array();
  11123. this._vectors3 = new Array();
  11124. this._matrices = new Array();
  11125. this._fallbackTextureUsed = false;
  11126. scene._proceduralTextures.push(this);
  11127. this.name = name;
  11128. this.isRenderTarget = true;
  11129. this._size = size;
  11130. this._generateMipMaps = generateMipMaps;
  11131. this.setFragment(fragment);
  11132. this._fallbackTexture = fallbackTexture;
  11133. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11134. // VBO
  11135. var vertices = [];
  11136. vertices.push(1, 1);
  11137. vertices.push(-1, 1);
  11138. vertices.push(-1, -1);
  11139. vertices.push(1, -1);
  11140. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11141. // Indices
  11142. var indices = [];
  11143. indices.push(0);
  11144. indices.push(1);
  11145. indices.push(2);
  11146. indices.push(0);
  11147. indices.push(2);
  11148. indices.push(3);
  11149. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11150. }
  11151. ProceduralTexture.prototype.reset = function () {
  11152. if (this._effect === undefined) {
  11153. return;
  11154. }
  11155. var engine = this.getScene().getEngine();
  11156. engine._releaseEffect(this._effect);
  11157. };
  11158. ProceduralTexture.prototype.isReady = function () {
  11159. var _this = this;
  11160. var engine = this.getScene().getEngine();
  11161. var shaders;
  11162. if (!this._fragment) {
  11163. return false;
  11164. }
  11165. if (this._fallbackTextureUsed) {
  11166. return true;
  11167. }
  11168. if (this._fragment.fragmentElement !== undefined) {
  11169. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11170. } else {
  11171. shaders = { vertex: "procedural", fragment: this._fragment };
  11172. }
  11173. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11174. _this.releaseInternalTexture();
  11175. if (_this._fallbackTexture) {
  11176. _this._texture = _this._fallbackTexture._texture;
  11177. _this._texture.references++;
  11178. }
  11179. _this._fallbackTextureUsed = true;
  11180. });
  11181. return this._effect.isReady();
  11182. };
  11183. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11184. this._currentRefreshId = -1;
  11185. };
  11186. ProceduralTexture.prototype.setFragment = function (fragment) {
  11187. this._fragment = fragment;
  11188. };
  11189. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11190. get: function () {
  11191. return this._refreshRate;
  11192. },
  11193. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11194. set: function (value) {
  11195. this._refreshRate = value;
  11196. this.resetRefreshCounter();
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. ProceduralTexture.prototype._shouldRender = function () {
  11202. if (!this.isReady() || !this._texture) {
  11203. return false;
  11204. }
  11205. if (this._fallbackTextureUsed) {
  11206. return false;
  11207. }
  11208. if (this._currentRefreshId === -1) {
  11209. this._currentRefreshId = 1;
  11210. return true;
  11211. }
  11212. if (this.refreshRate === this._currentRefreshId) {
  11213. this._currentRefreshId = 1;
  11214. return true;
  11215. }
  11216. this._currentRefreshId++;
  11217. return false;
  11218. };
  11219. ProceduralTexture.prototype.getRenderSize = function () {
  11220. return this._size;
  11221. };
  11222. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11223. if (this._fallbackTextureUsed) {
  11224. return;
  11225. }
  11226. this.releaseInternalTexture();
  11227. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11228. };
  11229. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11230. if (this._uniforms.indexOf(uniformName) === -1) {
  11231. this._uniforms.push(uniformName);
  11232. }
  11233. };
  11234. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11235. if (this._samplers.indexOf(name) === -1) {
  11236. this._samplers.push(name);
  11237. }
  11238. this._textures[name] = texture;
  11239. return this;
  11240. };
  11241. ProceduralTexture.prototype.setFloat = function (name, value) {
  11242. this._checkUniform(name);
  11243. this._floats[name] = value;
  11244. return this;
  11245. };
  11246. ProceduralTexture.prototype.setFloats = function (name, value) {
  11247. this._checkUniform(name);
  11248. this._floatsArrays[name] = value;
  11249. return this;
  11250. };
  11251. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11252. this._checkUniform(name);
  11253. this._colors3[name] = value;
  11254. return this;
  11255. };
  11256. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11257. this._checkUniform(name);
  11258. this._colors4[name] = value;
  11259. return this;
  11260. };
  11261. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11262. this._checkUniform(name);
  11263. this._vectors2[name] = value;
  11264. return this;
  11265. };
  11266. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11267. this._checkUniform(name);
  11268. this._vectors3[name] = value;
  11269. return this;
  11270. };
  11271. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11272. this._checkUniform(name);
  11273. this._matrices[name] = value;
  11274. return this;
  11275. };
  11276. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11277. var scene = this.getScene();
  11278. var engine = scene.getEngine();
  11279. engine.bindFramebuffer(this._texture);
  11280. // Clear
  11281. engine.clear(scene.clearColor, true, true);
  11282. // Render
  11283. engine.enableEffect(this._effect);
  11284. engine.setState(false);
  11285. for (var name in this._textures) {
  11286. this._effect.setTexture(name, this._textures[name]);
  11287. }
  11288. for (name in this._floats) {
  11289. this._effect.setFloat(name, this._floats[name]);
  11290. }
  11291. for (name in this._floatsArrays) {
  11292. this._effect.setArray(name, this._floatsArrays[name]);
  11293. }
  11294. for (name in this._colors3) {
  11295. this._effect.setColor3(name, this._colors3[name]);
  11296. }
  11297. for (name in this._colors4) {
  11298. var color = this._colors4[name];
  11299. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11300. }
  11301. for (name in this._vectors2) {
  11302. this._effect.setVector2(name, this._vectors2[name]);
  11303. }
  11304. for (name in this._vectors3) {
  11305. this._effect.setVector3(name, this._vectors3[name]);
  11306. }
  11307. for (name in this._matrices) {
  11308. this._effect.setMatrix(name, this._matrices[name]);
  11309. }
  11310. // VBOs
  11311. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11312. // Draw order
  11313. engine.draw(true, 0, 6);
  11314. // Unbind
  11315. engine.unBindFramebuffer(this._texture);
  11316. };
  11317. ProceduralTexture.prototype.clone = function () {
  11318. var textureSize = this.getSize();
  11319. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11320. // Base texture
  11321. newTexture.hasAlpha = this.hasAlpha;
  11322. newTexture.level = this.level;
  11323. // RenderTarget Texture
  11324. newTexture.coordinatesMode = this.coordinatesMode;
  11325. return newTexture;
  11326. };
  11327. ProceduralTexture.prototype.dispose = function () {
  11328. var index = this.getScene()._proceduralTextures.indexOf(this);
  11329. if (index >= 0) {
  11330. this.getScene()._proceduralTextures.splice(index, 1);
  11331. }
  11332. _super.prototype.dispose.call(this);
  11333. };
  11334. return ProceduralTexture;
  11335. })(BABYLON.Texture);
  11336. BABYLON.ProceduralTexture = ProceduralTexture;
  11337. })(BABYLON || (BABYLON = {}));
  11338. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11339. var BABYLON;
  11340. (function (BABYLON) {
  11341. var WoodProceduralTexture = (function (_super) {
  11342. __extends(WoodProceduralTexture, _super);
  11343. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11344. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11345. this._ampScale = 100.0;
  11346. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11347. this.updateShaderUniforms();
  11348. this.refreshRate = 0;
  11349. }
  11350. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11351. this.setFloat("ampScale", this._ampScale);
  11352. this.setColor3("woodColor", this._woodColor);
  11353. };
  11354. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11355. get: function () {
  11356. return this._ampScale;
  11357. },
  11358. set: function (value) {
  11359. this._ampScale = value;
  11360. this.updateShaderUniforms();
  11361. },
  11362. enumerable: true,
  11363. configurable: true
  11364. });
  11365. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11366. get: function () {
  11367. return this._woodColor;
  11368. },
  11369. set: function (value) {
  11370. this._woodColor = value;
  11371. this.updateShaderUniforms();
  11372. },
  11373. enumerable: true,
  11374. configurable: true
  11375. });
  11376. return WoodProceduralTexture;
  11377. })(BABYLON.ProceduralTexture);
  11378. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11379. var FireProceduralTexture = (function (_super) {
  11380. __extends(FireProceduralTexture, _super);
  11381. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11382. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11383. this._time = 0.0;
  11384. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11385. this._shift = 1.6;
  11386. this._autoGenerateTime = true;
  11387. this._alphaThreshold = 0.5;
  11388. this._fireColors = FireProceduralTexture.RedFireColors;
  11389. this.updateShaderUniforms();
  11390. this.refreshRate = 1;
  11391. }
  11392. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11393. this.setFloat("time", this._time);
  11394. this.setVector2("speed", this._speed);
  11395. this.setFloat("shift", this._shift);
  11396. this.setColor3("c1", this._fireColors[0]);
  11397. this.setColor3("c2", this._fireColors[1]);
  11398. this.setColor3("c3", this._fireColors[2]);
  11399. this.setColor3("c4", this._fireColors[3]);
  11400. this.setColor3("c5", this._fireColors[4]);
  11401. this.setColor3("c6", this._fireColors[5]);
  11402. this.setFloat("alphaThreshold", this._alphaThreshold);
  11403. };
  11404. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11405. if (this._autoGenerateTime) {
  11406. this._time += this.getScene().getAnimationRatio() * 0.03;
  11407. this.updateShaderUniforms();
  11408. }
  11409. _super.prototype.render.call(this, useCameraPostProcess);
  11410. };
  11411. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11412. get: function () {
  11413. return [
  11414. new BABYLON.Color3(0.5, 0.0, 1.0),
  11415. new BABYLON.Color3(0.9, 0.0, 1.0),
  11416. new BABYLON.Color3(0.2, 0.0, 1.0),
  11417. new BABYLON.Color3(1.0, 0.9, 1.0),
  11418. new BABYLON.Color3(0.1, 0.1, 1.0),
  11419. new BABYLON.Color3(0.9, 0.9, 1.0)
  11420. ];
  11421. },
  11422. enumerable: true,
  11423. configurable: true
  11424. });
  11425. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11426. get: function () {
  11427. return [
  11428. new BABYLON.Color3(0.5, 1.0, 0.0),
  11429. new BABYLON.Color3(0.5, 1.0, 0.0),
  11430. new BABYLON.Color3(0.3, 0.4, 0.0),
  11431. new BABYLON.Color3(0.5, 1.0, 0.0),
  11432. new BABYLON.Color3(0.2, 0.0, 0.0),
  11433. new BABYLON.Color3(0.5, 1.0, 0.0)
  11434. ];
  11435. },
  11436. enumerable: true,
  11437. configurable: true
  11438. });
  11439. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11440. get: function () {
  11441. return [
  11442. new BABYLON.Color3(0.5, 0.0, 0.1),
  11443. new BABYLON.Color3(0.9, 0.0, 0.0),
  11444. new BABYLON.Color3(0.2, 0.0, 0.0),
  11445. new BABYLON.Color3(1.0, 0.9, 0.0),
  11446. new BABYLON.Color3(0.1, 0.1, 0.1),
  11447. new BABYLON.Color3(0.9, 0.9, 0.9)
  11448. ];
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11454. get: function () {
  11455. return [
  11456. new BABYLON.Color3(0.1, 0.0, 0.5),
  11457. new BABYLON.Color3(0.0, 0.0, 0.5),
  11458. new BABYLON.Color3(0.1, 0.0, 0.2),
  11459. new BABYLON.Color3(0.0, 0.0, 1.0),
  11460. new BABYLON.Color3(0.1, 0.2, 0.3),
  11461. new BABYLON.Color3(0.0, 0.2, 0.9)
  11462. ];
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11468. get: function () {
  11469. return this._fireColors;
  11470. },
  11471. set: function (value) {
  11472. this._fireColors = value;
  11473. this.updateShaderUniforms();
  11474. },
  11475. enumerable: true,
  11476. configurable: true
  11477. });
  11478. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11479. get: function () {
  11480. return this._time;
  11481. },
  11482. set: function (value) {
  11483. this._time = value;
  11484. this.updateShaderUniforms();
  11485. },
  11486. enumerable: true,
  11487. configurable: true
  11488. });
  11489. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11490. get: function () {
  11491. return this._speed;
  11492. },
  11493. set: function (value) {
  11494. this._speed = value;
  11495. this.updateShaderUniforms();
  11496. },
  11497. enumerable: true,
  11498. configurable: true
  11499. });
  11500. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11501. get: function () {
  11502. return this._shift;
  11503. },
  11504. set: function (value) {
  11505. this._shift = value;
  11506. this.updateShaderUniforms();
  11507. },
  11508. enumerable: true,
  11509. configurable: true
  11510. });
  11511. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11512. get: function () {
  11513. return this._alphaThreshold;
  11514. },
  11515. set: function (value) {
  11516. this._alphaThreshold = value;
  11517. this.updateShaderUniforms();
  11518. },
  11519. enumerable: true,
  11520. configurable: true
  11521. });
  11522. return FireProceduralTexture;
  11523. })(BABYLON.ProceduralTexture);
  11524. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11525. var CloudProceduralTexture = (function (_super) {
  11526. __extends(CloudProceduralTexture, _super);
  11527. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11528. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11529. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11530. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11531. this.updateShaderUniforms();
  11532. this.refreshRate = 0;
  11533. }
  11534. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11535. this.setColor3("skyColor", this._skyColor);
  11536. this.setColor3("cloudColor", this._cloudColor);
  11537. };
  11538. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11539. get: function () {
  11540. return this._skyColor;
  11541. },
  11542. set: function (value) {
  11543. this._skyColor = value;
  11544. this.updateShaderUniforms();
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11550. get: function () {
  11551. return this._cloudColor;
  11552. },
  11553. set: function (value) {
  11554. this._cloudColor = value;
  11555. this.updateShaderUniforms();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. return CloudProceduralTexture;
  11561. })(BABYLON.ProceduralTexture);
  11562. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11563. var GrassProceduralTexture = (function (_super) {
  11564. __extends(GrassProceduralTexture, _super);
  11565. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11566. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11567. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11568. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11569. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11570. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11571. this._grassColors = [
  11572. new BABYLON.Color3(0.29, 0.38, 0.02),
  11573. new BABYLON.Color3(0.36, 0.49, 0.09),
  11574. new BABYLON.Color3(0.51, 0.6, 0.28)
  11575. ];
  11576. this.updateShaderUniforms();
  11577. this.refreshRate = 0;
  11578. }
  11579. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11580. this.setColor3("herb1Color", this._grassColors[0]);
  11581. this.setColor3("herb2Color", this._grassColors[1]);
  11582. this.setColor3("herb3Color", this._grassColors[2]);
  11583. this.setColor3("groundColor", this._groundColor);
  11584. };
  11585. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11586. get: function () {
  11587. return this._grassColors;
  11588. },
  11589. set: function (value) {
  11590. this._grassColors = value;
  11591. this.updateShaderUniforms();
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11597. get: function () {
  11598. return this._groundColor;
  11599. },
  11600. set: function (value) {
  11601. this.groundColor = value;
  11602. this.updateShaderUniforms();
  11603. },
  11604. enumerable: true,
  11605. configurable: true
  11606. });
  11607. return GrassProceduralTexture;
  11608. })(BABYLON.ProceduralTexture);
  11609. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11610. var RoadProceduralTexture = (function (_super) {
  11611. __extends(RoadProceduralTexture, _super);
  11612. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11613. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11614. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11615. this.updateShaderUniforms();
  11616. this.refreshRate = 0;
  11617. }
  11618. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11619. this.setColor3("roadColor", this._roadColor);
  11620. };
  11621. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11622. get: function () {
  11623. return this._roadColor;
  11624. },
  11625. set: function (value) {
  11626. this._roadColor = value;
  11627. this.updateShaderUniforms();
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. return RoadProceduralTexture;
  11633. })(BABYLON.ProceduralTexture);
  11634. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11635. var BrickProceduralTexture = (function (_super) {
  11636. __extends(BrickProceduralTexture, _super);
  11637. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11638. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11639. this._numberOfBricksHeight = 15;
  11640. this._numberOfBricksWidth = 5;
  11641. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11642. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11643. this.updateShaderUniforms();
  11644. this.refreshRate = 0;
  11645. }
  11646. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11647. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11648. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11649. this.setColor3("brickColor", this._brickColor);
  11650. this.setColor3("jointColor", this._jointColor);
  11651. };
  11652. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11653. get: function () {
  11654. return this._numberOfBricksHeight;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11660. set: function (value) {
  11661. this._numberOfBricksHeight = value;
  11662. this.updateShaderUniforms();
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11668. get: function () {
  11669. return this._numberOfBricksWidth;
  11670. },
  11671. set: function (value) {
  11672. this._numberOfBricksHeight = value;
  11673. this.updateShaderUniforms();
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11679. get: function () {
  11680. return this._jointColor;
  11681. },
  11682. set: function (value) {
  11683. this._jointColor = value;
  11684. this.updateShaderUniforms();
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11690. get: function () {
  11691. return this._brickColor;
  11692. },
  11693. set: function (value) {
  11694. this._brickColor = value;
  11695. this.updateShaderUniforms();
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. return BrickProceduralTexture;
  11701. })(BABYLON.ProceduralTexture);
  11702. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11703. var MarbleProceduralTexture = (function (_super) {
  11704. __extends(MarbleProceduralTexture, _super);
  11705. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11706. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11707. this._numberOfTilesHeight = 3;
  11708. this._numberOfTilesWidth = 3;
  11709. this._amplitude = 9.0;
  11710. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11711. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11712. this.updateShaderUniforms();
  11713. this.refreshRate = 0;
  11714. }
  11715. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11716. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11717. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11718. this.setFloat("amplitude", this._amplitude);
  11719. this.setColor3("marbleColor", this._marbleColor);
  11720. this.setColor3("jointColor", this._jointColor);
  11721. };
  11722. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11723. get: function () {
  11724. return this._numberOfTilesHeight;
  11725. },
  11726. set: function (value) {
  11727. this._numberOfTilesHeight = value;
  11728. this.updateShaderUniforms();
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11734. get: function () {
  11735. return this._numberOfTilesWidth;
  11736. },
  11737. set: function (value) {
  11738. this._numberOfTilesWidth = value;
  11739. this.updateShaderUniforms();
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11745. get: function () {
  11746. return this._jointColor;
  11747. },
  11748. set: function (value) {
  11749. this._jointColor = value;
  11750. this.updateShaderUniforms();
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11756. get: function () {
  11757. return this._marbleColor;
  11758. },
  11759. set: function (value) {
  11760. this._marbleColor = value;
  11761. this.updateShaderUniforms();
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. return MarbleProceduralTexture;
  11767. })(BABYLON.ProceduralTexture);
  11768. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11769. })(BABYLON || (BABYLON = {}));
  11770. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11771. var BABYLON;
  11772. (function (BABYLON) {
  11773. var CustomProceduralTexture = (function (_super) {
  11774. __extends(CustomProceduralTexture, _super);
  11775. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11776. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11777. this._animate = true;
  11778. this._time = 0;
  11779. this._texturePath = texturePath;
  11780. //Try to load json
  11781. this.loadJson(texturePath);
  11782. this.refreshRate = 1;
  11783. }
  11784. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11785. var _this = this;
  11786. var that = this;
  11787. function noConfigFile() {
  11788. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11789. try {
  11790. that.setFragment(that._texturePath);
  11791. } catch (ex) {
  11792. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11793. }
  11794. }
  11795. var configFileUrl = jsonUrl + "/config.json";
  11796. var xhr = new XMLHttpRequest();
  11797. xhr.open("GET", configFileUrl, true);
  11798. xhr.addEventListener("load", function () {
  11799. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11800. try {
  11801. _this._config = JSON.parse(xhr.response);
  11802. _this.updateShaderUniforms();
  11803. _this.updateTextures();
  11804. _this.setFragment(_this._texturePath + "/custom");
  11805. _this._animate = _this._config.animate;
  11806. _this.refreshRate = _this._config.refreshrate;
  11807. } catch (ex) {
  11808. noConfigFile();
  11809. }
  11810. } else {
  11811. noConfigFile();
  11812. }
  11813. }, false);
  11814. xhr.addEventListener("error", function (event) {
  11815. noConfigFile();
  11816. }, false);
  11817. try {
  11818. xhr.send();
  11819. } catch (ex) {
  11820. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11821. }
  11822. };
  11823. CustomProceduralTexture.prototype.isReady = function () {
  11824. if (!_super.prototype.isReady.call(this)) {
  11825. return false;
  11826. }
  11827. for (var name in this._textures) {
  11828. var texture = this._textures[name];
  11829. if (!texture.isReady()) {
  11830. return false;
  11831. }
  11832. }
  11833. return true;
  11834. };
  11835. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11836. if (this._animate) {
  11837. this._time += this.getScene().getAnimationRatio() * 0.03;
  11838. this.updateShaderUniforms();
  11839. }
  11840. _super.prototype.render.call(this, useCameraPostProcess);
  11841. };
  11842. CustomProceduralTexture.prototype.updateTextures = function () {
  11843. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11844. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11845. }
  11846. };
  11847. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11848. if (this._config) {
  11849. for (var j = 0; j < this._config.uniforms.length; j++) {
  11850. var uniform = this._config.uniforms[j];
  11851. switch (uniform.type) {
  11852. case "float":
  11853. this.setFloat(uniform.name, uniform.value);
  11854. break;
  11855. case "color3":
  11856. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11857. break;
  11858. case "color4":
  11859. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11860. break;
  11861. case "vector2":
  11862. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11863. break;
  11864. case "vector3":
  11865. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11866. break;
  11867. }
  11868. }
  11869. }
  11870. this.setFloat("time", this._time);
  11871. };
  11872. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11873. get: function () {
  11874. return this._animate;
  11875. },
  11876. set: function (value) {
  11877. this._animate = value;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. return CustomProceduralTexture;
  11883. })(BABYLON.ProceduralTexture);
  11884. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11885. })(BABYLON || (BABYLON = {}));
  11886. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11887. var BABYLON;
  11888. (function (BABYLON) {
  11889. var MirrorTexture = (function (_super) {
  11890. __extends(MirrorTexture, _super);
  11891. function MirrorTexture(name, size, scene, generateMipMaps) {
  11892. var _this = this;
  11893. _super.call(this, name, size, scene, generateMipMaps, true);
  11894. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11895. this._transformMatrix = BABYLON.Matrix.Zero();
  11896. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11897. this.onBeforeRender = function () {
  11898. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11899. _this._savedViewMatrix = scene.getViewMatrix();
  11900. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11901. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11902. scene.clipPlane = _this.mirrorPlane;
  11903. scene.getEngine().cullBackFaces = false;
  11904. };
  11905. this.onAfterRender = function () {
  11906. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11907. scene.getEngine().cullBackFaces = true;
  11908. delete scene.clipPlane;
  11909. };
  11910. }
  11911. MirrorTexture.prototype.clone = function () {
  11912. var textureSize = this.getSize();
  11913. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11914. // Base texture
  11915. newTexture.hasAlpha = this.hasAlpha;
  11916. newTexture.level = this.level;
  11917. // Mirror Texture
  11918. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11919. newTexture.renderList = this.renderList.slice(0);
  11920. return newTexture;
  11921. };
  11922. return MirrorTexture;
  11923. })(BABYLON.RenderTargetTexture);
  11924. BABYLON.MirrorTexture = MirrorTexture;
  11925. })(BABYLON || (BABYLON = {}));
  11926. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11927. var BABYLON;
  11928. (function (BABYLON) {
  11929. var DynamicTexture = (function (_super) {
  11930. __extends(DynamicTexture, _super);
  11931. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11932. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11933. _super.call(this, null, scene, !generateMipMaps);
  11934. this.name = name;
  11935. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11936. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11937. this._generateMipMaps = generateMipMaps;
  11938. if (options.getContext) {
  11939. this._canvas = options;
  11940. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11941. } else {
  11942. this._canvas = document.createElement("canvas");
  11943. if (options.width) {
  11944. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11945. } else {
  11946. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11947. }
  11948. }
  11949. var textureSize = this.getSize();
  11950. this._canvas.width = textureSize.width;
  11951. this._canvas.height = textureSize.height;
  11952. this._context = this._canvas.getContext("2d");
  11953. }
  11954. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11955. get: function () {
  11956. return true;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. DynamicTexture.prototype.scale = function (ratio) {
  11962. var textureSize = this.getSize();
  11963. textureSize.width *= ratio;
  11964. textureSize.height *= ratio;
  11965. this._canvas.width = textureSize.width;
  11966. this._canvas.height = textureSize.height;
  11967. this.releaseInternalTexture();
  11968. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11969. };
  11970. DynamicTexture.prototype.getContext = function () {
  11971. return this._context;
  11972. };
  11973. DynamicTexture.prototype.update = function (invertY) {
  11974. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11975. };
  11976. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11977. var size = this.getSize();
  11978. if (clearColor) {
  11979. this._context.fillStyle = clearColor;
  11980. this._context.fillRect(0, 0, size.width, size.height);
  11981. }
  11982. this._context.font = font;
  11983. if (x === null) {
  11984. var textSize = this._context.measureText(text);
  11985. x = (size.width - textSize.width) / 2;
  11986. }
  11987. this._context.fillStyle = color;
  11988. this._context.fillText(text, x, y);
  11989. this.update(invertY);
  11990. };
  11991. DynamicTexture.prototype.clone = function () {
  11992. var textureSize = this.getSize();
  11993. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11994. // Base texture
  11995. newTexture.hasAlpha = this.hasAlpha;
  11996. newTexture.level = this.level;
  11997. // Dynamic Texture
  11998. newTexture.wrapU = this.wrapU;
  11999. newTexture.wrapV = this.wrapV;
  12000. return newTexture;
  12001. };
  12002. return DynamicTexture;
  12003. })(BABYLON.Texture);
  12004. BABYLON.DynamicTexture = DynamicTexture;
  12005. })(BABYLON || (BABYLON = {}));
  12006. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12007. var BABYLON;
  12008. (function (BABYLON) {
  12009. var VideoTexture = (function (_super) {
  12010. __extends(VideoTexture, _super);
  12011. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12012. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12013. var _this = this;
  12014. _super.call(this, null, scene, !generateMipMaps, invertY);
  12015. this._autoLaunch = true;
  12016. this.name = name;
  12017. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12018. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12019. var requiredWidth = size.width || size;
  12020. var requiredHeight = size.height || size;
  12021. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12022. var textureSize = this.getSize();
  12023. this.video = document.createElement("video");
  12024. this.video.width = textureSize.width;
  12025. this.video.height = textureSize.height;
  12026. this.video.autoplay = false;
  12027. this.video.loop = true;
  12028. this.video.addEventListener("canplaythrough", function () {
  12029. if (_this._texture) {
  12030. _this._texture.isReady = true;
  12031. }
  12032. });
  12033. urls.forEach(function (url) {
  12034. var source = document.createElement("source");
  12035. source.src = url;
  12036. _this.video.appendChild(source);
  12037. });
  12038. this._lastUpdate = BABYLON.Tools.Now;
  12039. }
  12040. VideoTexture.prototype.update = function () {
  12041. if (this._autoLaunch) {
  12042. this._autoLaunch = false;
  12043. this.video.play();
  12044. }
  12045. var now = BABYLON.Tools.Now;
  12046. if (now - this._lastUpdate < 15) {
  12047. return false;
  12048. }
  12049. this._lastUpdate = now;
  12050. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12051. return true;
  12052. };
  12053. return VideoTexture;
  12054. })(BABYLON.Texture);
  12055. BABYLON.VideoTexture = VideoTexture;
  12056. })(BABYLON || (BABYLON = {}));
  12057. //# sourceMappingURL=babylon.videoTexture.js.map
  12058. var BABYLON;
  12059. (function (BABYLON) {
  12060. var EffectFallbacks = (function () {
  12061. function EffectFallbacks() {
  12062. this._defines = {};
  12063. this._currentRank = 32;
  12064. this._maxRank = -1;
  12065. }
  12066. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12067. if (!this._defines[rank]) {
  12068. if (rank < this._currentRank) {
  12069. this._currentRank = rank;
  12070. }
  12071. if (rank > this._maxRank) {
  12072. this._maxRank = rank;
  12073. }
  12074. this._defines[rank] = new Array();
  12075. }
  12076. this._defines[rank].push(define);
  12077. };
  12078. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12079. get: function () {
  12080. return this._currentRank <= this._maxRank;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12086. var currentFallbacks = this._defines[this._currentRank];
  12087. for (var index = 0; index < currentFallbacks.length; index++) {
  12088. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12089. }
  12090. this._currentRank++;
  12091. return currentDefines;
  12092. };
  12093. return EffectFallbacks;
  12094. })();
  12095. BABYLON.EffectFallbacks = EffectFallbacks;
  12096. var Effect = (function () {
  12097. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12098. var _this = this;
  12099. this._isReady = false;
  12100. this._compilationError = "";
  12101. this._valueCache = [];
  12102. this._engine = engine;
  12103. this.name = baseName;
  12104. this.defines = defines;
  12105. this._uniformsNames = uniformsNames.concat(samplers);
  12106. this._samplers = samplers;
  12107. this._attributesNames = attributesNames;
  12108. this.onError = onError;
  12109. this.onCompiled = onCompiled;
  12110. var vertexSource;
  12111. var fragmentSource;
  12112. if (baseName.vertexElement) {
  12113. vertexSource = document.getElementById(baseName.vertexElement);
  12114. if (!vertexSource) {
  12115. vertexSource = baseName.vertexElement;
  12116. }
  12117. } else {
  12118. vertexSource = baseName.vertex || baseName;
  12119. }
  12120. if (baseName.fragmentElement) {
  12121. fragmentSource = document.getElementById(baseName.fragmentElement);
  12122. if (!fragmentSource) {
  12123. fragmentSource = baseName.fragmentElement;
  12124. }
  12125. } else {
  12126. fragmentSource = baseName.fragment || baseName;
  12127. }
  12128. this._loadVertexShader(vertexSource, function (vertexCode) {
  12129. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12130. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12131. });
  12132. });
  12133. }
  12134. // Properties
  12135. Effect.prototype.isReady = function () {
  12136. return this._isReady;
  12137. };
  12138. Effect.prototype.getProgram = function () {
  12139. return this._program;
  12140. };
  12141. Effect.prototype.getAttributesNames = function () {
  12142. return this._attributesNames;
  12143. };
  12144. Effect.prototype.getAttributeLocation = function (index) {
  12145. return this._attributes[index];
  12146. };
  12147. Effect.prototype.getAttributeLocationByName = function (name) {
  12148. var index = this._attributesNames.indexOf(name);
  12149. return this._attributes[index];
  12150. };
  12151. Effect.prototype.getAttributesCount = function () {
  12152. return this._attributes.length;
  12153. };
  12154. Effect.prototype.getUniformIndex = function (uniformName) {
  12155. return this._uniformsNames.indexOf(uniformName);
  12156. };
  12157. Effect.prototype.getUniform = function (uniformName) {
  12158. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12159. };
  12160. Effect.prototype.getSamplers = function () {
  12161. return this._samplers;
  12162. };
  12163. Effect.prototype.getCompilationError = function () {
  12164. return this._compilationError;
  12165. };
  12166. // Methods
  12167. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12168. // DOM element ?
  12169. if (vertex instanceof HTMLElement) {
  12170. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12171. callback(vertexCode);
  12172. return;
  12173. }
  12174. // Is in local store ?
  12175. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12176. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12177. return;
  12178. }
  12179. var vertexShaderUrl;
  12180. if (vertex[0] === ".") {
  12181. vertexShaderUrl = vertex;
  12182. } else {
  12183. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12184. }
  12185. // Vertex shader
  12186. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12187. };
  12188. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12189. // DOM element ?
  12190. if (fragment instanceof HTMLElement) {
  12191. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12192. callback(fragmentCode);
  12193. return;
  12194. }
  12195. // Is in local store ?
  12196. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12197. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12198. return;
  12199. }
  12200. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12201. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12202. return;
  12203. }
  12204. var fragmentShaderUrl;
  12205. if (fragment[0] === ".") {
  12206. fragmentShaderUrl = fragment;
  12207. } else {
  12208. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12209. }
  12210. // Fragment shader
  12211. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12212. };
  12213. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12214. try {
  12215. var engine = this._engine;
  12216. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12217. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12218. this._attributes = engine.getAttributes(this._program, attributesNames);
  12219. for (var index = 0; index < this._samplers.length; index++) {
  12220. var sampler = this.getUniform(this._samplers[index]);
  12221. if (sampler == null) {
  12222. this._samplers.splice(index, 1);
  12223. index--;
  12224. }
  12225. }
  12226. engine.bindSamplers(this);
  12227. this._isReady = true;
  12228. if (this.onCompiled) {
  12229. this.onCompiled(this);
  12230. }
  12231. } catch (e) {
  12232. // Is it a problem with precision?
  12233. if (e.message.indexOf("highp") !== -1) {
  12234. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12235. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12236. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12237. return;
  12238. }
  12239. // Let's go through fallbacks then
  12240. if (fallbacks && fallbacks.isMoreFallbacks) {
  12241. defines = fallbacks.reduce(defines);
  12242. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12243. } else {
  12244. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12245. BABYLON.Tools.Error("Defines: " + defines);
  12246. BABYLON.Tools.Error("Error: " + e.message);
  12247. this._compilationError = e.message;
  12248. if (this.onError) {
  12249. this.onError(this, this._compilationError);
  12250. }
  12251. }
  12252. }
  12253. };
  12254. Effect.prototype._bindTexture = function (channel, texture) {
  12255. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12256. };
  12257. Effect.prototype.setTexture = function (channel, texture) {
  12258. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12259. };
  12260. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12261. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12262. };
  12263. //public _cacheMatrix(uniformName, matrix) {
  12264. // if (!this._valueCache[uniformName]) {
  12265. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12266. // }
  12267. // for (var index = 0; index < 16; index++) {
  12268. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12269. // }
  12270. //};
  12271. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12272. if (!this._valueCache[uniformName]) {
  12273. this._valueCache[uniformName] = [x, y];
  12274. return;
  12275. }
  12276. this._valueCache[uniformName][0] = x;
  12277. this._valueCache[uniformName][1] = y;
  12278. };
  12279. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12280. if (!this._valueCache[uniformName]) {
  12281. this._valueCache[uniformName] = [x, y, z];
  12282. return;
  12283. }
  12284. this._valueCache[uniformName][0] = x;
  12285. this._valueCache[uniformName][1] = y;
  12286. this._valueCache[uniformName][2] = z;
  12287. };
  12288. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12289. if (!this._valueCache[uniformName]) {
  12290. this._valueCache[uniformName] = [x, y, z, w];
  12291. return;
  12292. }
  12293. this._valueCache[uniformName][0] = x;
  12294. this._valueCache[uniformName][1] = y;
  12295. this._valueCache[uniformName][2] = z;
  12296. this._valueCache[uniformName][3] = w;
  12297. };
  12298. Effect.prototype.setArray = function (uniformName, array) {
  12299. this._engine.setArray(this.getUniform(uniformName), array);
  12300. return this;
  12301. };
  12302. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12303. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12304. return this;
  12305. };
  12306. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12307. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12308. // return;
  12309. //this._cacheMatrix(uniformName, matrix);
  12310. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12311. return this;
  12312. };
  12313. Effect.prototype.setFloat = function (uniformName, value) {
  12314. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12315. return this;
  12316. this._valueCache[uniformName] = value;
  12317. this._engine.setFloat(this.getUniform(uniformName), value);
  12318. return this;
  12319. };
  12320. Effect.prototype.setBool = function (uniformName, bool) {
  12321. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12322. return this;
  12323. this._valueCache[uniformName] = bool;
  12324. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12325. return this;
  12326. };
  12327. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12328. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12329. return this;
  12330. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12331. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12332. return this;
  12333. };
  12334. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12335. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12336. return this;
  12337. this._cacheFloat2(uniformName, x, y);
  12338. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12339. return this;
  12340. };
  12341. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12342. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12343. return this;
  12344. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12345. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12346. return this;
  12347. };
  12348. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12349. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12350. return this;
  12351. this._cacheFloat3(uniformName, x, y, z);
  12352. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12353. return this;
  12354. };
  12355. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12356. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12357. return this;
  12358. this._cacheFloat4(uniformName, x, y, z, w);
  12359. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12360. return this;
  12361. };
  12362. Effect.prototype.setColor3 = function (uniformName, color3) {
  12363. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12364. return this;
  12365. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12366. this._engine.setColor3(this.getUniform(uniformName), color3);
  12367. return this;
  12368. };
  12369. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12370. 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)
  12371. return this;
  12372. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12373. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12374. return this;
  12375. };
  12376. 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}",
  12377. 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}",
  12378. 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}",
  12379. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  12380. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  12381. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12382. 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}",
  12383. 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}",
  12384. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12385. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n 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\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  12386. 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}",
  12387. 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}",
  12388. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  12389. 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}",
  12390. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  12391. 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}",
  12392. 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}",
  12393. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12394. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  12395. 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}",
  12396. 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}",
  12397. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  12398. 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}",
  12399. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  12400. 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}",
  12401. 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}",
  12402. 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}",
  12403. 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}",
  12404. 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}",
  12405. 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}",
  12406. 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}",
  12407. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  12408. 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}",
  12409. 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}",
  12410. 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}",
  12411. 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}",
  12412. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  12413. };
  12414. return Effect;
  12415. })();
  12416. BABYLON.Effect = Effect;
  12417. })(BABYLON || (BABYLON = {}));
  12418. //# sourceMappingURL=babylon.effect.js.map
  12419. var BABYLON;
  12420. (function (BABYLON) {
  12421. var Material = (function () {
  12422. function Material(name, scene, doNotAdd) {
  12423. this.name = name;
  12424. this.checkReadyOnEveryCall = true;
  12425. this.checkReadyOnlyOnce = false;
  12426. this.state = "";
  12427. this.alpha = 1.0;
  12428. this.backFaceCulling = true;
  12429. this._wasPreviouslyReady = false;
  12430. this._fillMode = Material.TriangleFillMode;
  12431. this.pointSize = 1.0;
  12432. this.id = name;
  12433. this._scene = scene;
  12434. if (!doNotAdd) {
  12435. scene.materials.push(this);
  12436. }
  12437. }
  12438. Object.defineProperty(Material, "TriangleFillMode", {
  12439. get: function () {
  12440. return Material._TriangleFillMode;
  12441. },
  12442. enumerable: true,
  12443. configurable: true
  12444. });
  12445. Object.defineProperty(Material, "WireFrameFillMode", {
  12446. get: function () {
  12447. return Material._WireFrameFillMode;
  12448. },
  12449. enumerable: true,
  12450. configurable: true
  12451. });
  12452. Object.defineProperty(Material, "PointFillMode", {
  12453. get: function () {
  12454. return Material._PointFillMode;
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Material.prototype, "wireframe", {
  12460. get: function () {
  12461. return this._fillMode === Material.WireFrameFillMode;
  12462. },
  12463. set: function (value) {
  12464. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12465. },
  12466. enumerable: true,
  12467. configurable: true
  12468. });
  12469. Object.defineProperty(Material.prototype, "pointsCloud", {
  12470. get: function () {
  12471. return this._fillMode === Material.PointFillMode;
  12472. },
  12473. set: function (value) {
  12474. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. Object.defineProperty(Material.prototype, "fillMode", {
  12480. get: function () {
  12481. return this._fillMode;
  12482. },
  12483. set: function (value) {
  12484. this._fillMode = value;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Material.prototype.isReady = function (mesh, useInstances) {
  12490. return true;
  12491. };
  12492. Material.prototype.getEffect = function () {
  12493. return this._effect;
  12494. };
  12495. Material.prototype.getScene = function () {
  12496. return this._scene;
  12497. };
  12498. Material.prototype.needAlphaBlending = function () {
  12499. return (this.alpha < 1.0);
  12500. };
  12501. Material.prototype.needAlphaTesting = function () {
  12502. return false;
  12503. };
  12504. Material.prototype.getAlphaTestTexture = function () {
  12505. return null;
  12506. };
  12507. Material.prototype.trackCreation = function (onCompiled, onError) {
  12508. };
  12509. Material.prototype._preBind = function () {
  12510. var engine = this._scene.getEngine();
  12511. engine.enableEffect(this._effect);
  12512. engine.setState(this.backFaceCulling);
  12513. };
  12514. Material.prototype.bind = function (world, mesh) {
  12515. this._scene._cachedMaterial = this;
  12516. if (this.onBind) {
  12517. this.onBind(this);
  12518. }
  12519. };
  12520. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12521. };
  12522. Material.prototype.unbind = function () {
  12523. };
  12524. Material.prototype.dispose = function (forceDisposeEffect) {
  12525. // Remove from scene
  12526. var index = this._scene.materials.indexOf(this);
  12527. this._scene.materials.splice(index, 1);
  12528. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12529. if (forceDisposeEffect && this._effect) {
  12530. this._scene.getEngine()._releaseEffect(this._effect);
  12531. this._effect = null;
  12532. }
  12533. // Callback
  12534. if (this.onDispose) {
  12535. this.onDispose();
  12536. }
  12537. };
  12538. Material._TriangleFillMode = 0;
  12539. Material._WireFrameFillMode = 1;
  12540. Material._PointFillMode = 2;
  12541. return Material;
  12542. })();
  12543. BABYLON.Material = Material;
  12544. })(BABYLON || (BABYLON = {}));
  12545. //# sourceMappingURL=babylon.material.js.map
  12546. var BABYLON;
  12547. (function (BABYLON) {
  12548. var maxSimultaneousLights = 4;
  12549. var FresnelParameters = (function () {
  12550. function FresnelParameters() {
  12551. this.isEnabled = true;
  12552. this.leftColor = BABYLON.Color3.White();
  12553. this.rightColor = BABYLON.Color3.Black();
  12554. this.bias = 0;
  12555. this.power = 1;
  12556. }
  12557. return FresnelParameters;
  12558. })();
  12559. BABYLON.FresnelParameters = FresnelParameters;
  12560. var StandardMaterial = (function (_super) {
  12561. __extends(StandardMaterial, _super);
  12562. function StandardMaterial(name, scene) {
  12563. var _this = this;
  12564. _super.call(this, name, scene);
  12565. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12566. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12567. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12568. this.specularPower = 64;
  12569. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12570. this.useAlphaFromDiffuseTexture = false;
  12571. this.useSpecularOverAlpha = true;
  12572. this.fogEnabled = true;
  12573. this._cachedDefines = null;
  12574. this._renderTargets = new BABYLON.SmartArray(16);
  12575. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12576. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12577. this._scaledDiffuse = new BABYLON.Color3();
  12578. this._scaledSpecular = new BABYLON.Color3();
  12579. this.getRenderTargetTextures = function () {
  12580. _this._renderTargets.reset();
  12581. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12582. _this._renderTargets.push(_this.reflectionTexture);
  12583. }
  12584. return _this._renderTargets;
  12585. };
  12586. }
  12587. StandardMaterial.prototype.needAlphaBlending = function () {
  12588. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12589. };
  12590. StandardMaterial.prototype.needAlphaTesting = function () {
  12591. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12592. };
  12593. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12594. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12595. };
  12596. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12597. return this.diffuseTexture;
  12598. };
  12599. // Methods
  12600. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12601. if (this.checkReadyOnlyOnce) {
  12602. if (this._wasPreviouslyReady) {
  12603. return true;
  12604. }
  12605. }
  12606. var scene = this.getScene();
  12607. if (!this.checkReadyOnEveryCall) {
  12608. if (this._renderId === scene.getRenderId()) {
  12609. return true;
  12610. }
  12611. }
  12612. var engine = scene.getEngine();
  12613. var defines = [];
  12614. var fallbacks = new BABYLON.EffectFallbacks();
  12615. // Textures
  12616. if (scene.texturesEnabled) {
  12617. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12618. if (!this.diffuseTexture.isReady()) {
  12619. return false;
  12620. } else {
  12621. defines.push("#define DIFFUSE");
  12622. }
  12623. }
  12624. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12625. if (!this.ambientTexture.isReady()) {
  12626. return false;
  12627. } else {
  12628. defines.push("#define AMBIENT");
  12629. }
  12630. }
  12631. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12632. if (!this.opacityTexture.isReady()) {
  12633. return false;
  12634. } else {
  12635. defines.push("#define OPACITY");
  12636. if (this.opacityTexture.getAlphaFromRGB) {
  12637. defines.push("#define OPACITYRGB");
  12638. }
  12639. }
  12640. }
  12641. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12642. if (!this.reflectionTexture.isReady()) {
  12643. return false;
  12644. } else {
  12645. defines.push("#define REFLECTION");
  12646. fallbacks.addFallback(0, "REFLECTION");
  12647. }
  12648. }
  12649. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12650. if (!this.emissiveTexture.isReady()) {
  12651. return false;
  12652. } else {
  12653. defines.push("#define EMISSIVE");
  12654. }
  12655. }
  12656. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12657. if (!this.specularTexture.isReady()) {
  12658. return false;
  12659. } else {
  12660. defines.push("#define SPECULAR");
  12661. fallbacks.addFallback(0, "SPECULAR");
  12662. }
  12663. }
  12664. }
  12665. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12666. if (!this.bumpTexture.isReady()) {
  12667. return false;
  12668. } else {
  12669. defines.push("#define BUMP");
  12670. fallbacks.addFallback(0, "BUMP");
  12671. }
  12672. }
  12673. // Effect
  12674. if (this.useSpecularOverAlpha) {
  12675. defines.push("#define SPECULAROVERALPHA");
  12676. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12677. }
  12678. if (scene.clipPlane) {
  12679. defines.push("#define CLIPPLANE");
  12680. }
  12681. if (engine.getAlphaTesting()) {
  12682. defines.push("#define ALPHATEST");
  12683. }
  12684. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12685. defines.push("#define ALPHAFROMDIFFUSE");
  12686. }
  12687. // Point size
  12688. if (this.pointsCloud || scene.forcePointsCloud) {
  12689. defines.push("#define POINTSIZE");
  12690. }
  12691. // Fog
  12692. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12693. defines.push("#define FOG");
  12694. fallbacks.addFallback(1, "FOG");
  12695. }
  12696. var shadowsActivated = false;
  12697. var lightIndex = 0;
  12698. if (scene.lightsEnabled) {
  12699. for (var index = 0; index < scene.lights.length; index++) {
  12700. var light = scene.lights[index];
  12701. if (!light.isEnabled()) {
  12702. continue;
  12703. }
  12704. // Excluded check
  12705. if (light._excludedMeshesIds.length > 0) {
  12706. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12707. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12708. if (excludedMesh) {
  12709. light.excludedMeshes.push(excludedMesh);
  12710. }
  12711. }
  12712. light._excludedMeshesIds = [];
  12713. }
  12714. // Included check
  12715. if (light._includedOnlyMeshesIds.length > 0) {
  12716. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12717. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12718. if (includedOnlyMesh) {
  12719. light.includedOnlyMeshes.push(includedOnlyMesh);
  12720. }
  12721. }
  12722. light._includedOnlyMeshesIds = [];
  12723. }
  12724. if (!light.canAffectMesh(mesh)) {
  12725. continue;
  12726. }
  12727. defines.push("#define LIGHT" + lightIndex);
  12728. if (lightIndex > 0) {
  12729. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12730. }
  12731. var type;
  12732. if (light instanceof BABYLON.SpotLight) {
  12733. type = "#define SPOTLIGHT" + lightIndex;
  12734. } else if (light instanceof BABYLON.HemisphericLight) {
  12735. type = "#define HEMILIGHT" + lightIndex;
  12736. } else {
  12737. type = "#define POINTDIRLIGHT" + lightIndex;
  12738. }
  12739. defines.push(type);
  12740. if (lightIndex > 0) {
  12741. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12742. }
  12743. // Shadows
  12744. if (scene.shadowsEnabled) {
  12745. var shadowGenerator = light.getShadowGenerator();
  12746. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12747. defines.push("#define SHADOW" + lightIndex);
  12748. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12749. if (!shadowsActivated) {
  12750. defines.push("#define SHADOWS");
  12751. shadowsActivated = true;
  12752. }
  12753. if (shadowGenerator.useVarianceShadowMap) {
  12754. defines.push("#define SHADOWVSM" + lightIndex);
  12755. if (lightIndex > 0) {
  12756. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12757. }
  12758. }
  12759. if (shadowGenerator.usePoissonSampling) {
  12760. defines.push("#define SHADOWPCF" + lightIndex);
  12761. if (lightIndex > 0) {
  12762. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12763. }
  12764. }
  12765. }
  12766. }
  12767. lightIndex++;
  12768. if (lightIndex === maxSimultaneousLights)
  12769. break;
  12770. }
  12771. }
  12772. if (StandardMaterial.FresnelEnabled) {
  12773. // Fresnel
  12774. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12775. var fresnelRank = 1;
  12776. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12777. defines.push("#define DIFFUSEFRESNEL");
  12778. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12779. fresnelRank++;
  12780. }
  12781. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12782. defines.push("#define OPACITYFRESNEL");
  12783. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12784. fresnelRank++;
  12785. }
  12786. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12787. defines.push("#define REFLECTIONFRESNEL");
  12788. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12789. fresnelRank++;
  12790. }
  12791. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12792. defines.push("#define EMISSIVEFRESNEL");
  12793. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12794. fresnelRank++;
  12795. }
  12796. defines.push("#define FRESNEL");
  12797. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12798. }
  12799. }
  12800. // Attribs
  12801. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12802. if (mesh) {
  12803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12804. attribs.push(BABYLON.VertexBuffer.UVKind);
  12805. defines.push("#define UV1");
  12806. }
  12807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12809. defines.push("#define UV2");
  12810. }
  12811. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12812. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12813. defines.push("#define VERTEXCOLOR");
  12814. if (mesh.hasVertexAlpha) {
  12815. defines.push("#define VERTEXALPHA");
  12816. }
  12817. }
  12818. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12819. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12820. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12821. defines.push("#define BONES");
  12822. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12823. defines.push("#define BONES4");
  12824. fallbacks.addFallback(0, "BONES4");
  12825. }
  12826. // Instances
  12827. if (useInstances) {
  12828. defines.push("#define INSTANCES");
  12829. attribs.push("world0");
  12830. attribs.push("world1");
  12831. attribs.push("world2");
  12832. attribs.push("world3");
  12833. }
  12834. }
  12835. // Get correct effect
  12836. var join = defines.join("\n");
  12837. if (this._cachedDefines !== join) {
  12838. this._cachedDefines = join;
  12839. scene.resetCachedMaterial();
  12840. // Legacy browser patch
  12841. var shaderName = "default";
  12842. if (!scene.getEngine().getCaps().standardDerivatives) {
  12843. shaderName = "legacydefault";
  12844. }
  12845. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12846. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12847. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12848. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12849. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12850. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12851. "vFogInfos", "vFogColor", "pointSize",
  12852. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12853. "mBones",
  12854. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12855. "darkness0", "darkness1", "darkness2", "darkness3",
  12856. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12857. ], [
  12858. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12859. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12860. ], join, fallbacks, this.onCompiled, this.onError);
  12861. }
  12862. if (!this._effect.isReady()) {
  12863. return false;
  12864. }
  12865. this._renderId = scene.getRenderId();
  12866. this._wasPreviouslyReady = true;
  12867. return true;
  12868. };
  12869. StandardMaterial.prototype.unbind = function () {
  12870. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12871. this._effect.setTexture("reflection2DSampler", null);
  12872. }
  12873. };
  12874. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12875. this._effect.setMatrix("world", world);
  12876. };
  12877. StandardMaterial.prototype.bind = function (world, mesh) {
  12878. var scene = this.getScene();
  12879. // Matrices
  12880. this.bindOnlyWorldMatrix(world);
  12881. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12882. // Bones
  12883. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12884. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12885. }
  12886. if (scene.getCachedMaterial() !== this) {
  12887. if (StandardMaterial.FresnelEnabled) {
  12888. // Fresnel
  12889. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12890. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12891. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12892. }
  12893. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12894. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12895. }
  12896. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12897. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12898. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12899. }
  12900. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12901. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12902. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12903. }
  12904. }
  12905. // Textures
  12906. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12907. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12908. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12909. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12910. }
  12911. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12912. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12913. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12914. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12915. }
  12916. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12917. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12918. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12919. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12920. }
  12921. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12922. if (this.reflectionTexture.isCube) {
  12923. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12924. } else {
  12925. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12926. }
  12927. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12928. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12929. }
  12930. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12931. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12932. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12933. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12934. }
  12935. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12936. this._effect.setTexture("specularSampler", this.specularTexture);
  12937. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12938. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12939. }
  12940. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12941. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12942. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12943. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12944. }
  12945. // Clip plane
  12946. if (scene.clipPlane) {
  12947. var clipPlane = scene.clipPlane;
  12948. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12949. }
  12950. // Point size
  12951. if (this.pointsCloud) {
  12952. this._effect.setFloat("pointSize", this.pointSize);
  12953. }
  12954. // Colors
  12955. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12956. // Scaling down color according to emissive
  12957. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12958. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12959. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12960. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12961. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12962. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12963. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12964. }
  12965. // Scaling down color according to emissive
  12966. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12967. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12968. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12969. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12970. if (scene.lightsEnabled) {
  12971. var lightIndex = 0;
  12972. for (var index = 0; index < scene.lights.length; index++) {
  12973. var light = scene.lights[index];
  12974. if (!light.isEnabled()) {
  12975. continue;
  12976. }
  12977. if (!light.canAffectMesh(mesh)) {
  12978. continue;
  12979. }
  12980. if (light instanceof BABYLON.PointLight) {
  12981. // Point Light
  12982. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12983. } else if (light instanceof BABYLON.DirectionalLight) {
  12984. // Directional Light
  12985. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12986. } else if (light instanceof BABYLON.SpotLight) {
  12987. // Spot Light
  12988. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12989. } else if (light instanceof BABYLON.HemisphericLight) {
  12990. // Hemispheric Light
  12991. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12992. }
  12993. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12994. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12995. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12996. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12997. // Shadows
  12998. if (scene.shadowsEnabled) {
  12999. var shadowGenerator = light.getShadowGenerator();
  13000. if (mesh.receiveShadows && shadowGenerator) {
  13001. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13002. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13003. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13004. }
  13005. }
  13006. lightIndex++;
  13007. if (lightIndex === maxSimultaneousLights)
  13008. break;
  13009. }
  13010. }
  13011. // View
  13012. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13013. this._effect.setMatrix("view", scene.getViewMatrix());
  13014. }
  13015. // Fog
  13016. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13017. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13018. this._effect.setColor3("vFogColor", scene.fogColor);
  13019. }
  13020. _super.prototype.bind.call(this, world, mesh);
  13021. };
  13022. StandardMaterial.prototype.getAnimatables = function () {
  13023. var results = [];
  13024. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13025. results.push(this.diffuseTexture);
  13026. }
  13027. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13028. results.push(this.ambientTexture);
  13029. }
  13030. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13031. results.push(this.opacityTexture);
  13032. }
  13033. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13034. results.push(this.reflectionTexture);
  13035. }
  13036. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13037. results.push(this.emissiveTexture);
  13038. }
  13039. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13040. results.push(this.specularTexture);
  13041. }
  13042. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13043. results.push(this.bumpTexture);
  13044. }
  13045. return results;
  13046. };
  13047. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13048. if (this.diffuseTexture) {
  13049. this.diffuseTexture.dispose();
  13050. }
  13051. if (this.ambientTexture) {
  13052. this.ambientTexture.dispose();
  13053. }
  13054. if (this.opacityTexture) {
  13055. this.opacityTexture.dispose();
  13056. }
  13057. if (this.reflectionTexture) {
  13058. this.reflectionTexture.dispose();
  13059. }
  13060. if (this.emissiveTexture) {
  13061. this.emissiveTexture.dispose();
  13062. }
  13063. if (this.specularTexture) {
  13064. this.specularTexture.dispose();
  13065. }
  13066. if (this.bumpTexture) {
  13067. this.bumpTexture.dispose();
  13068. }
  13069. _super.prototype.dispose.call(this, forceDisposeEffect);
  13070. };
  13071. StandardMaterial.prototype.clone = function (name) {
  13072. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13073. // Base material
  13074. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13075. newStandardMaterial.alpha = this.alpha;
  13076. newStandardMaterial.fillMode = this.fillMode;
  13077. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13078. // Standard material
  13079. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13080. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13081. }
  13082. if (this.ambientTexture && this.ambientTexture.clone) {
  13083. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13084. }
  13085. if (this.opacityTexture && this.opacityTexture.clone) {
  13086. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13087. }
  13088. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13089. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13090. }
  13091. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13092. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13093. }
  13094. if (this.specularTexture && this.specularTexture.clone) {
  13095. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13096. }
  13097. if (this.bumpTexture && this.bumpTexture.clone) {
  13098. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13099. }
  13100. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13101. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13102. newStandardMaterial.specularColor = this.specularColor.clone();
  13103. newStandardMaterial.specularPower = this.specularPower;
  13104. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13105. return newStandardMaterial;
  13106. };
  13107. StandardMaterial.DiffuseTextureEnabled = true;
  13108. StandardMaterial.AmbientTextureEnabled = true;
  13109. StandardMaterial.OpacityTextureEnabled = true;
  13110. StandardMaterial.ReflectionTextureEnabled = true;
  13111. StandardMaterial.EmissiveTextureEnabled = true;
  13112. StandardMaterial.SpecularTextureEnabled = true;
  13113. StandardMaterial.BumpTextureEnabled = true;
  13114. StandardMaterial.FresnelEnabled = true;
  13115. return StandardMaterial;
  13116. })(BABYLON.Material);
  13117. BABYLON.StandardMaterial = StandardMaterial;
  13118. })(BABYLON || (BABYLON = {}));
  13119. //# sourceMappingURL=babylon.standardMaterial.js.map
  13120. var BABYLON;
  13121. (function (BABYLON) {
  13122. var MultiMaterial = (function (_super) {
  13123. __extends(MultiMaterial, _super);
  13124. function MultiMaterial(name, scene) {
  13125. _super.call(this, name, scene, true);
  13126. this.subMaterials = new Array();
  13127. scene.multiMaterials.push(this);
  13128. }
  13129. // Properties
  13130. MultiMaterial.prototype.getSubMaterial = function (index) {
  13131. if (index < 0 || index >= this.subMaterials.length) {
  13132. return this.getScene().defaultMaterial;
  13133. }
  13134. return this.subMaterials[index];
  13135. };
  13136. // Methods
  13137. MultiMaterial.prototype.isReady = function (mesh) {
  13138. for (var index = 0; index < this.subMaterials.length; index++) {
  13139. var subMaterial = this.subMaterials[index];
  13140. if (subMaterial) {
  13141. if (!this.subMaterials[index].isReady(mesh)) {
  13142. return false;
  13143. }
  13144. }
  13145. }
  13146. return true;
  13147. };
  13148. return MultiMaterial;
  13149. })(BABYLON.Material);
  13150. BABYLON.MultiMaterial = MultiMaterial;
  13151. })(BABYLON || (BABYLON = {}));
  13152. //# sourceMappingURL=babylon.multiMaterial.js.map
  13153. var BABYLON;
  13154. (function (BABYLON) {
  13155. var Database = (function () {
  13156. function Database(urlToScene, callbackManifestChecked) {
  13157. // Handling various flavors of prefixed version of IndexedDB
  13158. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13159. this.callbackManifestChecked = callbackManifestChecked;
  13160. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13161. this.db = null;
  13162. this.enableSceneOffline = false;
  13163. this.enableTexturesOffline = false;
  13164. this.manifestVersionFound = 0;
  13165. this.mustUpdateRessources = false;
  13166. this.hasReachedQuota = false;
  13167. this.checkManifestFile();
  13168. }
  13169. Database.prototype.checkManifestFile = function () {
  13170. var _this = this;
  13171. function noManifestFile() {
  13172. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13173. that.enableSceneOffline = false;
  13174. that.enableTexturesOffline = false;
  13175. that.callbackManifestChecked(false);
  13176. }
  13177. var that = this;
  13178. var manifestURL = this.currentSceneUrl + ".manifest";
  13179. var xhr = new XMLHttpRequest();
  13180. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13181. xhr.open("GET", manifestURLTimeStamped, true);
  13182. xhr.addEventListener("load", function () {
  13183. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13184. try {
  13185. var manifestFile = JSON.parse(xhr.response);
  13186. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13187. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13188. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13189. _this.manifestVersionFound = manifestFile.version;
  13190. }
  13191. if (_this.callbackManifestChecked) {
  13192. _this.callbackManifestChecked(true);
  13193. }
  13194. } catch (ex) {
  13195. noManifestFile();
  13196. }
  13197. } else {
  13198. noManifestFile();
  13199. }
  13200. }, false);
  13201. xhr.addEventListener("error", function (event) {
  13202. noManifestFile();
  13203. }, false);
  13204. try {
  13205. xhr.send();
  13206. } catch (ex) {
  13207. BABYLON.Tools.Error("Error on XHR send request.");
  13208. that.callbackManifestChecked(false);
  13209. }
  13210. };
  13211. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13212. var _this = this;
  13213. function handleError() {
  13214. that.isSupported = false;
  13215. if (errorCallback)
  13216. errorCallback();
  13217. }
  13218. var that = this;
  13219. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13220. // Your browser doesn't support IndexedDB
  13221. this.isSupported = false;
  13222. if (errorCallback)
  13223. errorCallback();
  13224. } else {
  13225. // If the DB hasn't been opened or created yet
  13226. if (!this.db) {
  13227. this.hasReachedQuota = false;
  13228. this.isSupported = true;
  13229. var request = this.idbFactory.open("babylonjs", 1);
  13230. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13231. request.onerror = function (event) {
  13232. handleError();
  13233. };
  13234. // executes when a version change transaction cannot complete due to other active transactions
  13235. request.onblocked = function (event) {
  13236. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13237. handleError();
  13238. };
  13239. // DB has been opened successfully
  13240. request.onsuccess = function (event) {
  13241. _this.db = request.result;
  13242. successCallback();
  13243. };
  13244. // Initialization of the DB. Creating Scenes & Textures stores
  13245. request.onupgradeneeded = function (event) {
  13246. _this.db = (event.target).result;
  13247. try {
  13248. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13249. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13250. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13251. } catch (ex) {
  13252. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13253. handleError();
  13254. }
  13255. };
  13256. } else {
  13257. if (successCallback)
  13258. successCallback();
  13259. }
  13260. }
  13261. };
  13262. Database.prototype.loadImageFromDB = function (url, image) {
  13263. var _this = this;
  13264. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13265. var saveAndLoadImage = function () {
  13266. if (!_this.hasReachedQuota && _this.db !== null) {
  13267. // the texture is not yet in the DB, let's try to save it
  13268. _this._saveImageIntoDBAsync(completeURL, image);
  13269. } else {
  13270. image.src = url;
  13271. }
  13272. };
  13273. if (!this.mustUpdateRessources) {
  13274. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13275. } else {
  13276. saveAndLoadImage();
  13277. }
  13278. };
  13279. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13280. if (this.isSupported && this.db !== null) {
  13281. var texture;
  13282. var transaction = this.db.transaction(["textures"]);
  13283. transaction.onabort = function (event) {
  13284. image.src = url;
  13285. };
  13286. transaction.oncomplete = function (event) {
  13287. var blobTextureURL;
  13288. if (texture) {
  13289. var URL = window.URL || window.webkitURL;
  13290. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13291. image.onerror = function () {
  13292. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13293. image.src = url;
  13294. };
  13295. image.src = blobTextureURL;
  13296. } else {
  13297. notInDBCallback();
  13298. }
  13299. };
  13300. var getRequest = transaction.objectStore("textures").get(url);
  13301. getRequest.onsuccess = function (event) {
  13302. texture = (event.target).result;
  13303. };
  13304. getRequest.onerror = function (event) {
  13305. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13306. image.src = url;
  13307. };
  13308. } else {
  13309. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13310. image.src = url;
  13311. }
  13312. };
  13313. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13314. var _this = this;
  13315. if (this.isSupported) {
  13316. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13317. var generateBlobUrl = function () {
  13318. var blobTextureURL;
  13319. if (blob) {
  13320. var URL = window.URL || window.webkitURL;
  13321. try {
  13322. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13323. } catch (ex) {
  13324. blobTextureURL = URL.createObjectURL(blob);
  13325. }
  13326. }
  13327. image.src = blobTextureURL;
  13328. };
  13329. if (BABYLON.Database.isUASupportingBlobStorage) {
  13330. var xhr = new XMLHttpRequest(), blob;
  13331. xhr.open("GET", url, true);
  13332. xhr.responseType = "blob";
  13333. xhr.addEventListener("load", function () {
  13334. if (xhr.status === 200) {
  13335. // Blob as response (XHR2)
  13336. blob = xhr.response;
  13337. var transaction = _this.db.transaction(["textures"], "readwrite");
  13338. // the transaction could abort because of a QuotaExceededError error
  13339. transaction.onabort = function (event) {
  13340. try {
  13341. if (event.srcElement.error.name === "QuotaExceededError") {
  13342. this.hasReachedQuota = true;
  13343. }
  13344. } catch (ex) {
  13345. }
  13346. generateBlobUrl();
  13347. };
  13348. transaction.oncomplete = function (event) {
  13349. generateBlobUrl();
  13350. };
  13351. var newTexture = { textureUrl: url, data: blob };
  13352. try {
  13353. // Put the blob into the dabase
  13354. var addRequest = transaction.objectStore("textures").put(newTexture);
  13355. addRequest.onsuccess = function (event) {
  13356. };
  13357. addRequest.onerror = function (event) {
  13358. generateBlobUrl();
  13359. };
  13360. } catch (ex) {
  13361. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13362. if (ex.code === 25) {
  13363. BABYLON.Database.isUASupportingBlobStorage = false;
  13364. }
  13365. image.src = url;
  13366. }
  13367. } else {
  13368. image.src = url;
  13369. }
  13370. }, false);
  13371. xhr.addEventListener("error", function (event) {
  13372. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13373. image.src = url;
  13374. }, false);
  13375. xhr.send();
  13376. } else {
  13377. image.src = url;
  13378. }
  13379. } else {
  13380. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13381. image.src = url;
  13382. }
  13383. };
  13384. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13385. var _this = this;
  13386. var updateVersion = function (event) {
  13387. // the version is not yet in the DB or we need to update it
  13388. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13389. };
  13390. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13391. };
  13392. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13393. var _this = this;
  13394. if (this.isSupported) {
  13395. var version;
  13396. try {
  13397. var transaction = this.db.transaction(["versions"]);
  13398. transaction.oncomplete = function (event) {
  13399. if (version) {
  13400. // If the version in the JSON file is > than the version in DB
  13401. if (_this.manifestVersionFound > version.data) {
  13402. _this.mustUpdateRessources = true;
  13403. updateInDBCallback();
  13404. } else {
  13405. callback(version.data);
  13406. }
  13407. } else {
  13408. _this.mustUpdateRessources = true;
  13409. updateInDBCallback();
  13410. }
  13411. };
  13412. transaction.onabort = function (event) {
  13413. callback(-1);
  13414. };
  13415. var getRequest = transaction.objectStore("versions").get(url);
  13416. getRequest.onsuccess = function (event) {
  13417. version = (event.target).result;
  13418. };
  13419. getRequest.onerror = function (event) {
  13420. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13421. callback(-1);
  13422. };
  13423. } catch (ex) {
  13424. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13425. callback(-1);
  13426. }
  13427. } else {
  13428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13429. callback(-1);
  13430. }
  13431. };
  13432. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13433. var _this = this;
  13434. if (this.isSupported && !this.hasReachedQuota) {
  13435. try {
  13436. // Open a transaction to the database
  13437. var transaction = this.db.transaction(["versions"], "readwrite");
  13438. // the transaction could abort because of a QuotaExceededError error
  13439. transaction.onabort = function (event) {
  13440. try {
  13441. if (event.srcElement.error.name === "QuotaExceededError") {
  13442. _this.hasReachedQuota = true;
  13443. }
  13444. } catch (ex) {
  13445. }
  13446. callback(-1);
  13447. };
  13448. transaction.oncomplete = function (event) {
  13449. callback(_this.manifestVersionFound);
  13450. };
  13451. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13452. // Put the scene into the database
  13453. var addRequest = transaction.objectStore("versions").put(newVersion);
  13454. addRequest.onsuccess = function (event) {
  13455. };
  13456. addRequest.onerror = function (event) {
  13457. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13458. };
  13459. } catch (ex) {
  13460. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13461. callback(-1);
  13462. }
  13463. } else {
  13464. callback(-1);
  13465. }
  13466. };
  13467. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13468. var _this = this;
  13469. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13470. var saveAndLoadFile = function (event) {
  13471. // the scene is not yet in the DB, let's try to save it
  13472. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13473. };
  13474. this._checkVersionFromDB(completeUrl, function (version) {
  13475. if (version !== -1) {
  13476. if (!_this.mustUpdateRessources) {
  13477. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13478. } else {
  13479. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13480. }
  13481. } else {
  13482. errorCallback();
  13483. }
  13484. });
  13485. };
  13486. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13487. if (this.isSupported) {
  13488. var targetStore;
  13489. if (url.indexOf(".babylon") !== -1) {
  13490. targetStore = "scenes";
  13491. } else {
  13492. targetStore = "textures";
  13493. }
  13494. var file;
  13495. var transaction = this.db.transaction([targetStore]);
  13496. transaction.oncomplete = function (event) {
  13497. if (file) {
  13498. callback(file.data);
  13499. } else {
  13500. notInDBCallback();
  13501. }
  13502. };
  13503. transaction.onabort = function (event) {
  13504. notInDBCallback();
  13505. };
  13506. var getRequest = transaction.objectStore(targetStore).get(url);
  13507. getRequest.onsuccess = function (event) {
  13508. file = (event.target).result;
  13509. };
  13510. getRequest.onerror = function (event) {
  13511. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13512. notInDBCallback();
  13513. };
  13514. } else {
  13515. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13516. callback();
  13517. }
  13518. };
  13519. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13520. var _this = this;
  13521. if (this.isSupported) {
  13522. var targetStore;
  13523. if (url.indexOf(".babylon") !== -1) {
  13524. targetStore = "scenes";
  13525. } else {
  13526. targetStore = "textures";
  13527. }
  13528. // Create XHR
  13529. var xhr = new XMLHttpRequest(), fileData;
  13530. xhr.open("GET", url, true);
  13531. if (useArrayBuffer) {
  13532. xhr.responseType = "arraybuffer";
  13533. }
  13534. xhr.onprogress = progressCallback;
  13535. xhr.addEventListener("load", function () {
  13536. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13537. // Blob as response (XHR2)
  13538. //fileData = xhr.responseText;
  13539. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13540. if (!_this.hasReachedQuota) {
  13541. // Open a transaction to the database
  13542. var transaction = _this.db.transaction([targetStore], "readwrite");
  13543. // the transaction could abort because of a QuotaExceededError error
  13544. transaction.onabort = function (event) {
  13545. try {
  13546. if (event.srcElement.error.name === "QuotaExceededError") {
  13547. this.hasReachedQuota = true;
  13548. }
  13549. } catch (ex) {
  13550. }
  13551. callback(fileData);
  13552. };
  13553. transaction.oncomplete = function (event) {
  13554. callback(fileData);
  13555. };
  13556. var newFile;
  13557. if (targetStore === "scenes") {
  13558. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13559. } else {
  13560. newFile = { textureUrl: url, data: fileData };
  13561. }
  13562. try {
  13563. // Put the scene into the database
  13564. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13565. addRequest.onsuccess = function (event) {
  13566. };
  13567. addRequest.onerror = function (event) {
  13568. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13569. };
  13570. } catch (ex) {
  13571. callback(fileData);
  13572. }
  13573. } else {
  13574. callback(fileData);
  13575. }
  13576. } else {
  13577. callback();
  13578. }
  13579. }, false);
  13580. xhr.addEventListener("error", function (event) {
  13581. BABYLON.Tools.Error("error on XHR request.");
  13582. callback();
  13583. }, false);
  13584. xhr.send();
  13585. } else {
  13586. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13587. callback();
  13588. }
  13589. };
  13590. Database.isUASupportingBlobStorage = true;
  13591. Database.parseURL = function (url) {
  13592. var a = document.createElement('a');
  13593. a.href = url;
  13594. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13595. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13596. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13597. return absLocation;
  13598. };
  13599. Database.ReturnFullUrlLocation = function (url) {
  13600. if (url.indexOf("http:/") === -1) {
  13601. return (BABYLON.Database.parseURL(window.location.href) + url);
  13602. } else {
  13603. return url;
  13604. }
  13605. };
  13606. return Database;
  13607. })();
  13608. BABYLON.Database = Database;
  13609. })(BABYLON || (BABYLON = {}));
  13610. //# sourceMappingURL=babylon.database.js.map
  13611. var BABYLON;
  13612. (function (BABYLON) {
  13613. var SpriteManager = (function () {
  13614. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13615. this.name = name;
  13616. this.cellSize = cellSize;
  13617. this.sprites = new Array();
  13618. this.renderingGroupId = 0;
  13619. this.fogEnabled = true;
  13620. this._vertexDeclaration = [3, 4, 4, 4];
  13621. this._vertexStrideSize = 15 * 4;
  13622. this._capacity = capacity;
  13623. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13624. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13625. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13626. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13627. this._scene = scene;
  13628. this._scene.spriteManagers.push(this);
  13629. // VBO
  13630. this._vertexDeclaration = [3, 4, 4, 4];
  13631. this._vertexStrideSize = 15 * 4;
  13632. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13633. var indices = [];
  13634. var index = 0;
  13635. for (var count = 0; count < capacity; count++) {
  13636. indices.push(index);
  13637. indices.push(index + 1);
  13638. indices.push(index + 2);
  13639. indices.push(index);
  13640. indices.push(index + 2);
  13641. indices.push(index + 3);
  13642. index += 4;
  13643. }
  13644. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13645. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13646. // Effects
  13647. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13648. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13649. }
  13650. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13651. var arrayOffset = index * 15;
  13652. if (offsetX == 0)
  13653. offsetX = this._epsilon;
  13654. else if (offsetX == 1)
  13655. offsetX = 1 - this._epsilon;
  13656. if (offsetY == 0)
  13657. offsetY = this._epsilon;
  13658. else if (offsetY == 1)
  13659. offsetY = 1 - this._epsilon;
  13660. this._vertices[arrayOffset] = sprite.position.x;
  13661. this._vertices[arrayOffset + 1] = sprite.position.y;
  13662. this._vertices[arrayOffset + 2] = sprite.position.z;
  13663. this._vertices[arrayOffset + 3] = sprite.angle;
  13664. this._vertices[arrayOffset + 4] = sprite.size;
  13665. this._vertices[arrayOffset + 5] = offsetX;
  13666. this._vertices[arrayOffset + 6] = offsetY;
  13667. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13668. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13669. var offset = (sprite.cellIndex / rowSize) >> 0;
  13670. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13671. this._vertices[arrayOffset + 10] = offset;
  13672. // Color
  13673. this._vertices[arrayOffset + 11] = sprite.color.r;
  13674. this._vertices[arrayOffset + 12] = sprite.color.g;
  13675. this._vertices[arrayOffset + 13] = sprite.color.b;
  13676. this._vertices[arrayOffset + 14] = sprite.color.a;
  13677. };
  13678. SpriteManager.prototype.render = function () {
  13679. // Check
  13680. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13681. return;
  13682. var engine = this._scene.getEngine();
  13683. var baseSize = this._spriteTexture.getBaseSize();
  13684. // Sprites
  13685. var deltaTime = engine.getDeltaTime();
  13686. var max = Math.min(this._capacity, this.sprites.length);
  13687. var rowSize = baseSize.width / this.cellSize;
  13688. var offset = 0;
  13689. for (var index = 0; index < max; index++) {
  13690. var sprite = this.sprites[index];
  13691. if (!sprite) {
  13692. continue;
  13693. }
  13694. sprite._animate(deltaTime);
  13695. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13696. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13697. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13698. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13699. }
  13700. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13701. // Render
  13702. var effect = this._effectBase;
  13703. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13704. effect = this._effectFog;
  13705. }
  13706. engine.enableEffect(effect);
  13707. var viewMatrix = this._scene.getViewMatrix();
  13708. effect.setTexture("diffuseSampler", this._spriteTexture);
  13709. effect.setMatrix("view", viewMatrix);
  13710. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13711. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13712. // Fog
  13713. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13714. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13715. effect.setColor3("vFogColor", this._scene.fogColor);
  13716. }
  13717. // VBOs
  13718. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13719. // Draw order
  13720. effect.setBool("alphaTest", true);
  13721. engine.setColorWrite(false);
  13722. engine.draw(true, 0, max * 6);
  13723. engine.setColorWrite(true);
  13724. effect.setBool("alphaTest", false);
  13725. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13726. engine.draw(true, 0, max * 6);
  13727. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13728. };
  13729. SpriteManager.prototype.dispose = function () {
  13730. if (this._vertexBuffer) {
  13731. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13732. this._vertexBuffer = null;
  13733. }
  13734. if (this._indexBuffer) {
  13735. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13736. this._indexBuffer = null;
  13737. }
  13738. if (this._spriteTexture) {
  13739. this._spriteTexture.dispose();
  13740. this._spriteTexture = null;
  13741. }
  13742. // Remove from scene
  13743. var index = this._scene.spriteManagers.indexOf(this);
  13744. this._scene.spriteManagers.splice(index, 1);
  13745. // Callback
  13746. if (this.onDispose) {
  13747. this.onDispose();
  13748. }
  13749. };
  13750. return SpriteManager;
  13751. })();
  13752. BABYLON.SpriteManager = SpriteManager;
  13753. })(BABYLON || (BABYLON = {}));
  13754. //# sourceMappingURL=babylon.spriteManager.js.map
  13755. var BABYLON;
  13756. (function (BABYLON) {
  13757. var Sprite = (function () {
  13758. function Sprite(name, manager) {
  13759. this.name = name;
  13760. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13761. this.size = 1.0;
  13762. this.angle = 0;
  13763. this.cellIndex = 0;
  13764. this.invertU = 0;
  13765. this.invertV = 0;
  13766. this.animations = new Array();
  13767. this._animationStarted = false;
  13768. this._loopAnimation = false;
  13769. this._fromIndex = 0;
  13770. this._toIndex = 0;
  13771. this._delay = 0;
  13772. this._direction = 1;
  13773. this._frameCount = 0;
  13774. this._time = 0;
  13775. this._manager = manager;
  13776. this._manager.sprites.push(this);
  13777. this.position = BABYLON.Vector3.Zero();
  13778. }
  13779. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13780. this._fromIndex = from;
  13781. this._toIndex = to;
  13782. this._loopAnimation = loop;
  13783. this._delay = delay;
  13784. this._animationStarted = true;
  13785. this._direction = from < to ? 1 : -1;
  13786. this.cellIndex = from;
  13787. this._time = 0;
  13788. };
  13789. Sprite.prototype.stopAnimation = function () {
  13790. this._animationStarted = false;
  13791. };
  13792. Sprite.prototype._animate = function (deltaTime) {
  13793. if (!this._animationStarted)
  13794. return;
  13795. this._time += deltaTime;
  13796. if (this._time > this._delay) {
  13797. this._time = this._time % this._delay;
  13798. this.cellIndex += this._direction;
  13799. if (this.cellIndex == this._toIndex) {
  13800. if (this._loopAnimation) {
  13801. this.cellIndex = this._fromIndex;
  13802. } else {
  13803. this._animationStarted = false;
  13804. if (this.disposeWhenFinishedAnimating) {
  13805. this.dispose();
  13806. }
  13807. }
  13808. }
  13809. }
  13810. };
  13811. Sprite.prototype.dispose = function () {
  13812. for (var i = 0; i < this._manager.sprites.length; i++) {
  13813. if (this._manager.sprites[i] == this) {
  13814. this._manager.sprites.splice(i, 1);
  13815. }
  13816. }
  13817. };
  13818. return Sprite;
  13819. })();
  13820. BABYLON.Sprite = Sprite;
  13821. })(BABYLON || (BABYLON = {}));
  13822. //# sourceMappingURL=babylon.sprite.js.map
  13823. var BABYLON;
  13824. (function (BABYLON) {
  13825. var Layer = (function () {
  13826. function Layer(name, imgUrl, scene, isBackground, color) {
  13827. this.name = name;
  13828. this._vertexDeclaration = [2];
  13829. this._vertexStrideSize = 2 * 4;
  13830. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13831. this.isBackground = isBackground === undefined ? true : isBackground;
  13832. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13833. this._scene = scene;
  13834. this._scene.layers.push(this);
  13835. // VBO
  13836. var vertices = [];
  13837. vertices.push(1, 1);
  13838. vertices.push(-1, 1);
  13839. vertices.push(-1, -1);
  13840. vertices.push(1, -1);
  13841. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13842. // Indices
  13843. var indices = [];
  13844. indices.push(0);
  13845. indices.push(1);
  13846. indices.push(2);
  13847. indices.push(0);
  13848. indices.push(2);
  13849. indices.push(3);
  13850. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13851. // Effects
  13852. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13853. }
  13854. Layer.prototype.render = function () {
  13855. // Check
  13856. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13857. return;
  13858. var engine = this._scene.getEngine();
  13859. // Render
  13860. engine.enableEffect(this._effect);
  13861. engine.setState(false);
  13862. // Texture
  13863. this._effect.setTexture("textureSampler", this.texture);
  13864. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13865. // Color
  13866. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13867. // VBOs
  13868. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13869. // Draw order
  13870. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13871. engine.draw(true, 0, 6);
  13872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13873. };
  13874. Layer.prototype.dispose = function () {
  13875. if (this._vertexBuffer) {
  13876. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13877. this._vertexBuffer = null;
  13878. }
  13879. if (this._indexBuffer) {
  13880. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13881. this._indexBuffer = null;
  13882. }
  13883. if (this.texture) {
  13884. this.texture.dispose();
  13885. this.texture = null;
  13886. }
  13887. // Remove from scene
  13888. var index = this._scene.layers.indexOf(this);
  13889. this._scene.layers.splice(index, 1);
  13890. // Callback
  13891. if (this.onDispose) {
  13892. this.onDispose();
  13893. }
  13894. };
  13895. return Layer;
  13896. })();
  13897. BABYLON.Layer = Layer;
  13898. })(BABYLON || (BABYLON = {}));
  13899. //# sourceMappingURL=babylon.layer.js.map
  13900. var BABYLON;
  13901. (function (BABYLON) {
  13902. var Particle = (function () {
  13903. function Particle() {
  13904. this.position = BABYLON.Vector3.Zero();
  13905. this.direction = BABYLON.Vector3.Zero();
  13906. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13907. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13908. this.lifeTime = 1.0;
  13909. this.age = 0;
  13910. this.size = 0;
  13911. this.angle = 0;
  13912. this.angularSpeed = 0;
  13913. }
  13914. return Particle;
  13915. })();
  13916. BABYLON.Particle = Particle;
  13917. })(BABYLON || (BABYLON = {}));
  13918. //# sourceMappingURL=babylon.particle.js.map
  13919. var BABYLON;
  13920. (function (BABYLON) {
  13921. var randomNumber = function (min, max) {
  13922. if (min === max) {
  13923. return (min);
  13924. }
  13925. var random = Math.random();
  13926. return ((random * (max - min)) + min);
  13927. };
  13928. var ParticleSystem = (function () {
  13929. function ParticleSystem(name, capacity, scene, customEffect) {
  13930. var _this = this;
  13931. this.name = name;
  13932. this.renderingGroupId = 0;
  13933. this.emitter = null;
  13934. this.emitRate = 10;
  13935. this.manualEmitCount = -1;
  13936. this.updateSpeed = 0.01;
  13937. this.targetStopDuration = 0;
  13938. this.disposeOnStop = false;
  13939. this.minEmitPower = 1;
  13940. this.maxEmitPower = 1;
  13941. this.minLifeTime = 1;
  13942. this.maxLifeTime = 1;
  13943. this.minSize = 1;
  13944. this.maxSize = 1;
  13945. this.minAngularSpeed = 0;
  13946. this.maxAngularSpeed = 0;
  13947. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13948. this.forceDepthWrite = false;
  13949. this.gravity = BABYLON.Vector3.Zero();
  13950. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13951. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13952. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13953. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13954. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13955. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13956. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13957. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13958. this.particles = new Array();
  13959. this._vertexDeclaration = [3, 4, 4];
  13960. this._vertexStrideSize = 11 * 4;
  13961. this._stockParticles = new Array();
  13962. this._newPartsExcess = 0;
  13963. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13964. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13965. this._scaledDirection = BABYLON.Vector3.Zero();
  13966. this._scaledGravity = BABYLON.Vector3.Zero();
  13967. this._currentRenderId = -1;
  13968. this._started = false;
  13969. this._stopped = false;
  13970. this._actualFrame = 0;
  13971. this.id = name;
  13972. this._capacity = capacity;
  13973. this._scene = scene;
  13974. this._customEffect = customEffect;
  13975. scene.particleSystems.push(this);
  13976. // VBO
  13977. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13978. var indices = [];
  13979. var index = 0;
  13980. for (var count = 0; count < capacity; count++) {
  13981. indices.push(index);
  13982. indices.push(index + 1);
  13983. indices.push(index + 2);
  13984. indices.push(index);
  13985. indices.push(index + 2);
  13986. indices.push(index + 3);
  13987. index += 4;
  13988. }
  13989. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13990. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13991. // Default behaviors
  13992. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13993. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13994. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13995. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13996. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13997. };
  13998. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13999. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14000. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14001. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14003. };
  14004. this.updateFunction = function (particles) {
  14005. for (var index = 0; index < particles.length; index++) {
  14006. var particle = particles[index];
  14007. particle.age += _this._scaledUpdateSpeed;
  14008. if (particle.age >= particle.lifeTime) {
  14009. particles.splice(index, 1);
  14010. _this._stockParticles.push(particle);
  14011. index--;
  14012. continue;
  14013. } else {
  14014. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14015. particle.color.addInPlace(_this._scaledColorStep);
  14016. if (particle.color.a < 0)
  14017. particle.color.a = 0;
  14018. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14019. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14020. particle.position.addInPlace(_this._scaledDirection);
  14021. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14022. particle.direction.addInPlace(_this._scaledGravity);
  14023. }
  14024. }
  14025. };
  14026. }
  14027. ParticleSystem.prototype.getCapacity = function () {
  14028. return this._capacity;
  14029. };
  14030. ParticleSystem.prototype.isAlive = function () {
  14031. return this._alive;
  14032. };
  14033. ParticleSystem.prototype.isStarted = function () {
  14034. return this._started;
  14035. };
  14036. ParticleSystem.prototype.start = function () {
  14037. this._started = true;
  14038. this._stopped = false;
  14039. this._actualFrame = 0;
  14040. };
  14041. ParticleSystem.prototype.stop = function () {
  14042. this._stopped = true;
  14043. };
  14044. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14045. var offset = index * 11;
  14046. this._vertices[offset] = particle.position.x;
  14047. this._vertices[offset + 1] = particle.position.y;
  14048. this._vertices[offset + 2] = particle.position.z;
  14049. this._vertices[offset + 3] = particle.color.r;
  14050. this._vertices[offset + 4] = particle.color.g;
  14051. this._vertices[offset + 5] = particle.color.b;
  14052. this._vertices[offset + 6] = particle.color.a;
  14053. this._vertices[offset + 7] = particle.angle;
  14054. this._vertices[offset + 8] = particle.size;
  14055. this._vertices[offset + 9] = offsetX;
  14056. this._vertices[offset + 10] = offsetY;
  14057. };
  14058. ParticleSystem.prototype._update = function (newParticles) {
  14059. // Update current
  14060. this._alive = this.particles.length > 0;
  14061. this.updateFunction(this.particles);
  14062. // Add new ones
  14063. var worldMatrix;
  14064. if (this.emitter.position) {
  14065. worldMatrix = this.emitter.getWorldMatrix();
  14066. } else {
  14067. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14068. }
  14069. for (var index = 0; index < newParticles; index++) {
  14070. if (this.particles.length === this._capacity) {
  14071. break;
  14072. }
  14073. if (this._stockParticles.length !== 0) {
  14074. var particle = this._stockParticles.pop();
  14075. particle.age = 0;
  14076. } else {
  14077. particle = new BABYLON.Particle();
  14078. }
  14079. this.particles.push(particle);
  14080. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14081. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14082. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14083. particle.size = randomNumber(this.minSize, this.maxSize);
  14084. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14085. this.startPositionFunction(worldMatrix, particle.position);
  14086. var step = randomNumber(0, 1.0);
  14087. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14088. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14089. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14090. }
  14091. };
  14092. ParticleSystem.prototype._getEffect = function () {
  14093. if (this._customEffect) {
  14094. return this._customEffect;
  14095. }
  14096. ;
  14097. var defines = [];
  14098. if (this._scene.clipPlane) {
  14099. defines.push("#define CLIPPLANE");
  14100. }
  14101. // Effect
  14102. var join = defines.join("\n");
  14103. if (this._cachedDefines !== join) {
  14104. this._cachedDefines = join;
  14105. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14106. }
  14107. return this._effect;
  14108. };
  14109. ParticleSystem.prototype.animate = function () {
  14110. if (!this._started)
  14111. return;
  14112. var effect = this._getEffect();
  14113. // Check
  14114. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14115. return;
  14116. if (this._currentRenderId === this._scene.getRenderId()) {
  14117. return;
  14118. }
  14119. this._currentRenderId = this._scene.getRenderId();
  14120. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14121. // determine the number of particles we need to create
  14122. var emitCout;
  14123. if (this.manualEmitCount > -1) {
  14124. emitCout = this.manualEmitCount;
  14125. this.manualEmitCount = 0;
  14126. } else {
  14127. emitCout = this.emitRate;
  14128. }
  14129. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14130. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14131. if (this._newPartsExcess > 1.0) {
  14132. newParticles += this._newPartsExcess >> 0;
  14133. this._newPartsExcess -= this._newPartsExcess >> 0;
  14134. }
  14135. this._alive = false;
  14136. if (!this._stopped) {
  14137. this._actualFrame += this._scaledUpdateSpeed;
  14138. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14139. this.stop();
  14140. } else {
  14141. newParticles = 0;
  14142. }
  14143. this._update(newParticles);
  14144. // Stopped?
  14145. if (this._stopped) {
  14146. if (!this._alive) {
  14147. this._started = false;
  14148. if (this.disposeOnStop) {
  14149. this._scene._toBeDisposed.push(this);
  14150. }
  14151. }
  14152. }
  14153. // Update VBO
  14154. var offset = 0;
  14155. for (var index = 0; index < this.particles.length; index++) {
  14156. var particle = this.particles[index];
  14157. this._appendParticleVertex(offset++, particle, 0, 0);
  14158. this._appendParticleVertex(offset++, particle, 1, 0);
  14159. this._appendParticleVertex(offset++, particle, 1, 1);
  14160. this._appendParticleVertex(offset++, particle, 0, 1);
  14161. }
  14162. var engine = this._scene.getEngine();
  14163. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14164. };
  14165. ParticleSystem.prototype.render = function () {
  14166. var effect = this._getEffect();
  14167. // Check
  14168. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14169. return 0;
  14170. var engine = this._scene.getEngine();
  14171. // Render
  14172. engine.enableEffect(effect);
  14173. engine.setState(false);
  14174. var viewMatrix = this._scene.getViewMatrix();
  14175. effect.setTexture("diffuseSampler", this.particleTexture);
  14176. effect.setMatrix("view", viewMatrix);
  14177. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14178. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14179. if (this._scene.clipPlane) {
  14180. var clipPlane = this._scene.clipPlane;
  14181. var invView = viewMatrix.clone();
  14182. invView.invert();
  14183. effect.setMatrix("invView", invView);
  14184. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14185. }
  14186. // VBOs
  14187. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14188. // Draw order
  14189. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14190. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14191. } else {
  14192. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14193. }
  14194. if (this.forceDepthWrite) {
  14195. engine.setDepthWrite(true);
  14196. }
  14197. engine.draw(true, 0, this.particles.length * 6);
  14198. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14199. return this.particles.length;
  14200. };
  14201. ParticleSystem.prototype.dispose = function () {
  14202. if (this._vertexBuffer) {
  14203. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14204. this._vertexBuffer = null;
  14205. }
  14206. if (this._indexBuffer) {
  14207. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14208. this._indexBuffer = null;
  14209. }
  14210. if (this.particleTexture) {
  14211. this.particleTexture.dispose();
  14212. this.particleTexture = null;
  14213. }
  14214. // Remove from scene
  14215. var index = this._scene.particleSystems.indexOf(this);
  14216. this._scene.particleSystems.splice(index, 1);
  14217. // Callback
  14218. if (this.onDispose) {
  14219. this.onDispose();
  14220. }
  14221. };
  14222. // Clone
  14223. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14224. var result = new ParticleSystem(name, this._capacity, this._scene);
  14225. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14226. if (newEmitter === undefined) {
  14227. newEmitter = this.emitter;
  14228. }
  14229. result.emitter = newEmitter;
  14230. if (this.particleTexture) {
  14231. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14232. }
  14233. result.start();
  14234. return result;
  14235. };
  14236. ParticleSystem.BLENDMODE_ONEONE = 0;
  14237. ParticleSystem.BLENDMODE_STANDARD = 1;
  14238. return ParticleSystem;
  14239. })();
  14240. BABYLON.ParticleSystem = ParticleSystem;
  14241. })(BABYLON || (BABYLON = {}));
  14242. //# sourceMappingURL=babylon.particleSystem.js.map
  14243. var BABYLON;
  14244. (function (BABYLON) {
  14245. var Animation = (function () {
  14246. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14247. this.name = name;
  14248. this.targetProperty = targetProperty;
  14249. this.framePerSecond = framePerSecond;
  14250. this.dataType = dataType;
  14251. this.loopMode = loopMode;
  14252. this._offsetsCache = {};
  14253. this._highLimitsCache = {};
  14254. this._stopped = false;
  14255. this.targetPropertyPath = targetProperty.split(".");
  14256. this.dataType = dataType;
  14257. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14258. }
  14259. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14260. var dataType = undefined;
  14261. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14262. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14263. } else if (from instanceof BABYLON.Quaternion) {
  14264. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14265. } else if (from instanceof BABYLON.Vector3) {
  14266. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14267. } else if (from instanceof BABYLON.Vector2) {
  14268. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14269. } else if (from instanceof BABYLON.Color3) {
  14270. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14271. }
  14272. if (dataType == undefined) {
  14273. return;
  14274. }
  14275. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14276. var keys = [];
  14277. keys.push({ frame: 0, value: from });
  14278. keys.push({ frame: totalFrame, value: to });
  14279. animation.setKeys(keys);
  14280. mesh.animations.push(animation);
  14281. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  14282. };
  14283. // Methods
  14284. Animation.prototype.isStopped = function () {
  14285. return this._stopped;
  14286. };
  14287. Animation.prototype.getKeys = function () {
  14288. return this._keys;
  14289. };
  14290. Animation.prototype.getEasingFunction = function () {
  14291. return this._easingFunction;
  14292. };
  14293. Animation.prototype.setEasingFunction = function (easingFunction) {
  14294. this._easingFunction = easingFunction;
  14295. };
  14296. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14297. return startValue + (endValue - startValue) * gradient;
  14298. };
  14299. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14300. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14301. };
  14302. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14303. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14304. };
  14305. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14306. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14307. };
  14308. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14309. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14310. };
  14311. Animation.prototype.clone = function () {
  14312. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14313. clone.setKeys(this._keys);
  14314. return clone;
  14315. };
  14316. Animation.prototype.setKeys = function (values) {
  14317. this._keys = values.slice(0);
  14318. this._offsetsCache = {};
  14319. this._highLimitsCache = {};
  14320. };
  14321. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14322. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14323. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14324. }
  14325. this.currentFrame = currentFrame;
  14326. for (var key = 0; key < this._keys.length; key++) {
  14327. // for each frame, we need the key just before the frame superior
  14328. if (this._keys[key + 1].frame >= currentFrame) {
  14329. var startValue = this._keys[key].value;
  14330. var endValue = this._keys[key + 1].value;
  14331. // gradient : percent of currentFrame between the frame inf and the frame sup
  14332. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14333. // check for easingFunction and correction of gradient
  14334. if (this._easingFunction != null) {
  14335. gradient = this._easingFunction.ease(gradient);
  14336. }
  14337. switch (this.dataType) {
  14338. case Animation.ANIMATIONTYPE_FLOAT:
  14339. switch (loopMode) {
  14340. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14341. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14342. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14343. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14344. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14345. }
  14346. break;
  14347. case Animation.ANIMATIONTYPE_QUATERNION:
  14348. var quaternion = null;
  14349. switch (loopMode) {
  14350. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14351. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14352. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14353. break;
  14354. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14355. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14356. break;
  14357. }
  14358. return quaternion;
  14359. case Animation.ANIMATIONTYPE_VECTOR3:
  14360. switch (loopMode) {
  14361. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14362. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14363. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14364. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14365. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14366. }
  14367. case Animation.ANIMATIONTYPE_VECTOR2:
  14368. switch (loopMode) {
  14369. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14370. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14371. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14372. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14373. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14374. }
  14375. case Animation.ANIMATIONTYPE_COLOR3:
  14376. switch (loopMode) {
  14377. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14378. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14379. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14380. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14381. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14382. }
  14383. case Animation.ANIMATIONTYPE_MATRIX:
  14384. switch (loopMode) {
  14385. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14386. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14387. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14388. return startValue;
  14389. }
  14390. default:
  14391. break;
  14392. }
  14393. break;
  14394. }
  14395. }
  14396. return this._keys[this._keys.length - 1].value;
  14397. };
  14398. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14399. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14400. this._stopped = true;
  14401. return false;
  14402. }
  14403. var returnValue = true;
  14404. // Adding a start key at frame 0 if missing
  14405. if (this._keys[0].frame != 0) {
  14406. var newKey = { frame: 0, value: this._keys[0].value };
  14407. this._keys.splice(0, 0, newKey);
  14408. }
  14409. // Check limits
  14410. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14411. from = this._keys[0].frame;
  14412. }
  14413. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14414. to = this._keys[this._keys.length - 1].frame;
  14415. }
  14416. // Compute ratio
  14417. var range = to - from;
  14418. var offsetValue;
  14419. // ratio represents the frame delta between from and to
  14420. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14421. if (ratio > range && !loop) {
  14422. returnValue = false;
  14423. highLimitValue = this._keys[this._keys.length - 1].value;
  14424. } else {
  14425. // Get max value if required
  14426. var highLimitValue = 0;
  14427. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  14428. var keyOffset = to.toString() + from.toString();
  14429. if (!this._offsetsCache[keyOffset]) {
  14430. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14431. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14432. switch (this.dataType) {
  14433. case Animation.ANIMATIONTYPE_FLOAT:
  14434. this._offsetsCache[keyOffset] = toValue - fromValue;
  14435. break;
  14436. case Animation.ANIMATIONTYPE_QUATERNION:
  14437. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14438. break;
  14439. case Animation.ANIMATIONTYPE_VECTOR3:
  14440. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14441. case Animation.ANIMATIONTYPE_VECTOR2:
  14442. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14443. case Animation.ANIMATIONTYPE_COLOR3:
  14444. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14445. default:
  14446. break;
  14447. }
  14448. this._highLimitsCache[keyOffset] = toValue;
  14449. }
  14450. highLimitValue = this._highLimitsCache[keyOffset];
  14451. offsetValue = this._offsetsCache[keyOffset];
  14452. }
  14453. }
  14454. if (offsetValue === undefined) {
  14455. switch (this.dataType) {
  14456. case Animation.ANIMATIONTYPE_FLOAT:
  14457. offsetValue = 0;
  14458. break;
  14459. case Animation.ANIMATIONTYPE_QUATERNION:
  14460. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14461. break;
  14462. case Animation.ANIMATIONTYPE_VECTOR3:
  14463. offsetValue = BABYLON.Vector3.Zero();
  14464. break;
  14465. case Animation.ANIMATIONTYPE_VECTOR2:
  14466. offsetValue = BABYLON.Vector2.Zero();
  14467. break;
  14468. case Animation.ANIMATIONTYPE_COLOR3:
  14469. offsetValue = BABYLON.Color3.Black();
  14470. }
  14471. }
  14472. // Compute value
  14473. var repeatCount = (ratio / range) >> 0;
  14474. var currentFrame = returnValue ? from + ratio % range : to;
  14475. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14476. // Set value
  14477. if (this.targetPropertyPath.length > 1) {
  14478. var property = this._target[this.targetPropertyPath[0]];
  14479. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14480. property = property[this.targetPropertyPath[index]];
  14481. }
  14482. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14483. } else {
  14484. this._target[this.targetPropertyPath[0]] = currentValue;
  14485. }
  14486. if (this._target.markAsDirty) {
  14487. this._target.markAsDirty(this.targetProperty);
  14488. }
  14489. if (!returnValue) {
  14490. this._stopped = true;
  14491. }
  14492. return returnValue;
  14493. };
  14494. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14495. get: function () {
  14496. return Animation._ANIMATIONTYPE_FLOAT;
  14497. },
  14498. enumerable: true,
  14499. configurable: true
  14500. });
  14501. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14502. get: function () {
  14503. return Animation._ANIMATIONTYPE_VECTOR3;
  14504. },
  14505. enumerable: true,
  14506. configurable: true
  14507. });
  14508. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14509. get: function () {
  14510. return Animation._ANIMATIONTYPE_VECTOR2;
  14511. },
  14512. enumerable: true,
  14513. configurable: true
  14514. });
  14515. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14516. get: function () {
  14517. return Animation._ANIMATIONTYPE_QUATERNION;
  14518. },
  14519. enumerable: true,
  14520. configurable: true
  14521. });
  14522. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14523. get: function () {
  14524. return Animation._ANIMATIONTYPE_MATRIX;
  14525. },
  14526. enumerable: true,
  14527. configurable: true
  14528. });
  14529. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14530. get: function () {
  14531. return Animation._ANIMATIONTYPE_COLOR3;
  14532. },
  14533. enumerable: true,
  14534. configurable: true
  14535. });
  14536. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14537. get: function () {
  14538. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14544. get: function () {
  14545. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14546. },
  14547. enumerable: true,
  14548. configurable: true
  14549. });
  14550. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14551. get: function () {
  14552. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14553. },
  14554. enumerable: true,
  14555. configurable: true
  14556. });
  14557. Animation._ANIMATIONTYPE_FLOAT = 0;
  14558. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14559. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14560. Animation._ANIMATIONTYPE_MATRIX = 3;
  14561. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14562. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14563. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14564. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14565. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14566. return Animation;
  14567. })();
  14568. BABYLON.Animation = Animation;
  14569. })(BABYLON || (BABYLON = {}));
  14570. //# sourceMappingURL=babylon.animation.js.map
  14571. var BABYLON;
  14572. (function (BABYLON) {
  14573. var Animatable = (function () {
  14574. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14575. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14576. if (typeof toFrame === "undefined") { toFrame = 100; }
  14577. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14578. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14579. this.target = target;
  14580. this.fromFrame = fromFrame;
  14581. this.toFrame = toFrame;
  14582. this.loopAnimation = loopAnimation;
  14583. this.speedRatio = speedRatio;
  14584. this.onAnimationEnd = onAnimationEnd;
  14585. this._animations = new Array();
  14586. this._paused = false;
  14587. this.animationStarted = false;
  14588. if (animations) {
  14589. this.appendAnimations(target, animations);
  14590. }
  14591. this._scene = scene;
  14592. scene._activeAnimatables.push(this);
  14593. }
  14594. // Methods
  14595. Animatable.prototype.appendAnimations = function (target, animations) {
  14596. for (var index = 0; index < animations.length; index++) {
  14597. var animation = animations[index];
  14598. animation._target = target;
  14599. this._animations.push(animation);
  14600. }
  14601. };
  14602. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14603. var animations = this._animations;
  14604. for (var index = 0; index < animations.length; index++) {
  14605. if (animations[index].targetProperty === property) {
  14606. return animations[index];
  14607. }
  14608. }
  14609. return null;
  14610. };
  14611. Animatable.prototype.pause = function () {
  14612. if (this._paused) {
  14613. return;
  14614. }
  14615. this._paused = true;
  14616. };
  14617. Animatable.prototype.restart = function () {
  14618. this._paused = false;
  14619. };
  14620. Animatable.prototype.stop = function () {
  14621. var index = this._scene._activeAnimatables.indexOf(this);
  14622. if (index > -1) {
  14623. this._scene._activeAnimatables.splice(index, 1);
  14624. }
  14625. if (this.onAnimationEnd) {
  14626. this.onAnimationEnd();
  14627. }
  14628. };
  14629. Animatable.prototype._animate = function (delay) {
  14630. if (this._paused) {
  14631. if (!this._pausedDelay) {
  14632. this._pausedDelay = delay;
  14633. }
  14634. return true;
  14635. }
  14636. if (!this._localDelayOffset) {
  14637. this._localDelayOffset = delay;
  14638. } else if (this._pausedDelay) {
  14639. this._localDelayOffset += delay - this._pausedDelay;
  14640. this._pausedDelay = null;
  14641. }
  14642. // Animating
  14643. var running = false;
  14644. var animations = this._animations;
  14645. for (var index = 0; index < animations.length; index++) {
  14646. var animation = animations[index];
  14647. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14648. running = running || isRunning;
  14649. }
  14650. if (!running && this.onAnimationEnd) {
  14651. this.onAnimationEnd();
  14652. }
  14653. return running;
  14654. };
  14655. return Animatable;
  14656. })();
  14657. BABYLON.Animatable = Animatable;
  14658. })(BABYLON || (BABYLON = {}));
  14659. //# sourceMappingURL=babylon.animatable.js.map
  14660. var BABYLON;
  14661. (function (BABYLON) {
  14662. var EasingFunction = (function () {
  14663. function EasingFunction() {
  14664. // Properties
  14665. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14666. }
  14667. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14668. get: function () {
  14669. return EasingFunction._EASINGMODE_EASEIN;
  14670. },
  14671. enumerable: true,
  14672. configurable: true
  14673. });
  14674. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14675. get: function () {
  14676. return EasingFunction._EASINGMODE_EASEOUT;
  14677. },
  14678. enumerable: true,
  14679. configurable: true
  14680. });
  14681. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14682. get: function () {
  14683. return EasingFunction._EASINGMODE_EASEINOUT;
  14684. },
  14685. enumerable: true,
  14686. configurable: true
  14687. });
  14688. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14689. var n = Math.min(Math.max(easingMode, 0), 2);
  14690. this._easingMode = n;
  14691. };
  14692. EasingFunction.prototype.getEasingMode = function () {
  14693. return this._easingMode;
  14694. };
  14695. EasingFunction.prototype.easeInCore = function (gradient) {
  14696. throw new Error('You must implement this method');
  14697. };
  14698. EasingFunction.prototype.ease = function (gradient) {
  14699. switch (this._easingMode) {
  14700. case EasingFunction.EASINGMODE_EASEIN:
  14701. return this.easeInCore(gradient);
  14702. case EasingFunction.EASINGMODE_EASEOUT:
  14703. return (1 - this.easeInCore(1 - gradient));
  14704. }
  14705. if (gradient >= 0.5) {
  14706. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14707. }
  14708. return (this.easeInCore(gradient * 2) * 0.5);
  14709. };
  14710. EasingFunction._EASINGMODE_EASEIN = 0;
  14711. EasingFunction._EASINGMODE_EASEOUT = 1;
  14712. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14713. return EasingFunction;
  14714. })();
  14715. BABYLON.EasingFunction = EasingFunction;
  14716. var CircleEase = (function (_super) {
  14717. __extends(CircleEase, _super);
  14718. function CircleEase() {
  14719. _super.apply(this, arguments);
  14720. }
  14721. CircleEase.prototype.easeInCore = function (gradient) {
  14722. gradient = Math.max(0, Math.min(1, gradient));
  14723. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14724. };
  14725. return CircleEase;
  14726. })(EasingFunction);
  14727. BABYLON.CircleEase = CircleEase;
  14728. var BackEase = (function (_super) {
  14729. __extends(BackEase, _super);
  14730. function BackEase(amplitude) {
  14731. if (typeof amplitude === "undefined") { amplitude = 1; }
  14732. _super.call(this);
  14733. this.amplitude = amplitude;
  14734. }
  14735. BackEase.prototype.easeInCore = function (gradient) {
  14736. var num = Math.max(0, this.amplitude);
  14737. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14738. };
  14739. return BackEase;
  14740. })(EasingFunction);
  14741. BABYLON.BackEase = BackEase;
  14742. var BounceEase = (function (_super) {
  14743. __extends(BounceEase, _super);
  14744. function BounceEase(bounces, bounciness) {
  14745. if (typeof bounces === "undefined") { bounces = 3; }
  14746. if (typeof bounciness === "undefined") { bounciness = 2; }
  14747. _super.call(this);
  14748. this.bounces = bounces;
  14749. this.bounciness = bounciness;
  14750. }
  14751. BounceEase.prototype.easeInCore = function (gradient) {
  14752. var y = Math.max(0.0, this.bounces);
  14753. var bounciness = this.bounciness;
  14754. if (bounciness <= 1.0) {
  14755. bounciness = 1.001;
  14756. }
  14757. var num9 = Math.pow(bounciness, y);
  14758. var num5 = 1.0 - bounciness;
  14759. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14760. var num15 = gradient * num4;
  14761. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14762. var num3 = Math.floor(num65);
  14763. var num13 = num3 + 1.0;
  14764. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14765. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14766. var num7 = (num8 + num12) * 0.5;
  14767. var num6 = gradient - num7;
  14768. var num2 = num7 - num8;
  14769. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14770. };
  14771. return BounceEase;
  14772. })(EasingFunction);
  14773. BABYLON.BounceEase = BounceEase;
  14774. var CubicEase = (function (_super) {
  14775. __extends(CubicEase, _super);
  14776. function CubicEase() {
  14777. _super.apply(this, arguments);
  14778. }
  14779. CubicEase.prototype.easeInCore = function (gradient) {
  14780. return (gradient * gradient * gradient);
  14781. };
  14782. return CubicEase;
  14783. })(EasingFunction);
  14784. BABYLON.CubicEase = CubicEase;
  14785. var ElasticEase = (function (_super) {
  14786. __extends(ElasticEase, _super);
  14787. function ElasticEase(oscillations, springiness) {
  14788. if (typeof oscillations === "undefined") { oscillations = 3; }
  14789. if (typeof springiness === "undefined") { springiness = 3; }
  14790. _super.call(this);
  14791. this.oscillations = oscillations;
  14792. this.springiness = springiness;
  14793. }
  14794. ElasticEase.prototype.easeInCore = function (gradient) {
  14795. var num2;
  14796. var num3 = Math.max(0.0, this.oscillations);
  14797. var num = Math.max(0.0, this.springiness);
  14798. if (num == 0) {
  14799. num2 = gradient;
  14800. } else {
  14801. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14802. }
  14803. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14804. };
  14805. return ElasticEase;
  14806. })(EasingFunction);
  14807. BABYLON.ElasticEase = ElasticEase;
  14808. var ExponentialEase = (function (_super) {
  14809. __extends(ExponentialEase, _super);
  14810. function ExponentialEase(exponent) {
  14811. if (typeof exponent === "undefined") { exponent = 2; }
  14812. _super.call(this);
  14813. this.exponent = exponent;
  14814. }
  14815. ExponentialEase.prototype.easeInCore = function (gradient) {
  14816. if (this.exponent <= 0) {
  14817. return gradient;
  14818. }
  14819. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14820. };
  14821. return ExponentialEase;
  14822. })(EasingFunction);
  14823. BABYLON.ExponentialEase = ExponentialEase;
  14824. var PowerEase = (function (_super) {
  14825. __extends(PowerEase, _super);
  14826. function PowerEase(power) {
  14827. if (typeof power === "undefined") { power = 2; }
  14828. _super.call(this);
  14829. this.power = power;
  14830. }
  14831. PowerEase.prototype.easeInCore = function (gradient) {
  14832. var y = Math.max(0.0, this.power);
  14833. return Math.pow(gradient, y);
  14834. };
  14835. return PowerEase;
  14836. })(EasingFunction);
  14837. BABYLON.PowerEase = PowerEase;
  14838. var QuadraticEase = (function (_super) {
  14839. __extends(QuadraticEase, _super);
  14840. function QuadraticEase() {
  14841. _super.apply(this, arguments);
  14842. }
  14843. QuadraticEase.prototype.easeInCore = function (gradient) {
  14844. return (gradient * gradient);
  14845. };
  14846. return QuadraticEase;
  14847. })(EasingFunction);
  14848. BABYLON.QuadraticEase = QuadraticEase;
  14849. var QuarticEase = (function (_super) {
  14850. __extends(QuarticEase, _super);
  14851. function QuarticEase() {
  14852. _super.apply(this, arguments);
  14853. }
  14854. QuarticEase.prototype.easeInCore = function (gradient) {
  14855. return (gradient * gradient * gradient * gradient);
  14856. };
  14857. return QuarticEase;
  14858. })(EasingFunction);
  14859. BABYLON.QuarticEase = QuarticEase;
  14860. var QuinticEase = (function (_super) {
  14861. __extends(QuinticEase, _super);
  14862. function QuinticEase() {
  14863. _super.apply(this, arguments);
  14864. }
  14865. QuinticEase.prototype.easeInCore = function (gradient) {
  14866. return (gradient * gradient * gradient * gradient * gradient);
  14867. };
  14868. return QuinticEase;
  14869. })(EasingFunction);
  14870. BABYLON.QuinticEase = QuinticEase;
  14871. var SineEase = (function (_super) {
  14872. __extends(SineEase, _super);
  14873. function SineEase() {
  14874. _super.apply(this, arguments);
  14875. }
  14876. SineEase.prototype.easeInCore = function (gradient) {
  14877. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14878. };
  14879. return SineEase;
  14880. })(EasingFunction);
  14881. BABYLON.SineEase = SineEase;
  14882. var BezierCurveEase = (function (_super) {
  14883. __extends(BezierCurveEase, _super);
  14884. function BezierCurveEase(x1, y1, x2, y2) {
  14885. if (typeof x1 === "undefined") { x1 = 0; }
  14886. if (typeof y1 === "undefined") { y1 = 0; }
  14887. if (typeof x2 === "undefined") { x2 = 1; }
  14888. if (typeof y2 === "undefined") { y2 = 1; }
  14889. _super.call(this);
  14890. this.x1 = x1;
  14891. this.y1 = y1;
  14892. this.x2 = x2;
  14893. this.y2 = y2;
  14894. }
  14895. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14896. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14897. };
  14898. return BezierCurveEase;
  14899. })(EasingFunction);
  14900. BABYLON.BezierCurveEase = BezierCurveEase;
  14901. })(BABYLON || (BABYLON = {}));
  14902. //# sourceMappingURL=babylon.easing.js.map
  14903. var BABYLON;
  14904. (function (BABYLON) {
  14905. var Octree = (function () {
  14906. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14907. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14908. this.maxDepth = maxDepth;
  14909. this.dynamicContent = new Array();
  14910. this._maxBlockCapacity = maxBlockCapacity || 64;
  14911. this._selectionContent = new BABYLON.SmartArray(1024);
  14912. this._creationFunc = creationFunc;
  14913. }
  14914. // Methods
  14915. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14916. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14917. };
  14918. Octree.prototype.addMesh = function (entry) {
  14919. for (var index = 0; index < this.blocks.length; index++) {
  14920. var block = this.blocks[index];
  14921. block.addEntry(entry);
  14922. }
  14923. };
  14924. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14925. this._selectionContent.reset();
  14926. for (var index = 0; index < this.blocks.length; index++) {
  14927. var block = this.blocks[index];
  14928. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14929. }
  14930. if (allowDuplicate) {
  14931. this._selectionContent.concat(this.dynamicContent);
  14932. } else {
  14933. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14934. }
  14935. return this._selectionContent;
  14936. };
  14937. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14938. this._selectionContent.reset();
  14939. for (var index = 0; index < this.blocks.length; index++) {
  14940. var block = this.blocks[index];
  14941. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14942. }
  14943. if (allowDuplicate) {
  14944. this._selectionContent.concat(this.dynamicContent);
  14945. } else {
  14946. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14947. }
  14948. return this._selectionContent;
  14949. };
  14950. Octree.prototype.intersectsRay = function (ray) {
  14951. this._selectionContent.reset();
  14952. for (var index = 0; index < this.blocks.length; index++) {
  14953. var block = this.blocks[index];
  14954. block.intersectsRay(ray, this._selectionContent);
  14955. }
  14956. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14957. return this._selectionContent;
  14958. };
  14959. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14960. target.blocks = new Array();
  14961. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14962. for (var x = 0; x < 2; x++) {
  14963. for (var y = 0; y < 2; y++) {
  14964. for (var z = 0; z < 2; z++) {
  14965. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14966. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14967. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14968. block.addEntries(entries);
  14969. target.blocks.push(block);
  14970. }
  14971. }
  14972. }
  14973. };
  14974. Octree.CreationFuncForMeshes = function (entry, block) {
  14975. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14976. block.entries.push(entry);
  14977. }
  14978. };
  14979. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14980. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14981. block.entries.push(entry);
  14982. }
  14983. };
  14984. return Octree;
  14985. })();
  14986. BABYLON.Octree = Octree;
  14987. })(BABYLON || (BABYLON = {}));
  14988. //# sourceMappingURL=babylon.octree.js.map
  14989. var BABYLON;
  14990. (function (BABYLON) {
  14991. var OctreeBlock = (function () {
  14992. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14993. this.entries = new Array();
  14994. this._boundingVectors = new Array();
  14995. this._capacity = capacity;
  14996. this._depth = depth;
  14997. this._maxDepth = maxDepth;
  14998. this._creationFunc = creationFunc;
  14999. this._minPoint = minPoint;
  15000. this._maxPoint = maxPoint;
  15001. this._boundingVectors.push(minPoint.clone());
  15002. this._boundingVectors.push(maxPoint.clone());
  15003. this._boundingVectors.push(minPoint.clone());
  15004. this._boundingVectors[2].x = maxPoint.x;
  15005. this._boundingVectors.push(minPoint.clone());
  15006. this._boundingVectors[3].y = maxPoint.y;
  15007. this._boundingVectors.push(minPoint.clone());
  15008. this._boundingVectors[4].z = maxPoint.z;
  15009. this._boundingVectors.push(maxPoint.clone());
  15010. this._boundingVectors[5].z = minPoint.z;
  15011. this._boundingVectors.push(maxPoint.clone());
  15012. this._boundingVectors[6].x = minPoint.x;
  15013. this._boundingVectors.push(maxPoint.clone());
  15014. this._boundingVectors[7].y = minPoint.y;
  15015. }
  15016. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15017. // Property
  15018. get: function () {
  15019. return this._capacity;
  15020. },
  15021. enumerable: true,
  15022. configurable: true
  15023. });
  15024. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15025. get: function () {
  15026. return this._minPoint;
  15027. },
  15028. enumerable: true,
  15029. configurable: true
  15030. });
  15031. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15032. get: function () {
  15033. return this._maxPoint;
  15034. },
  15035. enumerable: true,
  15036. configurable: true
  15037. });
  15038. // Methods
  15039. OctreeBlock.prototype.addEntry = function (entry) {
  15040. if (this.blocks) {
  15041. for (var index = 0; index < this.blocks.length; index++) {
  15042. var block = this.blocks[index];
  15043. block.addEntry(entry);
  15044. }
  15045. return;
  15046. }
  15047. this._creationFunc(entry, this);
  15048. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15049. this.createInnerBlocks();
  15050. }
  15051. };
  15052. OctreeBlock.prototype.addEntries = function (entries) {
  15053. for (var index = 0; index < entries.length; index++) {
  15054. var mesh = entries[index];
  15055. this.addEntry(mesh);
  15056. }
  15057. };
  15058. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15059. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15060. if (this.blocks) {
  15061. for (var index = 0; index < this.blocks.length; index++) {
  15062. var block = this.blocks[index];
  15063. block.select(frustumPlanes, selection, allowDuplicate);
  15064. }
  15065. return;
  15066. }
  15067. if (allowDuplicate) {
  15068. selection.concat(this.entries);
  15069. } else {
  15070. selection.concatWithNoDuplicate(this.entries);
  15071. }
  15072. }
  15073. };
  15074. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15075. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15076. if (this.blocks) {
  15077. for (var index = 0; index < this.blocks.length; index++) {
  15078. var block = this.blocks[index];
  15079. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15080. }
  15081. return;
  15082. }
  15083. if (allowDuplicate) {
  15084. selection.concat(this.entries);
  15085. } else {
  15086. selection.concatWithNoDuplicate(this.entries);
  15087. }
  15088. }
  15089. };
  15090. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15091. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15092. if (this.blocks) {
  15093. for (var index = 0; index < this.blocks.length; index++) {
  15094. var block = this.blocks[index];
  15095. block.intersectsRay(ray, selection);
  15096. }
  15097. return;
  15098. }
  15099. selection.concatWithNoDuplicate(this.entries);
  15100. }
  15101. };
  15102. OctreeBlock.prototype.createInnerBlocks = function () {
  15103. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15104. };
  15105. return OctreeBlock;
  15106. })();
  15107. BABYLON.OctreeBlock = OctreeBlock;
  15108. })(BABYLON || (BABYLON = {}));
  15109. //# sourceMappingURL=babylon.octreeBlock.js.map
  15110. var BABYLON;
  15111. (function (BABYLON) {
  15112. var Bone = (function () {
  15113. function Bone(name, skeleton, parentBone, matrix) {
  15114. this.name = name;
  15115. this.children = new Array();
  15116. this.animations = new Array();
  15117. this._worldTransform = new BABYLON.Matrix();
  15118. this._absoluteTransform = new BABYLON.Matrix();
  15119. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15120. this._skeleton = skeleton;
  15121. this._matrix = matrix;
  15122. this._baseMatrix = matrix;
  15123. skeleton.bones.push(this);
  15124. if (parentBone) {
  15125. this._parent = parentBone;
  15126. parentBone.children.push(this);
  15127. } else {
  15128. this._parent = null;
  15129. }
  15130. this._updateDifferenceMatrix();
  15131. }
  15132. // Members
  15133. Bone.prototype.getParent = function () {
  15134. return this._parent;
  15135. };
  15136. Bone.prototype.getLocalMatrix = function () {
  15137. return this._matrix;
  15138. };
  15139. Bone.prototype.getBaseMatrix = function () {
  15140. return this._baseMatrix;
  15141. };
  15142. Bone.prototype.getWorldMatrix = function () {
  15143. return this._worldTransform;
  15144. };
  15145. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15146. return this._invertedAbsoluteTransform;
  15147. };
  15148. Bone.prototype.getAbsoluteMatrix = function () {
  15149. var matrix = this._matrix.clone();
  15150. var parent = this._parent;
  15151. while (parent) {
  15152. matrix = matrix.multiply(parent.getLocalMatrix());
  15153. parent = parent.getParent();
  15154. }
  15155. return matrix;
  15156. };
  15157. // Methods
  15158. Bone.prototype.updateMatrix = function (matrix) {
  15159. this._matrix = matrix;
  15160. this._skeleton._markAsDirty();
  15161. this._updateDifferenceMatrix();
  15162. };
  15163. Bone.prototype._updateDifferenceMatrix = function () {
  15164. if (this._parent) {
  15165. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15166. } else {
  15167. this._absoluteTransform.copyFrom(this._matrix);
  15168. }
  15169. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15170. for (var index = 0; index < this.children.length; index++) {
  15171. this.children[index]._updateDifferenceMatrix();
  15172. }
  15173. };
  15174. Bone.prototype.markAsDirty = function () {
  15175. this._skeleton._markAsDirty();
  15176. };
  15177. return Bone;
  15178. })();
  15179. BABYLON.Bone = Bone;
  15180. })(BABYLON || (BABYLON = {}));
  15181. //# sourceMappingURL=babylon.bone.js.map
  15182. var BABYLON;
  15183. (function (BABYLON) {
  15184. var Skeleton = (function () {
  15185. function Skeleton(name, id, scene) {
  15186. this.name = name;
  15187. this.id = id;
  15188. this.bones = new Array();
  15189. this._isDirty = true;
  15190. this._identity = BABYLON.Matrix.Identity();
  15191. this.bones = [];
  15192. this._scene = scene;
  15193. scene.skeletons.push(this);
  15194. }
  15195. // Members
  15196. Skeleton.prototype.getTransformMatrices = function () {
  15197. return this._transformMatrices;
  15198. };
  15199. // Methods
  15200. Skeleton.prototype._markAsDirty = function () {
  15201. this._isDirty = true;
  15202. };
  15203. Skeleton.prototype.prepare = function () {
  15204. if (!this._isDirty) {
  15205. return;
  15206. }
  15207. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15208. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15209. }
  15210. for (var index = 0; index < this.bones.length; index++) {
  15211. var bone = this.bones[index];
  15212. var parentBone = bone.getParent();
  15213. if (parentBone) {
  15214. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15215. } else {
  15216. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15217. }
  15218. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15219. }
  15220. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15221. this._isDirty = false;
  15222. };
  15223. Skeleton.prototype.getAnimatables = function () {
  15224. if (!this._animatables || this._animatables.length != this.bones.length) {
  15225. this._animatables = [];
  15226. for (var index = 0; index < this.bones.length; index++) {
  15227. this._animatables.push(this.bones[index]);
  15228. }
  15229. }
  15230. return this._animatables;
  15231. };
  15232. Skeleton.prototype.clone = function (name, id) {
  15233. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15234. for (var index = 0; index < this.bones.length; index++) {
  15235. var source = this.bones[index];
  15236. var parentBone = null;
  15237. if (source.getParent()) {
  15238. var parentIndex = this.bones.indexOf(source.getParent());
  15239. parentBone = result.bones[parentIndex];
  15240. }
  15241. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15242. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15243. }
  15244. return result;
  15245. };
  15246. return Skeleton;
  15247. })();
  15248. BABYLON.Skeleton = Skeleton;
  15249. })(BABYLON || (BABYLON = {}));
  15250. //# sourceMappingURL=babylon.skeleton.js.map
  15251. var BABYLON;
  15252. (function (BABYLON) {
  15253. var PostProcess = (function () {
  15254. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15255. this.name = name;
  15256. this.width = -1;
  15257. this.height = -1;
  15258. this._reusable = false;
  15259. this._textures = new BABYLON.SmartArray(2);
  15260. this._currentRenderTextureInd = 0;
  15261. if (camera != null) {
  15262. this._camera = camera;
  15263. this._scene = camera.getScene();
  15264. camera.attachPostProcess(this);
  15265. this._engine = this._scene.getEngine();
  15266. } else {
  15267. this._engine = engine;
  15268. }
  15269. this._renderRatio = ratio;
  15270. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15271. this._reusable = reusable || false;
  15272. samplers = samplers || [];
  15273. samplers.push("textureSampler");
  15274. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15275. }
  15276. PostProcess.prototype.isReusable = function () {
  15277. return this._reusable;
  15278. };
  15279. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15280. camera = camera || this._camera;
  15281. var scene = camera.getScene();
  15282. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15283. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15284. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15285. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15286. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15287. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15288. if (this._textures.length > 0) {
  15289. for (var i = 0; i < this._textures.length; i++) {
  15290. this._engine._releaseTexture(this._textures.data[i]);
  15291. }
  15292. this._textures.reset();
  15293. }
  15294. this.width = desiredWidth;
  15295. this.height = desiredHeight;
  15296. 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 }));
  15297. if (this._reusable) {
  15298. 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 }));
  15299. }
  15300. if (this.onSizeChanged) {
  15301. this.onSizeChanged();
  15302. }
  15303. }
  15304. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15305. if (this.onActivate) {
  15306. this.onActivate(camera);
  15307. }
  15308. // Clear
  15309. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15310. if (this._reusable) {
  15311. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15312. }
  15313. };
  15314. PostProcess.prototype.apply = function () {
  15315. // Check
  15316. if (!this._effect.isReady())
  15317. return null;
  15318. // States
  15319. this._engine.enableEffect(this._effect);
  15320. this._engine.setState(false);
  15321. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15322. this._engine.setDepthBuffer(false);
  15323. this._engine.setDepthWrite(false);
  15324. // Texture
  15325. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15326. // Parameters
  15327. if (this.onApply) {
  15328. this.onApply(this._effect);
  15329. }
  15330. return this._effect;
  15331. };
  15332. PostProcess.prototype.dispose = function (camera) {
  15333. camera = camera || this._camera;
  15334. if (this._textures.length > 0) {
  15335. for (var i = 0; i < this._textures.length; i++) {
  15336. this._engine._releaseTexture(this._textures.data[i]);
  15337. }
  15338. this._textures.reset();
  15339. }
  15340. camera.detachPostProcess(this);
  15341. var index = camera._postProcesses.indexOf(this);
  15342. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15343. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15344. }
  15345. };
  15346. return PostProcess;
  15347. })();
  15348. BABYLON.PostProcess = PostProcess;
  15349. })(BABYLON || (BABYLON = {}));
  15350. //# sourceMappingURL=babylon.postProcess.js.map
  15351. var BABYLON;
  15352. (function (BABYLON) {
  15353. var PostProcessManager = (function () {
  15354. function PostProcessManager(scene) {
  15355. this._vertexDeclaration = [2];
  15356. this._vertexStrideSize = 2 * 4;
  15357. this._scene = scene;
  15358. // VBO
  15359. var vertices = [];
  15360. vertices.push(1, 1);
  15361. vertices.push(-1, 1);
  15362. vertices.push(-1, -1);
  15363. vertices.push(1, -1);
  15364. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15365. // Indices
  15366. var indices = [];
  15367. indices.push(0);
  15368. indices.push(1);
  15369. indices.push(2);
  15370. indices.push(0);
  15371. indices.push(2);
  15372. indices.push(3);
  15373. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15374. }
  15375. // Methods
  15376. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15377. var postProcesses = this._scene.activeCamera._postProcesses;
  15378. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15379. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15380. return false;
  15381. }
  15382. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15383. return true;
  15384. };
  15385. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15386. var postProcesses = this._scene.activeCamera._postProcesses;
  15387. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15388. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15389. return;
  15390. }
  15391. var engine = this._scene.getEngine();
  15392. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15393. if (index < postProcessesTakenIndices.length - 1) {
  15394. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15395. } else {
  15396. if (targetTexture) {
  15397. engine.bindFramebuffer(targetTexture);
  15398. } else {
  15399. engine.restoreDefaultFramebuffer();
  15400. }
  15401. }
  15402. if (doNotPresent) {
  15403. break;
  15404. }
  15405. var pp = postProcesses[postProcessesTakenIndices[index]];
  15406. var effect = pp.apply();
  15407. if (effect) {
  15408. if (pp.onBeforeRender) {
  15409. pp.onBeforeRender(effect);
  15410. }
  15411. // VBOs
  15412. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15413. // Draw order
  15414. engine.draw(true, 0, 6);
  15415. }
  15416. }
  15417. // Restore depth buffer
  15418. engine.setDepthBuffer(true);
  15419. engine.setDepthWrite(true);
  15420. };
  15421. PostProcessManager.prototype.dispose = function () {
  15422. if (this._vertexBuffer) {
  15423. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15424. this._vertexBuffer = null;
  15425. }
  15426. if (this._indexBuffer) {
  15427. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15428. this._indexBuffer = null;
  15429. }
  15430. };
  15431. return PostProcessManager;
  15432. })();
  15433. BABYLON.PostProcessManager = PostProcessManager;
  15434. })(BABYLON || (BABYLON = {}));
  15435. //# sourceMappingURL=babylon.postProcessManager.js.map
  15436. var BABYLON;
  15437. (function (BABYLON) {
  15438. var PassPostProcess = (function (_super) {
  15439. __extends(PassPostProcess, _super);
  15440. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15441. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15442. }
  15443. return PassPostProcess;
  15444. })(BABYLON.PostProcess);
  15445. BABYLON.PassPostProcess = PassPostProcess;
  15446. })(BABYLON || (BABYLON = {}));
  15447. //# sourceMappingURL=babylon.passPostProcess.js.map
  15448. var BABYLON;
  15449. (function (BABYLON) {
  15450. var BlurPostProcess = (function (_super) {
  15451. __extends(BlurPostProcess, _super);
  15452. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15453. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15454. var _this = this;
  15455. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15456. this.direction = direction;
  15457. this.blurWidth = blurWidth;
  15458. this.onApply = function (effect) {
  15459. effect.setFloat2("screenSize", _this.width, _this.height);
  15460. effect.setVector2("direction", _this.direction);
  15461. effect.setFloat("blurWidth", _this.blurWidth);
  15462. };
  15463. }
  15464. return BlurPostProcess;
  15465. })(BABYLON.PostProcess);
  15466. BABYLON.BlurPostProcess = BlurPostProcess;
  15467. })(BABYLON || (BABYLON = {}));
  15468. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15469. var BABYLON;
  15470. (function (BABYLON) {
  15471. var FilterPostProcess = (function (_super) {
  15472. __extends(FilterPostProcess, _super);
  15473. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15474. var _this = this;
  15475. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15476. this.kernelMatrix = kernelMatrix;
  15477. this.onApply = function (effect) {
  15478. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15479. };
  15480. }
  15481. return FilterPostProcess;
  15482. })(BABYLON.PostProcess);
  15483. BABYLON.FilterPostProcess = FilterPostProcess;
  15484. })(BABYLON || (BABYLON = {}));
  15485. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15486. var BABYLON;
  15487. (function (BABYLON) {
  15488. var RefractionPostProcess = (function (_super) {
  15489. __extends(RefractionPostProcess, _super);
  15490. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15491. var _this = this;
  15492. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15493. this.color = color;
  15494. this.depth = depth;
  15495. this.colorLevel = colorLevel;
  15496. this.onActivate = function (cam) {
  15497. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15498. };
  15499. this.onApply = function (effect) {
  15500. effect.setColor3("baseColor", _this.color);
  15501. effect.setFloat("depth", _this.depth);
  15502. effect.setFloat("colorLevel", _this.colorLevel);
  15503. effect.setTexture("refractionSampler", _this._refRexture);
  15504. };
  15505. }
  15506. // Methods
  15507. RefractionPostProcess.prototype.dispose = function (camera) {
  15508. if (this._refRexture) {
  15509. this._refRexture.dispose();
  15510. }
  15511. _super.prototype.dispose.call(this, camera);
  15512. };
  15513. return RefractionPostProcess;
  15514. })(BABYLON.PostProcess);
  15515. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15516. })(BABYLON || (BABYLON = {}));
  15517. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15518. var BABYLON;
  15519. (function (BABYLON) {
  15520. var BlackAndWhitePostProcess = (function (_super) {
  15521. __extends(BlackAndWhitePostProcess, _super);
  15522. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15523. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15524. }
  15525. return BlackAndWhitePostProcess;
  15526. })(BABYLON.PostProcess);
  15527. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15528. })(BABYLON || (BABYLON = {}));
  15529. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15530. var BABYLON;
  15531. (function (BABYLON) {
  15532. var ConvolutionPostProcess = (function (_super) {
  15533. __extends(ConvolutionPostProcess, _super);
  15534. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15535. var _this = this;
  15536. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15537. this.kernel = kernel;
  15538. this.onApply = function (effect) {
  15539. effect.setFloat2("screenSize", _this.width, _this.height);
  15540. effect.setArray("kernel", _this.kernel);
  15541. };
  15542. }
  15543. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15544. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15545. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15546. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15547. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15548. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15549. return ConvolutionPostProcess;
  15550. })(BABYLON.PostProcess);
  15551. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15552. })(BABYLON || (BABYLON = {}));
  15553. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15554. var BABYLON;
  15555. (function (BABYLON) {
  15556. var FxaaPostProcess = (function (_super) {
  15557. __extends(FxaaPostProcess, _super);
  15558. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15559. var _this = this;
  15560. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15561. this.onSizeChanged = function () {
  15562. _this.texelWidth = 1.0 / _this.width;
  15563. _this.texelHeight = 1.0 / _this.height;
  15564. };
  15565. this.onApply = function (effect) {
  15566. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15567. };
  15568. }
  15569. return FxaaPostProcess;
  15570. })(BABYLON.PostProcess);
  15571. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15572. })(BABYLON || (BABYLON = {}));
  15573. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15574. var BABYLON;
  15575. (function (BABYLON) {
  15576. var LensFlare = (function () {
  15577. function LensFlare(size, position, color, imgUrl, system) {
  15578. this.size = size;
  15579. this.position = position;
  15580. this.dispose = function () {
  15581. if (this.texture) {
  15582. this.texture.dispose();
  15583. }
  15584. // Remove from scene
  15585. var index = this._system.lensFlares.indexOf(this);
  15586. this._system.lensFlares.splice(index, 1);
  15587. };
  15588. this.color = color || new BABYLON.Color3(1, 1, 1);
  15589. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15590. this._system = system;
  15591. system.lensFlares.push(this);
  15592. }
  15593. return LensFlare;
  15594. })();
  15595. BABYLON.LensFlare = LensFlare;
  15596. })(BABYLON || (BABYLON = {}));
  15597. //# sourceMappingURL=babylon.lensFlare.js.map
  15598. var BABYLON;
  15599. (function (BABYLON) {
  15600. var LensFlareSystem = (function () {
  15601. function LensFlareSystem(name, emitter, scene) {
  15602. this.name = name;
  15603. this.lensFlares = new Array();
  15604. this.borderLimit = 300;
  15605. this._vertexDeclaration = [2];
  15606. this._vertexStrideSize = 2 * 4;
  15607. this._isEnabled = true;
  15608. this._scene = scene;
  15609. this._emitter = emitter;
  15610. scene.lensFlareSystems.push(this);
  15611. this.meshesSelectionPredicate = function (m) {
  15612. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15613. };
  15614. // VBO
  15615. var vertices = [];
  15616. vertices.push(1, 1);
  15617. vertices.push(-1, 1);
  15618. vertices.push(-1, -1);
  15619. vertices.push(1, -1);
  15620. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15621. // Indices
  15622. var indices = [];
  15623. indices.push(0);
  15624. indices.push(1);
  15625. indices.push(2);
  15626. indices.push(0);
  15627. indices.push(2);
  15628. indices.push(3);
  15629. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15630. // Effects
  15631. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15632. }
  15633. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15634. get: function () {
  15635. return this._isEnabled;
  15636. },
  15637. set: function (value) {
  15638. this._isEnabled = value;
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. LensFlareSystem.prototype.getScene = function () {
  15644. return this._scene;
  15645. };
  15646. LensFlareSystem.prototype.getEmitter = function () {
  15647. return this._emitter;
  15648. };
  15649. LensFlareSystem.prototype.getEmitterPosition = function () {
  15650. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15651. };
  15652. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15653. var position = this.getEmitterPosition();
  15654. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15655. this._positionX = position.x;
  15656. this._positionY = position.y;
  15657. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15658. if (position.z > 0) {
  15659. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15660. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15661. return true;
  15662. }
  15663. }
  15664. return false;
  15665. };
  15666. LensFlareSystem.prototype._isVisible = function () {
  15667. if (!this._isEnabled) {
  15668. return false;
  15669. }
  15670. var emitterPosition = this.getEmitterPosition();
  15671. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15672. var distance = direction.length();
  15673. direction.normalize();
  15674. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15675. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15676. return !pickInfo.hit || pickInfo.distance > distance;
  15677. };
  15678. LensFlareSystem.prototype.render = function () {
  15679. if (!this._effect.isReady())
  15680. return false;
  15681. var engine = this._scene.getEngine();
  15682. var viewport = this._scene.activeCamera.viewport;
  15683. var globalViewport = viewport.toGlobal(engine);
  15684. // Position
  15685. if (!this.computeEffectivePosition(globalViewport)) {
  15686. return false;
  15687. }
  15688. // Visibility
  15689. if (!this._isVisible()) {
  15690. return false;
  15691. }
  15692. // Intensity
  15693. var awayX;
  15694. var awayY;
  15695. if (this._positionX < this.borderLimit + globalViewport.x) {
  15696. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15697. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15698. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15699. } else {
  15700. awayX = 0;
  15701. }
  15702. if (this._positionY < this.borderLimit + globalViewport.y) {
  15703. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15704. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15705. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15706. } else {
  15707. awayY = 0;
  15708. }
  15709. var away = (awayX > awayY) ? awayX : awayY;
  15710. if (away > this.borderLimit) {
  15711. away = this.borderLimit;
  15712. }
  15713. var intensity = 1.0 - (away / this.borderLimit);
  15714. if (intensity < 0) {
  15715. return false;
  15716. }
  15717. if (intensity > 1.0) {
  15718. intensity = 1.0;
  15719. }
  15720. // Position
  15721. var centerX = globalViewport.x + globalViewport.width / 2;
  15722. var centerY = globalViewport.y + globalViewport.height / 2;
  15723. var distX = centerX - this._positionX;
  15724. var distY = centerY - this._positionY;
  15725. // Effects
  15726. engine.enableEffect(this._effect);
  15727. engine.setState(false);
  15728. engine.setDepthBuffer(false);
  15729. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15730. // VBOs
  15731. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15732. for (var index = 0; index < this.lensFlares.length; index++) {
  15733. var flare = this.lensFlares[index];
  15734. var x = centerX - (distX * flare.position);
  15735. var y = centerY - (distY * flare.position);
  15736. var cw = flare.size;
  15737. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15738. var cx = 2 * (x / globalViewport.width) - 1.0;
  15739. var cy = 1.0 - 2 * (y / globalViewport.height);
  15740. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15741. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15742. // Texture
  15743. this._effect.setTexture("textureSampler", flare.texture);
  15744. // Color
  15745. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15746. // Draw order
  15747. engine.draw(true, 0, 6);
  15748. }
  15749. engine.setDepthBuffer(true);
  15750. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15751. return true;
  15752. };
  15753. LensFlareSystem.prototype.dispose = function () {
  15754. if (this._vertexBuffer) {
  15755. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15756. this._vertexBuffer = null;
  15757. }
  15758. if (this._indexBuffer) {
  15759. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15760. this._indexBuffer = null;
  15761. }
  15762. while (this.lensFlares.length) {
  15763. this.lensFlares[0].dispose();
  15764. }
  15765. // Remove from scene
  15766. var index = this._scene.lensFlareSystems.indexOf(this);
  15767. this._scene.lensFlareSystems.splice(index, 1);
  15768. };
  15769. return LensFlareSystem;
  15770. })();
  15771. BABYLON.LensFlareSystem = LensFlareSystem;
  15772. })(BABYLON || (BABYLON = {}));
  15773. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15774. var BABYLON;
  15775. (function (BABYLON) {
  15776. var IntersectionInfo = (function () {
  15777. function IntersectionInfo(bu, bv, distance) {
  15778. this.bu = bu;
  15779. this.bv = bv;
  15780. this.distance = distance;
  15781. this.faceId = 0;
  15782. }
  15783. return IntersectionInfo;
  15784. })();
  15785. BABYLON.IntersectionInfo = IntersectionInfo;
  15786. var PickingInfo = (function () {
  15787. function PickingInfo() {
  15788. this.hit = false;
  15789. this.distance = 0;
  15790. this.pickedPoint = null;
  15791. this.pickedMesh = null;
  15792. this.bu = 0;
  15793. this.bv = 0;
  15794. this.faceId = -1;
  15795. }
  15796. // Methods
  15797. PickingInfo.prototype.getNormal = function () {
  15798. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15799. return null;
  15800. }
  15801. var indices = this.pickedMesh.getIndices();
  15802. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15803. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15804. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15805. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15806. normal0 = normal0.scale(this.bu);
  15807. normal1 = normal1.scale(this.bv);
  15808. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15809. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15810. };
  15811. PickingInfo.prototype.getTextureCoordinates = function () {
  15812. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15813. return null;
  15814. }
  15815. var indices = this.pickedMesh.getIndices();
  15816. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15817. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15818. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15819. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15820. uv0 = uv0.scale(this.bu);
  15821. uv1 = uv1.scale(this.bv);
  15822. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15823. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15824. };
  15825. return PickingInfo;
  15826. })();
  15827. BABYLON.PickingInfo = PickingInfo;
  15828. })(BABYLON || (BABYLON = {}));
  15829. //# sourceMappingURL=babylon.pickingInfo.js.map
  15830. var BABYLON;
  15831. (function (BABYLON) {
  15832. var FilesInput = (function () {
  15833. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15834. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15835. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15836. this.engine = p_engine;
  15837. this.canvas = p_canvas;
  15838. this.currentScene = p_scene;
  15839. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15840. this.progressCallback = p_progressCallback;
  15841. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15842. this.textureLoadingCallback = p_textureLoadingCallback;
  15843. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15844. }
  15845. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15846. var _this = this;
  15847. if (p_elementToMonitor) {
  15848. this.elementToMonitor = p_elementToMonitor;
  15849. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15850. _this.drag(e);
  15851. }, false);
  15852. this.elementToMonitor.addEventListener("dragover", function (e) {
  15853. _this.drag(e);
  15854. }, false);
  15855. this.elementToMonitor.addEventListener("drop", function (e) {
  15856. _this.drop(e);
  15857. }, false);
  15858. }
  15859. };
  15860. FilesInput.prototype.renderFunction = function () {
  15861. if (this.additionnalRenderLoopLogicCallback) {
  15862. this.additionnalRenderLoopLogicCallback();
  15863. }
  15864. if (this.currentScene) {
  15865. if (this.textureLoadingCallback) {
  15866. var remaining = this.currentScene.getWaitingItemsCount();
  15867. if (remaining > 0) {
  15868. this.textureLoadingCallback(remaining);
  15869. }
  15870. }
  15871. this.currentScene.render();
  15872. }
  15873. };
  15874. FilesInput.prototype.drag = function (e) {
  15875. e.stopPropagation();
  15876. e.preventDefault();
  15877. };
  15878. FilesInput.prototype.drop = function (eventDrop) {
  15879. eventDrop.stopPropagation();
  15880. eventDrop.preventDefault();
  15881. this.loadFiles(eventDrop);
  15882. };
  15883. FilesInput.prototype.loadFiles = function (event) {
  15884. var _this = this;
  15885. var that = this;
  15886. if (this.startingProcessingFilesCallback)
  15887. this.startingProcessingFilesCallback();
  15888. var sceneFileToLoad;
  15889. var filesToLoad;
  15890. // Handling data transfer via drag'n'drop
  15891. if (event && event.dataTransfer && event.dataTransfer.files) {
  15892. filesToLoad = event.dataTransfer.files;
  15893. }
  15894. // Handling files from input files
  15895. if (event && event.target && event.target.files) {
  15896. filesToLoad = event.target.files;
  15897. }
  15898. if (filesToLoad && filesToLoad.length > 0) {
  15899. for (var i = 0; i < filesToLoad.length; i++) {
  15900. switch (filesToLoad[i].type) {
  15901. case "image/jpeg":
  15902. case "image/png":
  15903. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15904. break;
  15905. case "image/targa":
  15906. case "image/vnd.ms-dds":
  15907. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15908. break;
  15909. default:
  15910. 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) {
  15911. sceneFileToLoad = filesToLoad[i];
  15912. }
  15913. break;
  15914. }
  15915. }
  15916. // If a ".babylon" file has been provided
  15917. if (sceneFileToLoad) {
  15918. if (this.currentScene) {
  15919. this.engine.stopRenderLoop();
  15920. this.currentScene.dispose();
  15921. }
  15922. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15923. that.currentScene = newScene;
  15924. // Wait for textures and shaders to be ready
  15925. that.currentScene.executeWhenReady(function () {
  15926. // Attach camera to canvas inputs
  15927. if (that.currentScene.activeCamera) {
  15928. that.currentScene.activeCamera.attachControl(that.canvas);
  15929. }
  15930. if (that.sceneLoadedCallback) {
  15931. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15932. }
  15933. that.engine.runRenderLoop(function () {
  15934. that.renderFunction();
  15935. });
  15936. });
  15937. }, function (progress) {
  15938. if (_this.progressCallback) {
  15939. _this.progressCallback(progress);
  15940. }
  15941. });
  15942. } else {
  15943. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15944. }
  15945. }
  15946. };
  15947. FilesInput.FilesTextures = new Array();
  15948. FilesInput.FilesToLoad = new Array();
  15949. return FilesInput;
  15950. })();
  15951. BABYLON.FilesInput = FilesInput;
  15952. })(BABYLON || (BABYLON = {}));
  15953. //# sourceMappingURL=babylon.filesInput.js.map
  15954. var BABYLON;
  15955. (function (BABYLON) {
  15956. var OimoJSPlugin = (function () {
  15957. function OimoJSPlugin() {
  15958. this._registeredMeshes = [];
  15959. /**
  15960. * Update the body position according to the mesh position
  15961. * @param mesh
  15962. */
  15963. this.updateBodyPosition = function (mesh) {
  15964. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15965. var registeredMesh = this._registeredMeshes[index];
  15966. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15967. var body = registeredMesh.body.body;
  15968. mesh.computeWorldMatrix(true);
  15969. var center = mesh.getBoundingInfo().boundingBox.center;
  15970. body.setPosition(center.x, center.y, center.z);
  15971. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15972. return;
  15973. }
  15974. // Case where the parent has been updated
  15975. if (registeredMesh.mesh.parent === mesh) {
  15976. mesh.computeWorldMatrix(true);
  15977. registeredMesh.mesh.computeWorldMatrix(true);
  15978. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15979. var absoluteRotation = mesh.rotation;
  15980. body = registeredMesh.body.body;
  15981. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15982. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15983. return;
  15984. }
  15985. }
  15986. };
  15987. }
  15988. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15989. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15990. };
  15991. OimoJSPlugin.prototype.initialize = function (iterations) {
  15992. this._world = new OIMO.World();
  15993. this._world.clear();
  15994. };
  15995. OimoJSPlugin.prototype.setGravity = function (gravity) {
  15996. this._world.gravity = gravity;
  15997. };
  15998. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15999. var body = null;
  16000. this.unregisterMesh(mesh);
  16001. mesh.computeWorldMatrix(true);
  16002. switch (impostor) {
  16003. case BABYLON.PhysicsEngine.SphereImpostor:
  16004. var bbox = mesh.getBoundingInfo().boundingBox;
  16005. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16006. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16007. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16008. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16009. // The delta between the mesh position and the mesh bounding box center
  16010. var deltaPosition = mesh.position.subtract(bbox.center);
  16011. body = new OIMO.Body({
  16012. type: 'sphere',
  16013. size: [size],
  16014. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16015. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16016. move: options.mass != 0,
  16017. config: [options.mass, options.friction, options.restitution],
  16018. world: this._world
  16019. });
  16020. this._registeredMeshes.push({
  16021. mesh: mesh,
  16022. body: body,
  16023. delta: deltaPosition
  16024. });
  16025. break;
  16026. case BABYLON.PhysicsEngine.PlaneImpostor:
  16027. case BABYLON.PhysicsEngine.BoxImpostor:
  16028. bbox = mesh.getBoundingInfo().boundingBox;
  16029. var min = bbox.minimumWorld;
  16030. var max = bbox.maximumWorld;
  16031. var box = max.subtract(min);
  16032. var sizeX = this._checkWithEpsilon(box.x);
  16033. var sizeY = this._checkWithEpsilon(box.y);
  16034. var sizeZ = this._checkWithEpsilon(box.z);
  16035. // The delta between the mesh position and the mesh boudning box center
  16036. var deltaPosition = mesh.position.subtract(bbox.center);
  16037. body = new OIMO.Body({
  16038. type: 'box',
  16039. size: [sizeX, sizeY, sizeZ],
  16040. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16041. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16042. move: options.mass != 0,
  16043. config: [options.mass, options.friction, options.restitution],
  16044. world: this._world
  16045. });
  16046. this._registeredMeshes.push({
  16047. mesh: mesh,
  16048. body: body,
  16049. delta: deltaPosition
  16050. });
  16051. break;
  16052. }
  16053. return body;
  16054. };
  16055. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16056. var types = [], sizes = [], positions = [], rotations = [];
  16057. var initialMesh = parts[0].mesh;
  16058. for (var index = 0; index < parts.length; index++) {
  16059. var part = parts[index];
  16060. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16061. types.push(bodyParameters.type);
  16062. sizes.push.apply(sizes, bodyParameters.size);
  16063. positions.push.apply(positions, bodyParameters.pos);
  16064. rotations.push.apply(rotations, bodyParameters.rot);
  16065. }
  16066. var body = new OIMO.Body({
  16067. type: types,
  16068. size: sizes,
  16069. pos: positions,
  16070. rot: rotations,
  16071. move: options.mass != 0,
  16072. config: [options.mass, options.friction, options.restitution],
  16073. world: this._world
  16074. });
  16075. this._registeredMeshes.push({
  16076. mesh: initialMesh,
  16077. body: body
  16078. });
  16079. return body;
  16080. };
  16081. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16082. var bodyParameters = null;
  16083. var mesh = part.mesh;
  16084. switch (part.impostor) {
  16085. case BABYLON.PhysicsEngine.SphereImpostor:
  16086. var bbox = mesh.getBoundingInfo().boundingBox;
  16087. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16088. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16089. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16090. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16091. bodyParameters = {
  16092. type: 'sphere',
  16093. /* bug with oimo : sphere needs 3 sizes in this case */
  16094. size: [size, -1, -1],
  16095. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16096. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16097. };
  16098. break;
  16099. case BABYLON.PhysicsEngine.PlaneImpostor:
  16100. case BABYLON.PhysicsEngine.BoxImpostor:
  16101. bbox = mesh.getBoundingInfo().boundingBox;
  16102. var min = bbox.minimumWorld;
  16103. var max = bbox.maximumWorld;
  16104. var box = max.subtract(min);
  16105. var sizeX = this._checkWithEpsilon(box.x);
  16106. var sizeY = this._checkWithEpsilon(box.y);
  16107. var sizeZ = this._checkWithEpsilon(box.z);
  16108. var relativePosition = mesh.position;
  16109. bodyParameters = {
  16110. type: 'box',
  16111. size: [sizeX, sizeY, sizeZ],
  16112. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16113. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16114. };
  16115. break;
  16116. }
  16117. return bodyParameters;
  16118. };
  16119. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16120. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16121. var registeredMesh = this._registeredMeshes[index];
  16122. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16123. if (registeredMesh.body) {
  16124. this._world.removeRigidBody(registeredMesh.body.body);
  16125. this._unbindBody(registeredMesh.body);
  16126. }
  16127. this._registeredMeshes.splice(index, 1);
  16128. return;
  16129. }
  16130. }
  16131. };
  16132. OimoJSPlugin.prototype._unbindBody = function (body) {
  16133. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16134. var registeredMesh = this._registeredMeshes[index];
  16135. if (registeredMesh.body === body) {
  16136. registeredMesh.body = null;
  16137. }
  16138. }
  16139. };
  16140. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16141. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16142. var registeredMesh = this._registeredMeshes[index];
  16143. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16144. // Get object mass to have a behaviour similar to cannon.js
  16145. var mass = registeredMesh.body.body.massInfo.mass;
  16146. // The force is scaled with the mass of object
  16147. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16148. return;
  16149. }
  16150. }
  16151. };
  16152. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16153. var body1 = null, body2 = null;
  16154. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16155. var registeredMesh = this._registeredMeshes[index];
  16156. if (registeredMesh.mesh === mesh1) {
  16157. body1 = registeredMesh.body.body;
  16158. } else if (registeredMesh.mesh === mesh2) {
  16159. body2 = registeredMesh.body.body;
  16160. }
  16161. }
  16162. if (!body1 || !body2) {
  16163. return false;
  16164. }
  16165. if (!options) {
  16166. options = {};
  16167. }
  16168. new OIMO.Link({
  16169. type: options.type,
  16170. body1: body1,
  16171. body2: body2,
  16172. min: options.min,
  16173. max: options.max,
  16174. axe1: options.axe1,
  16175. axe2: options.axe2,
  16176. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16177. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16178. collision: options.collision,
  16179. spring: options.spring,
  16180. world: this._world
  16181. });
  16182. return true;
  16183. };
  16184. OimoJSPlugin.prototype.dispose = function () {
  16185. this._world.clear();
  16186. while (this._registeredMeshes.length) {
  16187. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16188. }
  16189. };
  16190. OimoJSPlugin.prototype.isSupported = function () {
  16191. return OIMO !== undefined;
  16192. };
  16193. OimoJSPlugin.prototype._getLastShape = function (body) {
  16194. var lastShape = body.shapes;
  16195. while (lastShape.next) {
  16196. lastShape = lastShape.next;
  16197. }
  16198. return lastShape;
  16199. };
  16200. OimoJSPlugin.prototype.runOneStep = function (time) {
  16201. this._world.step();
  16202. // Update the position of all registered meshes
  16203. var i = this._registeredMeshes.length;
  16204. var m;
  16205. while (i--) {
  16206. var body = this._registeredMeshes[i].body.body;
  16207. var mesh = this._registeredMeshes[i].mesh;
  16208. var delta = this._registeredMeshes[i].delta;
  16209. if (!body.sleeping) {
  16210. if (body.shapes.next) {
  16211. var parentShape = this._getLastShape(body);
  16212. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16213. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16214. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16215. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16216. if (!mesh.rotationQuaternion) {
  16217. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16218. }
  16219. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16220. mesh.computeWorldMatrix();
  16221. } else {
  16222. m = body.getMatrix();
  16223. mtx = BABYLON.Matrix.FromArray(m);
  16224. // Body position
  16225. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16226. if (!delta) {
  16227. mesh.position.x = bodyX;
  16228. mesh.position.y = bodyY;
  16229. mesh.position.z = bodyZ;
  16230. } else {
  16231. mesh.position.x = bodyX + delta.x;
  16232. mesh.position.y = bodyY + delta.y;
  16233. mesh.position.z = bodyZ + delta.z;
  16234. }
  16235. if (!mesh.rotationQuaternion) {
  16236. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16237. }
  16238. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16239. mesh.computeWorldMatrix();
  16240. }
  16241. }
  16242. }
  16243. };
  16244. return OimoJSPlugin;
  16245. })();
  16246. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16247. })(BABYLON || (BABYLON = {}));
  16248. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16249. var BABYLON;
  16250. (function (BABYLON) {
  16251. var PhysicsEngine = (function () {
  16252. function PhysicsEngine(plugin) {
  16253. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16254. }
  16255. PhysicsEngine.prototype._initialize = function (gravity) {
  16256. this._currentPlugin.initialize();
  16257. this._setGravity(gravity);
  16258. };
  16259. PhysicsEngine.prototype._runOneStep = function (delta) {
  16260. if (delta > 0.1) {
  16261. delta = 0.1;
  16262. } else if (delta <= 0) {
  16263. delta = 1.0 / 60.0;
  16264. }
  16265. this._currentPlugin.runOneStep(delta);
  16266. };
  16267. PhysicsEngine.prototype._setGravity = function (gravity) {
  16268. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16269. this._currentPlugin.setGravity(this.gravity);
  16270. };
  16271. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16272. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16273. };
  16274. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16275. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16276. };
  16277. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16278. this._currentPlugin.unregisterMesh(mesh);
  16279. };
  16280. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16281. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16282. };
  16283. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16284. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16285. };
  16286. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16287. this._currentPlugin.updateBodyPosition(mesh);
  16288. };
  16289. PhysicsEngine.prototype.dispose = function () {
  16290. this._currentPlugin.dispose();
  16291. };
  16292. PhysicsEngine.prototype.isSupported = function () {
  16293. return this._currentPlugin.isSupported();
  16294. };
  16295. PhysicsEngine.NoImpostor = 0;
  16296. PhysicsEngine.SphereImpostor = 1;
  16297. PhysicsEngine.BoxImpostor = 2;
  16298. PhysicsEngine.PlaneImpostor = 3;
  16299. PhysicsEngine.MeshImpostor = 4;
  16300. PhysicsEngine.CapsuleImpostor = 5;
  16301. PhysicsEngine.ConeImpostor = 6;
  16302. PhysicsEngine.CylinderImpostor = 7;
  16303. PhysicsEngine.ConvexHullImpostor = 8;
  16304. PhysicsEngine.Epsilon = 0.001;
  16305. return PhysicsEngine;
  16306. })();
  16307. BABYLON.PhysicsEngine = PhysicsEngine;
  16308. })(BABYLON || (BABYLON = {}));
  16309. //# sourceMappingURL=babylon.physicsEngine.js.map
  16310. var BABYLON;
  16311. (function (BABYLON) {
  16312. var serializeLight = function (light) {
  16313. var serializationObject = {};
  16314. serializationObject.name = light.name;
  16315. serializationObject.id = light.id;
  16316. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16317. if (light instanceof BABYLON.PointLight) {
  16318. serializationObject.type = 0;
  16319. serializationObject.position = light.position.asArray();
  16320. } else if (light instanceof BABYLON.DirectionalLight) {
  16321. serializationObject.type = 1;
  16322. var directionalLight = light;
  16323. serializationObject.position = directionalLight.position.asArray();
  16324. serializationObject.direction = directionalLight.direction.asArray();
  16325. } else if (light instanceof BABYLON.SpotLight) {
  16326. serializationObject.type = 2;
  16327. var spotLight = light;
  16328. serializationObject.position = spotLight.position.asArray();
  16329. serializationObject.direction = spotLight.position.asArray();
  16330. serializationObject.angle = spotLight.angle;
  16331. serializationObject.exponent = spotLight.exponent;
  16332. } else if (light instanceof BABYLON.HemisphericLight) {
  16333. serializationObject.type = 3;
  16334. var hemisphericLight = light;
  16335. serializationObject.direction = hemisphericLight.direction.asArray();
  16336. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16337. }
  16338. if (light.intensity) {
  16339. serializationObject.intensity = light.intensity;
  16340. }
  16341. serializationObject.range = light.range;
  16342. serializationObject.diffuse = light.diffuse.asArray();
  16343. serializationObject.specular = light.specular.asArray();
  16344. return serializationObject;
  16345. };
  16346. var serializeFresnelParameter = function (fresnelParameter) {
  16347. var serializationObject = {};
  16348. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16349. serializationObject.leftColor = fresnelParameter.leftColor;
  16350. serializationObject.rightColor = fresnelParameter.rightColor;
  16351. serializationObject.bias = fresnelParameter.bias;
  16352. serializationObject.power = fresnelParameter.power;
  16353. return serializationObject;
  16354. };
  16355. var serializeCamera = function (camera) {
  16356. var serializationObject = {};
  16357. serializationObject.name = camera.name;
  16358. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16359. serializationObject.id = camera.id;
  16360. serializationObject.position = camera.position.asArray();
  16361. // Parent
  16362. if (camera.parent) {
  16363. serializationObject.parentId = camera.parent.id;
  16364. }
  16365. // Target
  16366. serializationObject.rotation = camera.rotation.asArray();
  16367. // Locked target
  16368. if (camera.lockedTarget && camera.lockedTarget.id) {
  16369. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16370. }
  16371. serializationObject.fov = camera.fov;
  16372. serializationObject.minZ = camera.minZ;
  16373. serializationObject.maxZ = camera.maxZ;
  16374. serializationObject.speed = camera.speed;
  16375. serializationObject.inertia = camera.inertia;
  16376. serializationObject.checkCollisions = camera.checkCollisions;
  16377. serializationObject.applyGravity = camera.applyGravity;
  16378. if (camera.ellipsoid) {
  16379. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16380. }
  16381. // Animations
  16382. appendAnimations(camera, serializationObject);
  16383. // Layer mask
  16384. serializationObject.layerMask = camera.layerMask;
  16385. return serializationObject;
  16386. };
  16387. var appendAnimations = function (source, destination) {
  16388. if (source.animations) {
  16389. destination.animations = [];
  16390. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16391. var animation = source.animations[animationIndex];
  16392. destination.animations.push(serializeAnimation(animation));
  16393. }
  16394. }
  16395. };
  16396. var serializeAnimation = function (animation) {
  16397. var serializationObject = {};
  16398. serializationObject.name = animation.name;
  16399. serializationObject.property = animation.targetProperty;
  16400. serializationObject.framePerSecond = animation.framePerSecond;
  16401. serializationObject.dataType = animation.dataType;
  16402. serializationObject.loopBehavior = animation.loopMode;
  16403. var dataType = animation.dataType;
  16404. serializationObject.keys = [];
  16405. var keys = animation.getKeys();
  16406. for (var index = 0; index < keys.length; index++) {
  16407. var animationKey = keys[index];
  16408. var key = {};
  16409. key.frame = animationKey.frame;
  16410. switch (dataType) {
  16411. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16412. key.values = [animationKey.value];
  16413. break;
  16414. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16415. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16416. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16417. key.values = animationKey.value.asArray();
  16418. break;
  16419. }
  16420. serializationObject.keys.push(key);
  16421. }
  16422. return serializationObject;
  16423. };
  16424. var serializeMultiMaterial = function (material) {
  16425. var serializationObject = {};
  16426. serializationObject.name = material.name;
  16427. serializationObject.id = material.id;
  16428. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16429. serializationObject.materials = [];
  16430. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16431. var subMat = material.subMaterials[matIndex];
  16432. if (subMat) {
  16433. serializationObject.materials.push(subMat.id);
  16434. } else {
  16435. serializationObject.materials.push(null);
  16436. }
  16437. }
  16438. return serializationObject;
  16439. };
  16440. var serializeMaterial = function (material) {
  16441. var serializationObject = {};
  16442. serializationObject.name = material.name;
  16443. serializationObject.ambient = material.ambientColor.asArray();
  16444. serializationObject.diffuse = material.diffuseColor.asArray();
  16445. serializationObject.specular = material.specularColor.asArray();
  16446. serializationObject.specularPower = material.specularPower;
  16447. serializationObject.emissive = material.emissiveColor.asArray();
  16448. serializationObject.alpha = material.alpha;
  16449. serializationObject.id = material.id;
  16450. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16451. serializationObject.backFaceCulling = material.backFaceCulling;
  16452. if (material.diffuseTexture) {
  16453. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16454. }
  16455. if (material.diffuseFresnelParameters) {
  16456. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16457. }
  16458. if (material.ambientTexture) {
  16459. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16460. }
  16461. if (material.opacityTexture) {
  16462. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16463. }
  16464. if (material.opacityFresnelParameters) {
  16465. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16466. }
  16467. if (material.reflectionTexture) {
  16468. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16469. }
  16470. if (material.reflectionFresnelParameters) {
  16471. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16472. }
  16473. if (material.emissiveTexture) {
  16474. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16475. }
  16476. if (material.emissiveFresnelParameters) {
  16477. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16478. }
  16479. if (material.specularTexture) {
  16480. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16481. }
  16482. if (material.bumpTexture) {
  16483. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16484. }
  16485. return serializationObject;
  16486. };
  16487. var serializeTexture = function (texture) {
  16488. var serializationObject = {};
  16489. if (!texture.name) {
  16490. return null;
  16491. }
  16492. if (texture instanceof BABYLON.CubeTexture) {
  16493. serializationObject.name = texture.name;
  16494. serializationObject.hasAlpha = texture.hasAlpha;
  16495. serializationObject.level = texture.level;
  16496. serializationObject.coordinatesMode = texture.coordinatesMode;
  16497. return serializationObject;
  16498. }
  16499. if (texture instanceof BABYLON.MirrorTexture) {
  16500. var mirrorTexture = texture;
  16501. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16502. serializationObject.renderList = [];
  16503. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16504. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16505. }
  16506. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16507. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16508. var renderTargetTexture = texture;
  16509. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16510. serializationObject.renderList = [];
  16511. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16512. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16513. }
  16514. }
  16515. var regularTexture = texture;
  16516. serializationObject.name = texture.name;
  16517. serializationObject.hasAlpha = texture.hasAlpha;
  16518. serializationObject.level = texture.level;
  16519. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16520. serializationObject.coordinatesMode = texture.coordinatesMode;
  16521. serializationObject.uOffset = regularTexture.uOffset;
  16522. serializationObject.vOffset = regularTexture.vOffset;
  16523. serializationObject.uScale = regularTexture.uScale;
  16524. serializationObject.vScale = regularTexture.vScale;
  16525. serializationObject.uAng = regularTexture.uAng;
  16526. serializationObject.vAng = regularTexture.vAng;
  16527. serializationObject.wAng = regularTexture.wAng;
  16528. serializationObject.wrapU = texture.wrapU;
  16529. serializationObject.wrapV = texture.wrapV;
  16530. // Animations
  16531. appendAnimations(texture, serializationObject);
  16532. return serializationObject;
  16533. };
  16534. var serializeSkeleton = function (skeleton) {
  16535. var serializationObject = {};
  16536. serializationObject.name = skeleton.name;
  16537. serializationObject.id = skeleton.id;
  16538. serializationObject.bones = [];
  16539. for (var index = 0; index < skeleton.bones.length; index++) {
  16540. var bone = skeleton.bones[index];
  16541. var serializedBone = {
  16542. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16543. name: bone.name,
  16544. matrix: bone.getLocalMatrix().toArray()
  16545. };
  16546. serializationObject.bones.push(serializedBone);
  16547. if (bone.animations && bone.animations.length > 0) {
  16548. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16549. }
  16550. }
  16551. return serializationObject;
  16552. };
  16553. var serializeParticleSystem = function (particleSystem) {
  16554. var serializationObject = {};
  16555. serializationObject.emitterId = particleSystem.emitter.id;
  16556. serializationObject.capacity = particleSystem.getCapacity();
  16557. if (particleSystem.particleTexture) {
  16558. serializationObject.textureName = particleSystem.particleTexture.name;
  16559. }
  16560. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16561. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16562. serializationObject.minSize = particleSystem.minSize;
  16563. serializationObject.maxSize = particleSystem.maxSize;
  16564. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16565. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16566. serializationObject.emitRate = particleSystem.emitRate;
  16567. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16568. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16569. serializationObject.gravity = particleSystem.gravity.asArray();
  16570. serializationObject.direction1 = particleSystem.direction1.asArray();
  16571. serializationObject.direction2 = particleSystem.direction2.asArray();
  16572. serializationObject.color1 = particleSystem.color1.asArray();
  16573. serializationObject.color2 = particleSystem.color2.asArray();
  16574. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16575. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16576. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16577. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16578. serializationObject.blendMode = particleSystem.blendMode;
  16579. return serializationObject;
  16580. };
  16581. var serializeLensFlareSystem = function (lensFlareSystem) {
  16582. var serializationObject = {};
  16583. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16584. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16585. serializationObject.flares = [];
  16586. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16587. var flare = lensFlareSystem.lensFlares[index];
  16588. serializationObject.flares.push({
  16589. size: flare.size,
  16590. position: flare.position,
  16591. color: flare.color.asArray(),
  16592. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16593. });
  16594. }
  16595. return serializationObject;
  16596. };
  16597. var serializeShadowGenerator = function (light) {
  16598. var serializationObject = {};
  16599. var shadowGenerator = light.getShadowGenerator();
  16600. serializationObject.lightId = light.id;
  16601. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16602. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16603. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16604. serializationObject.renderList = [];
  16605. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16606. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16607. serializationObject.renderList.push(mesh.id);
  16608. }
  16609. return serializationObject;
  16610. };
  16611. var serializedGeometries = [];
  16612. var serializeGeometry = function (geometry, serializationGeometries) {
  16613. if (serializedGeometries[geometry.id]) {
  16614. return;
  16615. }
  16616. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16617. serializationGeometries.boxes.push(serializeBox(geometry));
  16618. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16619. serializationGeometries.spheres.push(serializeSphere(geometry));
  16620. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16621. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16622. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16623. serializationGeometries.toruses.push(serializeTorus(geometry));
  16624. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16625. serializationGeometries.grounds.push(serializeGround(geometry));
  16626. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16627. serializationGeometries.planes.push(serializePlane(geometry));
  16628. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16629. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16630. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16631. throw new Error("Unknow primitive type");
  16632. } else {
  16633. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16634. }
  16635. serializedGeometries[geometry.id] = true;
  16636. };
  16637. var serializeGeometryBase = function (geometry) {
  16638. var serializationObject = {};
  16639. serializationObject.id = geometry.id;
  16640. if (BABYLON.Tags.HasTags(geometry)) {
  16641. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16642. }
  16643. return serializationObject;
  16644. };
  16645. var serializeVertexData = function (vertexData) {
  16646. var serializationObject = serializeGeometryBase(vertexData);
  16647. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16648. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16649. }
  16650. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16651. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16652. }
  16653. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16654. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16655. }
  16656. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16657. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16658. }
  16659. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16660. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16661. }
  16662. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16663. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16664. serializationObject.matricesIndices._isExpanded = true;
  16665. }
  16666. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16667. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16668. }
  16669. serializationObject.indices = vertexData.getIndices();
  16670. return serializationObject;
  16671. };
  16672. var serializePrimitive = function (primitive) {
  16673. var serializationObject = serializeGeometryBase(primitive);
  16674. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16675. return serializationObject;
  16676. };
  16677. var serializeBox = function (box) {
  16678. var serializationObject = serializePrimitive(box);
  16679. serializationObject.size = box.size;
  16680. return serializationObject;
  16681. };
  16682. var serializeSphere = function (sphere) {
  16683. var serializationObject = serializePrimitive(sphere);
  16684. serializationObject.segments = sphere.segments;
  16685. serializationObject.diameter = sphere.diameter;
  16686. return serializationObject;
  16687. };
  16688. var serializeCylinder = function (cylinder) {
  16689. var serializationObject = serializePrimitive(cylinder);
  16690. serializationObject.height = cylinder.height;
  16691. serializationObject.diameterTop = cylinder.diameterTop;
  16692. serializationObject.diameterBottom = cylinder.diameterBottom;
  16693. serializationObject.tessellation = cylinder.tessellation;
  16694. return serializationObject;
  16695. };
  16696. var serializeTorus = function (torus) {
  16697. var serializationObject = serializePrimitive(torus);
  16698. serializationObject.diameter = torus.diameter;
  16699. serializationObject.thickness = torus.thickness;
  16700. serializationObject.tessellation = torus.tessellation;
  16701. return serializationObject;
  16702. };
  16703. var serializeGround = function (ground) {
  16704. var serializationObject = serializePrimitive(ground);
  16705. serializationObject.width = ground.width;
  16706. serializationObject.height = ground.height;
  16707. serializationObject.subdivisions = ground.subdivisions;
  16708. return serializationObject;
  16709. };
  16710. var serializePlane = function (plane) {
  16711. var serializationObject = serializePrimitive(plane);
  16712. serializationObject.size = plane.size;
  16713. return serializationObject;
  16714. };
  16715. var serializeTorusKnot = function (torusKnot) {
  16716. var serializationObject = serializePrimitive(torusKnot);
  16717. serializationObject.radius = torusKnot.radius;
  16718. serializationObject.tube = torusKnot.tube;
  16719. serializationObject.radialSegments = torusKnot.radialSegments;
  16720. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16721. serializationObject.p = torusKnot.p;
  16722. serializationObject.q = torusKnot.q;
  16723. return serializationObject;
  16724. };
  16725. var serializeMesh = function (mesh, serializationScene) {
  16726. var serializationObject = {};
  16727. serializationObject.name = mesh.name;
  16728. serializationObject.id = mesh.id;
  16729. if (BABYLON.Tags.HasTags(mesh)) {
  16730. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16731. }
  16732. serializationObject.position = mesh.position.asArray();
  16733. if (mesh.rotationQuaternion) {
  16734. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16735. } else if (mesh.rotation) {
  16736. serializationObject.rotation = mesh.rotation.asArray();
  16737. }
  16738. serializationObject.scaling = mesh.scaling.asArray();
  16739. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16740. serializationObject.isEnabled = mesh.isEnabled();
  16741. serializationObject.isVisible = mesh.isVisible;
  16742. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16743. serializationObject.pickable = mesh.isPickable;
  16744. serializationObject.receiveShadows = mesh.receiveShadows;
  16745. serializationObject.billboardMode = mesh.billboardMode;
  16746. serializationObject.visibility = mesh.visibility;
  16747. serializationObject.checkCollisions = mesh.checkCollisions;
  16748. // Parent
  16749. if (mesh.parent) {
  16750. serializationObject.parentId = mesh.parent.id;
  16751. }
  16752. // Geometry
  16753. var geometry = mesh._geometry;
  16754. if (geometry) {
  16755. var geometryId = geometry.id;
  16756. serializationObject.geometryId = geometryId;
  16757. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16758. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  16759. serializeGeometry(geometry, serializationScene.geometries);
  16760. }
  16761. // SubMeshes
  16762. serializationObject.subMeshes = [];
  16763. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16764. var subMesh = mesh.subMeshes[subIndex];
  16765. serializationObject.subMeshes.push({
  16766. materialIndex: subMesh.materialIndex,
  16767. verticesStart: subMesh.verticesStart,
  16768. verticesCount: subMesh.verticesCount,
  16769. indexStart: subMesh.indexStart,
  16770. indexCount: subMesh.indexCount
  16771. });
  16772. }
  16773. }
  16774. // Material
  16775. if (mesh.material) {
  16776. serializationObject.materialId = mesh.material.id;
  16777. } else {
  16778. mesh.material = null;
  16779. }
  16780. // Skeleton
  16781. if (mesh.skeleton) {
  16782. serializationObject.skeletonId = mesh.skeleton.id;
  16783. }
  16784. // Physics
  16785. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16786. serializationObject.physicsMass = mesh.getPhysicsMass();
  16787. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16788. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16789. switch (mesh.getPhysicsImpostor()) {
  16790. case BABYLON.PhysicsEngine.BoxImpostor:
  16791. serializationObject.physicsImpostor = 1;
  16792. break;
  16793. case BABYLON.PhysicsEngine.SphereImpostor:
  16794. serializationObject.physicsImpostor = 2;
  16795. break;
  16796. }
  16797. }
  16798. // Instances
  16799. serializationObject.instances = [];
  16800. for (var index = 0; index < mesh.instances.length; index++) {
  16801. var instance = mesh.instances[index];
  16802. var serializationInstance = {
  16803. name: instance.name,
  16804. position: instance.position,
  16805. rotation: instance.rotation,
  16806. rotationQuaternion: instance.rotationQuaternion,
  16807. scaling: instance.scaling
  16808. };
  16809. serializationObject.instances.push(serializationInstance);
  16810. // Animations
  16811. appendAnimations(instance, serializationInstance);
  16812. }
  16813. // Animations
  16814. appendAnimations(mesh, serializationObject);
  16815. // Layer mask
  16816. serializationObject.layerMask = mesh.layerMask;
  16817. return serializationObject;
  16818. };
  16819. var SceneSerializer = (function () {
  16820. function SceneSerializer() {
  16821. }
  16822. SceneSerializer.Serialize = function (scene) {
  16823. var serializationObject = {};
  16824. // Scene
  16825. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16826. serializationObject.autoClear = scene.autoClear;
  16827. serializationObject.clearColor = scene.clearColor.asArray();
  16828. serializationObject.ambientColor = scene.ambientColor.asArray();
  16829. serializationObject.gravity = scene.gravity.asArray();
  16830. // Fog
  16831. if (scene.fogMode && scene.fogMode !== 0) {
  16832. serializationObject.fogMode = scene.fogMode;
  16833. serializationObject.fogColor = scene.fogColor.asArray();
  16834. serializationObject.fogStart = scene.fogStart;
  16835. serializationObject.fogEnd = scene.fogEnd;
  16836. serializationObject.fogDensity = scene.fogDensity;
  16837. }
  16838. // Lights
  16839. serializationObject.lights = [];
  16840. for (var index = 0; index < scene.lights.length; index++) {
  16841. var light = scene.lights[index];
  16842. serializationObject.lights.push(serializeLight(light));
  16843. }
  16844. // Cameras
  16845. serializationObject.cameras = [];
  16846. for (index = 0; index < scene.cameras.length; index++) {
  16847. var camera = scene.cameras[index];
  16848. if (camera instanceof BABYLON.FreeCamera) {
  16849. serializationObject.cameras.push(serializeCamera(camera));
  16850. }
  16851. }
  16852. if (scene.activeCamera) {
  16853. serializationObject.activeCameraID = scene.activeCamera.id;
  16854. }
  16855. // Materials
  16856. serializationObject.materials = [];
  16857. serializationObject.multiMaterials = [];
  16858. for (index = 0; index < scene.materials.length; index++) {
  16859. var material = scene.materials[index];
  16860. if (material instanceof BABYLON.StandardMaterial) {
  16861. serializationObject.materials.push(serializeMaterial(material));
  16862. } else if (material instanceof BABYLON.MultiMaterial) {
  16863. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16864. }
  16865. }
  16866. // Skeletons
  16867. serializationObject.skeletons = [];
  16868. for (index = 0; index < scene.skeletons.length; index++) {
  16869. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16870. }
  16871. // Geometries
  16872. serializationObject.geometries = {};
  16873. serializationObject.geometries.boxes = [];
  16874. serializationObject.geometries.spheres = [];
  16875. serializationObject.geometries.cylinders = [];
  16876. serializationObject.geometries.toruses = [];
  16877. serializationObject.geometries.grounds = [];
  16878. serializationObject.geometries.planes = [];
  16879. serializationObject.geometries.torusKnots = [];
  16880. serializationObject.geometries.vertexData = [];
  16881. serializedGeometries = [];
  16882. var geometries = scene.getGeometries();
  16883. for (var index = 0; index < geometries.length; index++) {
  16884. var geometry = geometries[index];
  16885. if (geometry.isReady()) {
  16886. serializeGeometry(geometry, serializationObject.geometries);
  16887. }
  16888. }
  16889. // Meshes
  16890. serializationObject.meshes = [];
  16891. for (index = 0; index < scene.meshes.length; index++) {
  16892. var abstractMesh = scene.meshes[index];
  16893. if (abstractMesh instanceof BABYLON.Mesh) {
  16894. var mesh = abstractMesh;
  16895. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16896. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16897. }
  16898. }
  16899. }
  16900. // Particles Systems
  16901. serializationObject.particleSystems = [];
  16902. for (index = 0; index < scene.particleSystems.length; index++) {
  16903. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16904. }
  16905. // Lens flares
  16906. serializationObject.lensFlareSystems = [];
  16907. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16908. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16909. }
  16910. // Shadows
  16911. serializationObject.shadowGenerators = [];
  16912. for (index = 0; index < scene.lights.length; index++) {
  16913. light = scene.lights[index];
  16914. if (light.getShadowGenerator()) {
  16915. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16916. }
  16917. }
  16918. return serializationObject;
  16919. };
  16920. return SceneSerializer;
  16921. })();
  16922. BABYLON.SceneSerializer = SceneSerializer;
  16923. })(BABYLON || (BABYLON = {}));
  16924. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16925. var BABYLON;
  16926. (function (BABYLON) {
  16927. var SceneLoader = (function () {
  16928. function SceneLoader() {
  16929. }
  16930. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16931. get: function () {
  16932. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16933. },
  16934. set: function (value) {
  16935. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16936. },
  16937. enumerable: true,
  16938. configurable: true
  16939. });
  16940. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16941. get: function () {
  16942. return SceneLoader._ShowLoadingScreen;
  16943. },
  16944. set: function (value) {
  16945. SceneLoader._ShowLoadingScreen = value;
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16951. var dotPosition = sceneFilename.lastIndexOf(".");
  16952. var queryStringPosition = sceneFilename.indexOf("?");
  16953. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16954. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16955. var plugin = this._registeredPlugins[index];
  16956. if (plugin.extensions.indexOf(extension) !== -1) {
  16957. return plugin;
  16958. }
  16959. }
  16960. return this._registeredPlugins[this._registeredPlugins.length - 1];
  16961. };
  16962. // Public functions
  16963. SceneLoader.RegisterPlugin = function (plugin) {
  16964. plugin.extensions = plugin.extensions.toLowerCase();
  16965. SceneLoader._registeredPlugins.push(plugin);
  16966. };
  16967. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16968. var manifestChecked = function (success) {
  16969. scene.database = database;
  16970. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16971. var importMeshFromData = function (data) {
  16972. var meshes = [];
  16973. var particleSystems = [];
  16974. var skeletons = [];
  16975. try {
  16976. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16977. if (onerror) {
  16978. onerror(scene, 'unable to load the scene');
  16979. }
  16980. return;
  16981. }
  16982. } catch (e) {
  16983. if (onerror) {
  16984. onerror(scene, e);
  16985. }
  16986. return;
  16987. }
  16988. if (onsuccess) {
  16989. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16990. onsuccess(meshes, particleSystems, skeletons);
  16991. }
  16992. };
  16993. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16994. // Direct load
  16995. importMeshFromData(sceneFilename.substr(5));
  16996. return;
  16997. }
  16998. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  16999. importMeshFromData(data);
  17000. }, progressCallBack, database);
  17001. };
  17002. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17003. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17004. };
  17005. /**
  17006. * Load a scene
  17007. * @param rootUrl a string that defines the root url for scene and resources
  17008. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17009. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17010. */
  17011. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17012. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17013. };
  17014. /**
  17015. * Append a scene
  17016. * @param rootUrl a string that defines the root url for scene and resources
  17017. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17018. * @param scene is the instance of BABYLON.Scene to append to
  17019. */
  17020. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17021. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17022. var database;
  17023. if (SceneLoader.ShowLoadingScreen) {
  17024. scene.getEngine().displayLoadingUI();
  17025. }
  17026. var loadSceneFromData = function (data) {
  17027. scene.database = database;
  17028. if (!plugin.load(scene, data, rootUrl)) {
  17029. if (onerror) {
  17030. onerror(scene);
  17031. }
  17032. scene.getEngine().hideLoadingUI();
  17033. return;
  17034. }
  17035. if (onsuccess) {
  17036. onsuccess(scene);
  17037. }
  17038. if (SceneLoader.ShowLoadingScreen) {
  17039. scene.executeWhenReady(function () {
  17040. scene.getEngine().hideLoadingUI();
  17041. });
  17042. }
  17043. };
  17044. var manifestChecked = function (success) {
  17045. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17046. };
  17047. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17048. // Direct load
  17049. loadSceneFromData(sceneFilename.substr(5));
  17050. return;
  17051. }
  17052. if (rootUrl.indexOf("file:") === -1) {
  17053. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17054. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17055. } else {
  17056. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17057. }
  17058. };
  17059. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17060. SceneLoader._ShowLoadingScreen = true;
  17061. SceneLoader._registeredPlugins = new Array();
  17062. return SceneLoader;
  17063. })();
  17064. BABYLON.SceneLoader = SceneLoader;
  17065. ;
  17066. })(BABYLON || (BABYLON = {}));
  17067. //# sourceMappingURL=babylon.sceneLoader.js.map
  17068. var BABYLON;
  17069. (function (BABYLON) {
  17070. (function (Internals) {
  17071. var checkColors4 = function (colors, count) {
  17072. // Check if color3 was used
  17073. if (colors.length === count * 3) {
  17074. var colors4 = [];
  17075. for (var index = 0; index < colors.length; index += 3) {
  17076. var newIndex = (index / 3) * 4;
  17077. colors4[newIndex] = colors[index];
  17078. colors4[newIndex + 1] = colors[index + 1];
  17079. colors4[newIndex + 2] = colors[index + 2];
  17080. colors4[newIndex + 3] = 1.0;
  17081. }
  17082. return colors4;
  17083. }
  17084. return colors;
  17085. };
  17086. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17087. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17088. texture.name = parsedTexture.name;
  17089. texture.hasAlpha = parsedTexture.hasAlpha;
  17090. texture.level = parsedTexture.level;
  17091. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17092. return texture;
  17093. };
  17094. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17095. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17096. return null;
  17097. }
  17098. if (parsedTexture.isCube) {
  17099. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17100. }
  17101. var texture;
  17102. if (parsedTexture.mirrorPlane) {
  17103. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17104. texture._waitingRenderList = parsedTexture.renderList;
  17105. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17106. } else if (parsedTexture.isRenderTarget) {
  17107. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17108. texture._waitingRenderList = parsedTexture.renderList;
  17109. } else {
  17110. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17111. }
  17112. texture.name = parsedTexture.name;
  17113. texture.hasAlpha = parsedTexture.hasAlpha;
  17114. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17115. texture.level = parsedTexture.level;
  17116. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17117. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17118. texture.uOffset = parsedTexture.uOffset;
  17119. texture.vOffset = parsedTexture.vOffset;
  17120. texture.uScale = parsedTexture.uScale;
  17121. texture.vScale = parsedTexture.vScale;
  17122. texture.uAng = parsedTexture.uAng;
  17123. texture.vAng = parsedTexture.vAng;
  17124. texture.wAng = parsedTexture.wAng;
  17125. texture.wrapU = parsedTexture.wrapU;
  17126. texture.wrapV = parsedTexture.wrapV;
  17127. // Animations
  17128. if (parsedTexture.animations) {
  17129. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17130. var parsedAnimation = parsedTexture.animations[animationIndex];
  17131. texture.animations.push(parseAnimation(parsedAnimation));
  17132. }
  17133. }
  17134. return texture;
  17135. };
  17136. var parseSkeleton = function (parsedSkeleton, scene) {
  17137. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17138. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17139. var parsedBone = parsedSkeleton.bones[index];
  17140. var parentBone = null;
  17141. if (parsedBone.parentBoneIndex > -1) {
  17142. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17143. }
  17144. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17145. if (parsedBone.animation) {
  17146. bone.animations.push(parseAnimation(parsedBone.animation));
  17147. }
  17148. }
  17149. return skeleton;
  17150. };
  17151. var parseFresnelParameters = function (parsedFresnelParameters) {
  17152. var fresnelParameters = new BABYLON.FresnelParameters();
  17153. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17154. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17155. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17156. fresnelParameters.bias = parsedFresnelParameters.bias;
  17157. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17158. return fresnelParameters;
  17159. };
  17160. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17161. var material;
  17162. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17163. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17164. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17165. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17166. material.specularPower = parsedMaterial.specularPower;
  17167. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17168. material.alpha = parsedMaterial.alpha;
  17169. material.id = parsedMaterial.id;
  17170. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17171. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17172. material.wireframe = parsedMaterial.wireframe;
  17173. if (parsedMaterial.diffuseTexture) {
  17174. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17175. }
  17176. if (parsedMaterial.diffuseFresnelParameters) {
  17177. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17178. }
  17179. if (parsedMaterial.ambientTexture) {
  17180. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17181. }
  17182. if (parsedMaterial.opacityTexture) {
  17183. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17184. }
  17185. if (parsedMaterial.opacityFresnelParameters) {
  17186. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17187. }
  17188. if (parsedMaterial.reflectionTexture) {
  17189. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17190. }
  17191. if (parsedMaterial.reflectionFresnelParameters) {
  17192. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17193. }
  17194. if (parsedMaterial.emissiveTexture) {
  17195. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17196. }
  17197. if (parsedMaterial.emissiveFresnelParameters) {
  17198. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17199. }
  17200. if (parsedMaterial.specularTexture) {
  17201. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17202. }
  17203. if (parsedMaterial.bumpTexture) {
  17204. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17205. }
  17206. return material;
  17207. };
  17208. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17209. for (var index = 0; index < parsedData.materials.length; index++) {
  17210. var parsedMaterial = parsedData.materials[index];
  17211. if (parsedMaterial.id === id) {
  17212. return parseMaterial(parsedMaterial, scene, rootUrl);
  17213. }
  17214. }
  17215. return null;
  17216. };
  17217. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17218. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17219. multiMaterial.id = parsedMultiMaterial.id;
  17220. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17221. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17222. var subMatId = parsedMultiMaterial.materials[matIndex];
  17223. if (subMatId) {
  17224. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17225. } else {
  17226. multiMaterial.subMaterials.push(null);
  17227. }
  17228. }
  17229. return multiMaterial;
  17230. };
  17231. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17232. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17233. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17234. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17235. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17236. var parsedFlare = parsedLensFlareSystem.flares[index];
  17237. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17238. }
  17239. return lensFlareSystem;
  17240. };
  17241. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17242. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17243. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17244. if (parsedParticleSystem.textureName) {
  17245. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17246. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17247. }
  17248. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17249. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17250. particleSystem.minSize = parsedParticleSystem.minSize;
  17251. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17252. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17253. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17254. particleSystem.emitter = emitter;
  17255. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17256. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17257. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17258. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17259. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17260. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17261. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17262. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17263. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17264. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17265. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17266. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17267. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17268. particleSystem.start();
  17269. return particleSystem;
  17270. };
  17271. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17272. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17273. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17274. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17275. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17276. shadowGenerator.getShadowMap().renderList.push(mesh);
  17277. }
  17278. if (parsedShadowGenerator.usePoissonSampling) {
  17279. shadowGenerator.usePoissonSampling = true;
  17280. } else {
  17281. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17282. }
  17283. return shadowGenerator;
  17284. };
  17285. var parseAnimation = function (parsedAnimation) {
  17286. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17287. var dataType = parsedAnimation.dataType;
  17288. var keys = [];
  17289. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17290. var key = parsedAnimation.keys[index];
  17291. var data;
  17292. switch (dataType) {
  17293. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17294. data = key.values[0];
  17295. break;
  17296. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17297. data = BABYLON.Quaternion.FromArray(key.values);
  17298. break;
  17299. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17300. data = BABYLON.Matrix.FromArray(key.values);
  17301. break;
  17302. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17303. default:
  17304. data = BABYLON.Vector3.FromArray(key.values);
  17305. break;
  17306. }
  17307. keys.push({
  17308. frame: key.frame,
  17309. value: data
  17310. });
  17311. }
  17312. animation.setKeys(keys);
  17313. return animation;
  17314. };
  17315. var parseLight = function (parsedLight, scene) {
  17316. var light;
  17317. switch (parsedLight.type) {
  17318. case 0:
  17319. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17320. break;
  17321. case 1:
  17322. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17323. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17324. break;
  17325. case 2:
  17326. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17327. break;
  17328. case 3:
  17329. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17330. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17331. break;
  17332. }
  17333. light.id = parsedLight.id;
  17334. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17335. if (parsedLight.intensity !== undefined) {
  17336. light.intensity = parsedLight.intensity;
  17337. }
  17338. if (parsedLight.range) {
  17339. light.range = parsedLight.range;
  17340. }
  17341. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17342. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17343. if (parsedLight.excludedMeshesIds) {
  17344. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17345. }
  17346. // Parent
  17347. if (parsedLight.parentId) {
  17348. light._waitingParentId = parsedLight.parentId;
  17349. }
  17350. if (parsedLight.includedOnlyMeshesIds) {
  17351. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17352. }
  17353. // Animations
  17354. if (parsedLight.animations) {
  17355. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17356. var parsedAnimation = parsedLight.animations[animationIndex];
  17357. light.animations.push(parseAnimation(parsedAnimation));
  17358. }
  17359. }
  17360. if (parsedLight.autoAnimate) {
  17361. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17362. }
  17363. };
  17364. var parseCamera = function (parsedCamera, scene) {
  17365. var camera;
  17366. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17367. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17368. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17369. var alpha = parsedCamera.alpha;
  17370. var beta = parsedCamera.beta;
  17371. var radius = parsedCamera.radius;
  17372. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17373. var eye_space = parsedCamera.eye_space;
  17374. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17375. } else {
  17376. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17377. }
  17378. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17379. var eye_space = parsedCamera.eye_space;
  17380. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17381. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17382. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17383. } else if (parsedCamera.type === "FollowCamera") {
  17384. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17385. camera.heightOffset = parsedCamera.heightOffset;
  17386. camera.radius = parsedCamera.radius;
  17387. camera.rotationOffset = parsedCamera.rotationOffset;
  17388. if (lockedTargetMesh)
  17389. camera.target = lockedTargetMesh;
  17390. } else if (parsedCamera.type === "GamepadCamera") {
  17391. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17392. } else if (parsedCamera.type === "OculusCamera") {
  17393. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17394. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17395. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17396. } else if (parsedCamera.type === "TouchCamera") {
  17397. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17398. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17399. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17400. } else if (parsedCamera.type === "WebVRCamera") {
  17401. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17402. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17403. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17404. } else {
  17405. // Free Camera is the default value
  17406. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17407. }
  17408. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17409. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17410. camera.lockedTarget = lockedTargetMesh;
  17411. }
  17412. camera.id = parsedCamera.id;
  17413. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17414. // Parent
  17415. if (parsedCamera.parentId) {
  17416. camera._waitingParentId = parsedCamera.parentId;
  17417. }
  17418. // Target
  17419. if (parsedCamera.target) {
  17420. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17421. } else {
  17422. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17423. }
  17424. camera.fov = parsedCamera.fov;
  17425. camera.minZ = parsedCamera.minZ;
  17426. camera.maxZ = parsedCamera.maxZ;
  17427. camera.speed = parsedCamera.speed;
  17428. camera.inertia = parsedCamera.inertia;
  17429. camera.checkCollisions = parsedCamera.checkCollisions;
  17430. camera.applyGravity = parsedCamera.applyGravity;
  17431. if (parsedCamera.ellipsoid) {
  17432. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17433. }
  17434. // Animations
  17435. if (parsedCamera.animations) {
  17436. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17437. var parsedAnimation = parsedCamera.animations[animationIndex];
  17438. camera.animations.push(parseAnimation(parsedAnimation));
  17439. }
  17440. }
  17441. if (parsedCamera.autoAnimate) {
  17442. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17443. }
  17444. // Layer Mask
  17445. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17446. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17447. } else {
  17448. camera.layerMask = 0xFFFFFFFF;
  17449. }
  17450. return camera;
  17451. };
  17452. var parseGeometry = function (parsedGeometry, scene) {
  17453. var id = parsedGeometry.id;
  17454. return scene.getGeometryByID(id);
  17455. };
  17456. var parseBox = function (parsedBox, scene) {
  17457. if (parseGeometry(parsedBox, scene)) {
  17458. return null;
  17459. }
  17460. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17461. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17462. scene.pushGeometry(box, true);
  17463. return box;
  17464. };
  17465. var parseSphere = function (parsedSphere, scene) {
  17466. if (parseGeometry(parsedSphere, scene)) {
  17467. return null;
  17468. }
  17469. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17470. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17471. scene.pushGeometry(sphere, true);
  17472. return sphere;
  17473. };
  17474. var parseCylinder = function (parsedCylinder, scene) {
  17475. if (parseGeometry(parsedCylinder, scene)) {
  17476. return null;
  17477. }
  17478. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17479. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17480. scene.pushGeometry(cylinder, true);
  17481. return cylinder;
  17482. };
  17483. var parseTorus = function (parsedTorus, scene) {
  17484. if (parseGeometry(parsedTorus, scene)) {
  17485. return null;
  17486. }
  17487. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17488. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17489. scene.pushGeometry(torus, true);
  17490. return torus;
  17491. };
  17492. var parseGround = function (parsedGround, scene) {
  17493. if (parseGeometry(parsedGround, scene)) {
  17494. return null;
  17495. }
  17496. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17497. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17498. scene.pushGeometry(ground, true);
  17499. return ground;
  17500. };
  17501. var parsePlane = function (parsedPlane, scene) {
  17502. if (parseGeometry(parsedPlane, scene)) {
  17503. return null;
  17504. }
  17505. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17506. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17507. scene.pushGeometry(plane, true);
  17508. return plane;
  17509. };
  17510. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17511. if (parseGeometry(parsedTorusKnot, scene)) {
  17512. return null;
  17513. }
  17514. 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);
  17515. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17516. scene.pushGeometry(torusKnot, true);
  17517. return torusKnot;
  17518. };
  17519. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17520. if (parseGeometry(parsedVertexData, scene)) {
  17521. return null;
  17522. }
  17523. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17524. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17525. if (parsedVertexData.delayLoadingFile) {
  17526. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17527. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17528. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17529. geometry._delayInfo = [];
  17530. if (parsedVertexData.hasUVs) {
  17531. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17532. }
  17533. if (parsedVertexData.hasUVs2) {
  17534. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17535. }
  17536. if (parsedVertexData.hasColors) {
  17537. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17538. }
  17539. if (parsedVertexData.hasMatricesIndices) {
  17540. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17541. }
  17542. if (parsedVertexData.hasMatricesWeights) {
  17543. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17544. }
  17545. geometry._delayLoadingFunction = importVertexData;
  17546. } else {
  17547. importVertexData(parsedVertexData, geometry);
  17548. }
  17549. scene.pushGeometry(geometry, true);
  17550. return geometry;
  17551. };
  17552. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17553. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17554. mesh.id = parsedMesh.id;
  17555. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17556. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17557. if (parsedMesh.rotationQuaternion) {
  17558. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17559. } else if (parsedMesh.rotation) {
  17560. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17561. }
  17562. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17563. if (parsedMesh.localMatrix) {
  17564. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17565. } else if (parsedMesh.pivotMatrix) {
  17566. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17567. }
  17568. mesh.setEnabled(parsedMesh.isEnabled);
  17569. mesh.isVisible = parsedMesh.isVisible;
  17570. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17571. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17572. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17573. if (parsedMesh.applyFog !== undefined) {
  17574. mesh.applyFog = parsedMesh.applyFog;
  17575. }
  17576. if (parsedMesh.pickable !== undefined) {
  17577. mesh.isPickable = parsedMesh.pickable;
  17578. }
  17579. if (parsedMesh.alphaIndex !== undefined) {
  17580. mesh.alphaIndex = parsedMesh.alphaIndex;
  17581. }
  17582. mesh.receiveShadows = parsedMesh.receiveShadows;
  17583. mesh.billboardMode = parsedMesh.billboardMode;
  17584. if (parsedMesh.visibility !== undefined) {
  17585. mesh.visibility = parsedMesh.visibility;
  17586. }
  17587. mesh.checkCollisions = parsedMesh.checkCollisions;
  17588. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17589. // Parent
  17590. if (parsedMesh.parentId) {
  17591. mesh._waitingParentId = parsedMesh.parentId;
  17592. }
  17593. // Geometry
  17594. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17595. if (parsedMesh.delayLoadingFile) {
  17596. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17597. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17598. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17599. if (parsedMesh._binaryInfo) {
  17600. mesh._binaryInfo = parsedMesh._binaryInfo;
  17601. }
  17602. mesh._delayInfo = [];
  17603. if (parsedMesh.hasUVs) {
  17604. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17605. }
  17606. if (parsedMesh.hasUVs2) {
  17607. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17608. }
  17609. if (parsedMesh.hasColors) {
  17610. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17611. }
  17612. if (parsedMesh.hasMatricesIndices) {
  17613. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17614. }
  17615. if (parsedMesh.hasMatricesWeights) {
  17616. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17617. }
  17618. mesh._delayLoadingFunction = importGeometry;
  17619. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17620. mesh._checkDelayState();
  17621. }
  17622. } else {
  17623. importGeometry(parsedMesh, mesh);
  17624. }
  17625. // Material
  17626. if (parsedMesh.materialId) {
  17627. mesh.setMaterialByID(parsedMesh.materialId);
  17628. } else {
  17629. mesh.material = null;
  17630. }
  17631. // Skeleton
  17632. if (parsedMesh.skeletonId > -1) {
  17633. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17634. }
  17635. // Physics
  17636. if (parsedMesh.physicsImpostor) {
  17637. if (!scene.isPhysicsEnabled()) {
  17638. scene.enablePhysics();
  17639. }
  17640. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17641. }
  17642. // Animations
  17643. if (parsedMesh.animations) {
  17644. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17645. var parsedAnimation = parsedMesh.animations[animationIndex];
  17646. mesh.animations.push(parseAnimation(parsedAnimation));
  17647. }
  17648. }
  17649. if (parsedMesh.autoAnimate) {
  17650. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17651. }
  17652. // Layer Mask
  17653. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17654. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17655. } else {
  17656. mesh.layerMask = 0xFFFFFFFF;
  17657. }
  17658. // Instances
  17659. if (parsedMesh.instances) {
  17660. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17661. var parsedInstance = parsedMesh.instances[index];
  17662. var instance = mesh.createInstance(parsedInstance.name);
  17663. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17664. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17665. if (parsedInstance.rotationQuaternion) {
  17666. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17667. } else if (parsedInstance.rotation) {
  17668. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17669. }
  17670. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17671. instance.checkCollisions = mesh.checkCollisions;
  17672. if (parsedMesh.animations) {
  17673. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17674. parsedAnimation = parsedMesh.animations[animationIndex];
  17675. instance.animations.push(parseAnimation(parsedAnimation));
  17676. }
  17677. }
  17678. }
  17679. }
  17680. return mesh;
  17681. };
  17682. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17683. names = (names instanceof Array) ? names : [names];
  17684. for (var i in names) {
  17685. if (mesh.name === names[i]) {
  17686. hierarchyIds.push(mesh.id);
  17687. return true;
  17688. }
  17689. }
  17690. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17691. hierarchyIds.push(mesh.id);
  17692. return true;
  17693. }
  17694. return false;
  17695. };
  17696. var importVertexData = function (parsedVertexData, geometry) {
  17697. var vertexData = new BABYLON.VertexData();
  17698. // positions
  17699. var positions = parsedVertexData.positions;
  17700. if (positions) {
  17701. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17702. }
  17703. // normals
  17704. var normals = parsedVertexData.normals;
  17705. if (normals) {
  17706. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17707. }
  17708. // uvs
  17709. var uvs = parsedVertexData.uvs;
  17710. if (uvs) {
  17711. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17712. }
  17713. // uv2s
  17714. var uv2s = parsedVertexData.uv2s;
  17715. if (uv2s) {
  17716. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17717. }
  17718. // colors
  17719. var colors = parsedVertexData.colors;
  17720. if (colors) {
  17721. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17722. }
  17723. // matricesIndices
  17724. var matricesIndices = parsedVertexData.matricesIndices;
  17725. if (matricesIndices) {
  17726. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17727. }
  17728. // matricesWeights
  17729. var matricesWeights = parsedVertexData.matricesWeights;
  17730. if (matricesWeights) {
  17731. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17732. }
  17733. // indices
  17734. var indices = parsedVertexData.indices;
  17735. if (indices) {
  17736. vertexData.indices = indices;
  17737. }
  17738. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17739. };
  17740. var importGeometry = function (parsedGeometry, mesh) {
  17741. var scene = mesh.getScene();
  17742. // Geometry
  17743. var geometryId = parsedGeometry.geometryId;
  17744. if (geometryId) {
  17745. var geometry = scene.getGeometryByID(geometryId);
  17746. if (geometry) {
  17747. geometry.applyToMesh(mesh);
  17748. }
  17749. } else if (parsedGeometry instanceof ArrayBuffer) {
  17750. var binaryInfo = mesh._binaryInfo;
  17751. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17752. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17753. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17754. }
  17755. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17756. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17757. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17758. }
  17759. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17760. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17761. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17762. }
  17763. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17764. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17765. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17766. }
  17767. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17768. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17769. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17770. }
  17771. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17772. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17774. }
  17775. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17776. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17777. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17778. }
  17779. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17780. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17781. mesh.setIndices(indicesData);
  17782. }
  17783. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17784. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17785. mesh.subMeshes = [];
  17786. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17787. var materialIndex = subMeshesData[(i * 5) + 0];
  17788. var verticesStart = subMeshesData[(i * 5) + 1];
  17789. var verticesCount = subMeshesData[(i * 5) + 2];
  17790. var indexStart = subMeshesData[(i * 5) + 3];
  17791. var indexCount = subMeshesData[(i * 5) + 4];
  17792. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17793. }
  17794. }
  17795. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17796. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17797. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17798. if (parsedGeometry.uvs) {
  17799. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17800. }
  17801. if (parsedGeometry.uvs2) {
  17802. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17803. }
  17804. if (parsedGeometry.colors) {
  17805. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17806. }
  17807. if (parsedGeometry.matricesIndices) {
  17808. if (!parsedGeometry.matricesIndices._isExpanded) {
  17809. var floatIndices = [];
  17810. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17811. var matricesIndex = parsedGeometry.matricesIndices[i];
  17812. floatIndices.push(matricesIndex & 0x000000FF);
  17813. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17814. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17815. floatIndices.push(matricesIndex >> 24);
  17816. }
  17817. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17818. } else {
  17819. delete parsedGeometry.matricesIndices._isExpanded;
  17820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17821. }
  17822. }
  17823. if (parsedGeometry.matricesWeights) {
  17824. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17825. }
  17826. mesh.setIndices(parsedGeometry.indices);
  17827. // SubMeshes
  17828. if (parsedGeometry.subMeshes) {
  17829. mesh.subMeshes = [];
  17830. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17831. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17832. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17833. }
  17834. }
  17835. }
  17836. // Flat shading
  17837. if (mesh._shouldGenerateFlatShading) {
  17838. mesh.convertToFlatShadedMesh();
  17839. delete mesh._shouldGenerateFlatShading;
  17840. }
  17841. // Update
  17842. mesh.computeWorldMatrix(true);
  17843. // Octree
  17844. if (scene._selectionOctree) {
  17845. scene._selectionOctree.addMesh(mesh);
  17846. }
  17847. };
  17848. BABYLON.SceneLoader.RegisterPlugin({
  17849. extensions: ".babylon",
  17850. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17851. var parsedData = JSON.parse(data);
  17852. var loadedSkeletonsIds = [];
  17853. var loadedMaterialsIds = [];
  17854. var hierarchyIds = [];
  17855. for (var index = 0; index < parsedData.meshes.length; index++) {
  17856. var parsedMesh = parsedData.meshes[index];
  17857. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17858. if (meshesNames instanceof Array) {
  17859. // Remove found mesh name from list.
  17860. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17861. }
  17862. // Material ?
  17863. if (parsedMesh.materialId) {
  17864. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17865. if (!materialFound) {
  17866. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17867. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17868. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17869. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17870. var subMatId = parsedMultiMaterial.materials[matIndex];
  17871. loadedMaterialsIds.push(subMatId);
  17872. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17873. }
  17874. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17875. parseMultiMaterial(parsedMultiMaterial, scene);
  17876. materialFound = true;
  17877. break;
  17878. }
  17879. }
  17880. }
  17881. if (!materialFound) {
  17882. loadedMaterialsIds.push(parsedMesh.materialId);
  17883. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17884. }
  17885. }
  17886. // Skeleton ?
  17887. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17888. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17889. if (!skeletonAlreadyLoaded) {
  17890. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17891. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17892. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17893. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17894. loadedSkeletonsIds.push(parsedSkeleton.id);
  17895. }
  17896. }
  17897. }
  17898. }
  17899. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17900. meshes.push(mesh);
  17901. }
  17902. }
  17903. for (index = 0; index < scene.meshes.length; index++) {
  17904. var currentMesh = scene.meshes[index];
  17905. if (currentMesh._waitingParentId) {
  17906. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17907. currentMesh._waitingParentId = undefined;
  17908. }
  17909. }
  17910. // Particles
  17911. if (parsedData.particleSystems) {
  17912. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17913. var parsedParticleSystem = parsedData.particleSystems[index];
  17914. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17915. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17916. }
  17917. }
  17918. }
  17919. return true;
  17920. },
  17921. load: function (scene, data, rootUrl) {
  17922. var parsedData = JSON.parse(data);
  17923. // Scene
  17924. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17925. scene.autoClear = parsedData.autoClear;
  17926. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17927. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17928. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17929. // Fog
  17930. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17931. scene.fogMode = parsedData.fogMode;
  17932. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17933. scene.fogStart = parsedData.fogStart;
  17934. scene.fogEnd = parsedData.fogEnd;
  17935. scene.fogDensity = parsedData.fogDensity;
  17936. }
  17937. for (var index = 0; index < parsedData.lights.length; index++) {
  17938. var parsedLight = parsedData.lights[index];
  17939. parseLight(parsedLight, scene);
  17940. }
  17941. // Materials
  17942. if (parsedData.materials) {
  17943. for (index = 0; index < parsedData.materials.length; index++) {
  17944. var parsedMaterial = parsedData.materials[index];
  17945. parseMaterial(parsedMaterial, scene, rootUrl);
  17946. }
  17947. }
  17948. if (parsedData.multiMaterials) {
  17949. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17950. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17951. parseMultiMaterial(parsedMultiMaterial, scene);
  17952. }
  17953. }
  17954. // Skeletons
  17955. if (parsedData.skeletons) {
  17956. for (index = 0; index < parsedData.skeletons.length; index++) {
  17957. var parsedSkeleton = parsedData.skeletons[index];
  17958. parseSkeleton(parsedSkeleton, scene);
  17959. }
  17960. }
  17961. // Geometries
  17962. var geometries = parsedData.geometries;
  17963. if (geometries) {
  17964. // Boxes
  17965. var boxes = geometries.boxes;
  17966. if (boxes) {
  17967. for (index = 0; index < boxes.length; index++) {
  17968. var parsedBox = boxes[index];
  17969. parseBox(parsedBox, scene);
  17970. }
  17971. }
  17972. // Spheres
  17973. var spheres = geometries.spheres;
  17974. if (spheres) {
  17975. for (index = 0; index < spheres.length; index++) {
  17976. var parsedSphere = spheres[index];
  17977. parseSphere(parsedSphere, scene);
  17978. }
  17979. }
  17980. // Cylinders
  17981. var cylinders = geometries.cylinders;
  17982. if (cylinders) {
  17983. for (index = 0; index < cylinders.length; index++) {
  17984. var parsedCylinder = cylinders[index];
  17985. parseCylinder(parsedCylinder, scene);
  17986. }
  17987. }
  17988. // Toruses
  17989. var toruses = geometries.toruses;
  17990. if (toruses) {
  17991. for (index = 0; index < toruses.length; index++) {
  17992. var parsedTorus = toruses[index];
  17993. parseTorus(parsedTorus, scene);
  17994. }
  17995. }
  17996. // Grounds
  17997. var grounds = geometries.grounds;
  17998. if (grounds) {
  17999. for (index = 0; index < grounds.length; index++) {
  18000. var parsedGround = grounds[index];
  18001. parseGround(parsedGround, scene);
  18002. }
  18003. }
  18004. // Planes
  18005. var planes = geometries.planes;
  18006. if (planes) {
  18007. for (index = 0; index < planes.length; index++) {
  18008. var parsedPlane = planes[index];
  18009. parsePlane(parsedPlane, scene);
  18010. }
  18011. }
  18012. // TorusKnots
  18013. var torusKnots = geometries.torusKnots;
  18014. if (torusKnots) {
  18015. for (index = 0; index < torusKnots.length; index++) {
  18016. var parsedTorusKnot = torusKnots[index];
  18017. parseTorusKnot(parsedTorusKnot, scene);
  18018. }
  18019. }
  18020. // VertexData
  18021. var vertexData = geometries.vertexData;
  18022. if (vertexData) {
  18023. for (index = 0; index < vertexData.length; index++) {
  18024. var parsedVertexData = vertexData[index];
  18025. parseVertexData(parsedVertexData, scene, rootUrl);
  18026. }
  18027. }
  18028. }
  18029. for (index = 0; index < parsedData.meshes.length; index++) {
  18030. var parsedMesh = parsedData.meshes[index];
  18031. parseMesh(parsedMesh, scene, rootUrl);
  18032. }
  18033. for (index = 0; index < parsedData.cameras.length; index++) {
  18034. var parsedCamera = parsedData.cameras[index];
  18035. parseCamera(parsedCamera, scene);
  18036. }
  18037. if (parsedData.activeCameraID) {
  18038. scene.setActiveCameraByID(parsedData.activeCameraID);
  18039. }
  18040. for (index = 0; index < scene.cameras.length; index++) {
  18041. var camera = scene.cameras[index];
  18042. if (camera._waitingParentId) {
  18043. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18044. camera._waitingParentId = undefined;
  18045. }
  18046. }
  18047. for (index = 0; index < scene.lights.length; index++) {
  18048. var light = scene.lights[index];
  18049. if (light._waitingParentId) {
  18050. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18051. light._waitingParentId = undefined;
  18052. }
  18053. }
  18054. for (index = 0; index < scene.meshes.length; index++) {
  18055. var mesh = scene.meshes[index];
  18056. if (mesh._waitingParentId) {
  18057. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18058. mesh._waitingParentId = undefined;
  18059. }
  18060. }
  18061. // Particles Systems
  18062. if (parsedData.particleSystems) {
  18063. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18064. var parsedParticleSystem = parsedData.particleSystems[index];
  18065. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18066. }
  18067. }
  18068. // Lens flares
  18069. if (parsedData.lensFlareSystems) {
  18070. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18071. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18072. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18073. }
  18074. }
  18075. // Shadows
  18076. if (parsedData.shadowGenerators) {
  18077. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18078. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18079. parseShadowGenerator(parsedShadowGenerator, scene);
  18080. }
  18081. }
  18082. // Finish
  18083. return true;
  18084. }
  18085. });
  18086. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18087. var Internals = BABYLON.Internals;
  18088. })(BABYLON || (BABYLON = {}));
  18089. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18090. var BABYLON;
  18091. (function (BABYLON) {
  18092. // Unique ID when we import meshes from Babylon to CSG
  18093. var currentCSGMeshId = 0;
  18094. // # class Vertex
  18095. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18096. // one to provide additional features like texture coordinates and vertex
  18097. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18098. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18099. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18100. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18101. // is not used anywhere else.
  18102. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18103. var Vertex = (function () {
  18104. function Vertex(pos, normal, uv) {
  18105. this.pos = pos;
  18106. this.normal = normal;
  18107. this.uv = uv;
  18108. }
  18109. Vertex.prototype.clone = function () {
  18110. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18111. };
  18112. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18113. // orientation of a polygon is flipped.
  18114. Vertex.prototype.flip = function () {
  18115. this.normal = this.normal.scale(-1);
  18116. };
  18117. // Create a new vertex between this vertex and `other` by linearly
  18118. // interpolating all properties using a parameter of `t`. Subclasses should
  18119. // override this to interpolate additional properties.
  18120. Vertex.prototype.interpolate = function (other, t) {
  18121. 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));
  18122. };
  18123. return Vertex;
  18124. })();
  18125. // # class Plane
  18126. // Represents a plane in 3D space.
  18127. var Plane = (function () {
  18128. function Plane(normal, w) {
  18129. this.normal = normal;
  18130. this.w = w;
  18131. }
  18132. Plane.FromPoints = function (a, b, c) {
  18133. var v0 = c.subtract(a);
  18134. var v1 = b.subtract(a);
  18135. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18136. return null;
  18137. }
  18138. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18139. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18140. };
  18141. Plane.prototype.clone = function () {
  18142. return new Plane(this.normal.clone(), this.w);
  18143. };
  18144. Plane.prototype.flip = function () {
  18145. this.normal.scaleInPlace(-1);
  18146. this.w = -this.w;
  18147. };
  18148. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18149. // fragments in the appropriate lists. Coplanar polygons go into either
  18150. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18151. // respect to this plane. Polygons in front or in back of this plane go into
  18152. // either `front` or `back`.
  18153. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18154. var COPLANAR = 0;
  18155. var FRONT = 1;
  18156. var BACK = 2;
  18157. var SPANNING = 3;
  18158. // Classify each point as well as the entire polygon into one of the above
  18159. // four classes.
  18160. var polygonType = 0;
  18161. var types = [];
  18162. for (var i = 0; i < polygon.vertices.length; i++) {
  18163. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18164. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18165. polygonType |= type;
  18166. types.push(type);
  18167. }
  18168. switch (polygonType) {
  18169. case COPLANAR:
  18170. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18171. break;
  18172. case FRONT:
  18173. front.push(polygon);
  18174. break;
  18175. case BACK:
  18176. back.push(polygon);
  18177. break;
  18178. case SPANNING:
  18179. var f = [], b = [];
  18180. for (i = 0; i < polygon.vertices.length; i++) {
  18181. var j = (i + 1) % polygon.vertices.length;
  18182. var ti = types[i], tj = types[j];
  18183. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18184. if (ti != BACK)
  18185. f.push(vi);
  18186. if (ti != FRONT)
  18187. b.push(ti != BACK ? vi.clone() : vi);
  18188. if ((ti | tj) == SPANNING) {
  18189. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18190. var v = vi.interpolate(vj, t);
  18191. f.push(v);
  18192. b.push(v.clone());
  18193. }
  18194. }
  18195. if (f.length >= 3) {
  18196. var poly = new Polygon(f, polygon.shared);
  18197. if (poly.plane)
  18198. front.push(poly);
  18199. }
  18200. if (b.length >= 3) {
  18201. poly = new Polygon(b, polygon.shared);
  18202. if (poly.plane)
  18203. back.push(poly);
  18204. }
  18205. break;
  18206. }
  18207. };
  18208. Plane.EPSILON = 1e-5;
  18209. return Plane;
  18210. })();
  18211. // # class Polygon
  18212. // Represents a convex polygon. The vertices used to initialize a polygon must
  18213. // be coplanar and form a convex loop.
  18214. //
  18215. // Each convex polygon has a `shared` property, which is shared between all
  18216. // polygons that are clones of each other or were split from the same polygon.
  18217. // This can be used to define per-polygon properties (such as surface color).
  18218. var Polygon = (function () {
  18219. function Polygon(vertices, shared) {
  18220. this.vertices = vertices;
  18221. this.shared = shared;
  18222. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18223. }
  18224. Polygon.prototype.clone = function () {
  18225. var vertices = this.vertices.map(function (v) {
  18226. return v.clone();
  18227. });
  18228. return new Polygon(vertices, this.shared);
  18229. };
  18230. Polygon.prototype.flip = function () {
  18231. this.vertices.reverse().map(function (v) {
  18232. v.flip();
  18233. });
  18234. this.plane.flip();
  18235. };
  18236. return Polygon;
  18237. })();
  18238. // # class Node
  18239. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18240. // by picking a polygon to split along. That polygon (and all other coplanar
  18241. // polygons) are added directly to that node and the other polygons are added to
  18242. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18243. // no distinction between internal and leaf nodes.
  18244. var Node = (function () {
  18245. function Node(polygons) {
  18246. this.plane = null;
  18247. this.front = null;
  18248. this.back = null;
  18249. this.polygons = [];
  18250. if (polygons) {
  18251. this.build(polygons);
  18252. }
  18253. }
  18254. Node.prototype.clone = function () {
  18255. var node = new Node();
  18256. node.plane = this.plane && this.plane.clone();
  18257. node.front = this.front && this.front.clone();
  18258. node.back = this.back && this.back.clone();
  18259. node.polygons = this.polygons.map(function (p) {
  18260. return p.clone();
  18261. });
  18262. return node;
  18263. };
  18264. // Convert solid space to empty space and empty space to solid space.
  18265. Node.prototype.invert = function () {
  18266. for (var i = 0; i < this.polygons.length; i++) {
  18267. this.polygons[i].flip();
  18268. }
  18269. if (this.plane) {
  18270. this.plane.flip();
  18271. }
  18272. if (this.front) {
  18273. this.front.invert();
  18274. }
  18275. if (this.back) {
  18276. this.back.invert();
  18277. }
  18278. var temp = this.front;
  18279. this.front = this.back;
  18280. this.back = temp;
  18281. };
  18282. // Recursively remove all polygons in `polygons` that are inside this BSP
  18283. // tree.
  18284. Node.prototype.clipPolygons = function (polygons) {
  18285. if (!this.plane)
  18286. return polygons.slice();
  18287. var front = [], back = [];
  18288. for (var i = 0; i < polygons.length; i++) {
  18289. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18290. }
  18291. if (this.front) {
  18292. front = this.front.clipPolygons(front);
  18293. }
  18294. if (this.back) {
  18295. back = this.back.clipPolygons(back);
  18296. } else {
  18297. back = [];
  18298. }
  18299. return front.concat(back);
  18300. };
  18301. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18302. // `bsp`.
  18303. Node.prototype.clipTo = function (bsp) {
  18304. this.polygons = bsp.clipPolygons(this.polygons);
  18305. if (this.front)
  18306. this.front.clipTo(bsp);
  18307. if (this.back)
  18308. this.back.clipTo(bsp);
  18309. };
  18310. // Return a list of all polygons in this BSP tree.
  18311. Node.prototype.allPolygons = function () {
  18312. var polygons = this.polygons.slice();
  18313. if (this.front)
  18314. polygons = polygons.concat(this.front.allPolygons());
  18315. if (this.back)
  18316. polygons = polygons.concat(this.back.allPolygons());
  18317. return polygons;
  18318. };
  18319. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18320. // new polygons are filtered down to the bottom of the tree and become new
  18321. // nodes there. Each set of polygons is partitioned using the first polygon
  18322. // (no heuristic is used to pick a good split).
  18323. Node.prototype.build = function (polygons) {
  18324. if (!polygons.length)
  18325. return;
  18326. if (!this.plane)
  18327. this.plane = polygons[0].plane.clone();
  18328. var front = [], back = [];
  18329. for (var i = 0; i < polygons.length; i++) {
  18330. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18331. }
  18332. if (front.length) {
  18333. if (!this.front)
  18334. this.front = new Node();
  18335. this.front.build(front);
  18336. }
  18337. if (back.length) {
  18338. if (!this.back)
  18339. this.back = new Node();
  18340. this.back.build(back);
  18341. }
  18342. };
  18343. return Node;
  18344. })();
  18345. var CSG = (function () {
  18346. function CSG() {
  18347. this.polygons = new Array();
  18348. }
  18349. // Convert BABYLON.Mesh to BABYLON.CSG
  18350. CSG.FromMesh = function (mesh) {
  18351. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18352. if (mesh instanceof BABYLON.Mesh) {
  18353. mesh.computeWorldMatrix(true);
  18354. var matrix = mesh.getWorldMatrix();
  18355. var meshPosition = mesh.position.clone();
  18356. var meshRotation = mesh.rotation.clone();
  18357. var meshScaling = mesh.scaling.clone();
  18358. } else {
  18359. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18360. }
  18361. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18362. var subMeshes = mesh.subMeshes;
  18363. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18364. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18365. vertices = [];
  18366. for (var j = 0; j < 3; j++) {
  18367. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18368. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18369. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18370. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18371. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18372. vertex = new Vertex(position, normal, uv);
  18373. vertices.push(vertex);
  18374. }
  18375. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18376. // To handle the case of degenerated triangle
  18377. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18378. if (polygon.plane)
  18379. polygons.push(polygon);
  18380. }
  18381. }
  18382. var csg = CSG.FromPolygons(polygons);
  18383. csg.matrix = matrix;
  18384. csg.position = meshPosition;
  18385. csg.rotation = meshRotation;
  18386. csg.scaling = meshScaling;
  18387. currentCSGMeshId++;
  18388. return csg;
  18389. };
  18390. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18391. CSG.FromPolygons = function (polygons) {
  18392. var csg = new BABYLON.CSG();
  18393. csg.polygons = polygons;
  18394. return csg;
  18395. };
  18396. CSG.prototype.clone = function () {
  18397. var csg = new BABYLON.CSG();
  18398. csg.polygons = this.polygons.map(function (p) {
  18399. return p.clone();
  18400. });
  18401. csg.copyTransformAttributes(this);
  18402. return csg;
  18403. };
  18404. CSG.prototype.toPolygons = function () {
  18405. return this.polygons;
  18406. };
  18407. CSG.prototype.union = function (csg) {
  18408. var a = new Node(this.clone().polygons);
  18409. var b = new Node(csg.clone().polygons);
  18410. a.clipTo(b);
  18411. b.clipTo(a);
  18412. b.invert();
  18413. b.clipTo(a);
  18414. b.invert();
  18415. a.build(b.allPolygons());
  18416. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18417. };
  18418. CSG.prototype.unionInPlace = function (csg) {
  18419. var a = new Node(this.polygons);
  18420. var b = new Node(csg.polygons);
  18421. a.clipTo(b);
  18422. b.clipTo(a);
  18423. b.invert();
  18424. b.clipTo(a);
  18425. b.invert();
  18426. a.build(b.allPolygons());
  18427. this.polygons = a.allPolygons();
  18428. };
  18429. CSG.prototype.subtract = function (csg) {
  18430. var a = new Node(this.clone().polygons);
  18431. var b = new Node(csg.clone().polygons);
  18432. a.invert();
  18433. a.clipTo(b);
  18434. b.clipTo(a);
  18435. b.invert();
  18436. b.clipTo(a);
  18437. b.invert();
  18438. a.build(b.allPolygons());
  18439. a.invert();
  18440. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18441. };
  18442. CSG.prototype.subtractInPlace = function (csg) {
  18443. var a = new Node(this.polygons);
  18444. var b = new Node(csg.polygons);
  18445. a.invert();
  18446. a.clipTo(b);
  18447. b.clipTo(a);
  18448. b.invert();
  18449. b.clipTo(a);
  18450. b.invert();
  18451. a.build(b.allPolygons());
  18452. a.invert();
  18453. this.polygons = a.allPolygons();
  18454. };
  18455. CSG.prototype.intersect = function (csg) {
  18456. var a = new Node(this.clone().polygons);
  18457. var b = new Node(csg.clone().polygons);
  18458. a.invert();
  18459. b.clipTo(a);
  18460. b.invert();
  18461. a.clipTo(b);
  18462. b.clipTo(a);
  18463. a.build(b.allPolygons());
  18464. a.invert();
  18465. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18466. };
  18467. CSG.prototype.intersectInPlace = function (csg) {
  18468. var a = new Node(this.polygons);
  18469. var b = new Node(csg.polygons);
  18470. a.invert();
  18471. b.clipTo(a);
  18472. b.invert();
  18473. a.clipTo(b);
  18474. b.clipTo(a);
  18475. a.build(b.allPolygons());
  18476. a.invert();
  18477. this.polygons = a.allPolygons();
  18478. };
  18479. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18480. // not modified.
  18481. CSG.prototype.inverse = function () {
  18482. var csg = this.clone();
  18483. csg.inverseInPlace();
  18484. return csg;
  18485. };
  18486. CSG.prototype.inverseInPlace = function () {
  18487. this.polygons.map(function (p) {
  18488. p.flip();
  18489. });
  18490. };
  18491. // This is used to keep meshes transformations so they can be restored
  18492. // when we build back a Babylon Mesh
  18493. // NB : All CSG operations are performed in world coordinates
  18494. CSG.prototype.copyTransformAttributes = function (csg) {
  18495. this.matrix = csg.matrix;
  18496. this.position = csg.position;
  18497. this.rotation = csg.rotation;
  18498. this.scaling = csg.scaling;
  18499. return this;
  18500. };
  18501. // Build Raw mesh from CSG
  18502. // Coordinates here are in world space
  18503. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18504. var matrix = this.matrix.clone();
  18505. matrix.invert();
  18506. 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;
  18507. if (keepSubMeshes) {
  18508. // Sort Polygons, since subMeshes are indices range
  18509. polygons.sort(function (a, b) {
  18510. if (a.shared.meshId === b.shared.meshId) {
  18511. return a.shared.subMeshId - b.shared.subMeshId;
  18512. } else {
  18513. return a.shared.meshId - b.shared.meshId;
  18514. }
  18515. });
  18516. }
  18517. for (var i = 0, il = polygons.length; i < il; i++) {
  18518. polygon = polygons[i];
  18519. // Building SubMeshes
  18520. if (!subMesh_dict[polygon.shared.meshId]) {
  18521. subMesh_dict[polygon.shared.meshId] = {};
  18522. }
  18523. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18524. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18525. indexStart: +Infinity,
  18526. indexEnd: -Infinity,
  18527. materialIndex: polygon.shared.materialIndex
  18528. };
  18529. }
  18530. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18531. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18532. polygonIndices[0] = 0;
  18533. polygonIndices[1] = j - 1;
  18534. polygonIndices[2] = j;
  18535. for (var k = 0; k < 3; k++) {
  18536. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18537. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18538. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18539. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18540. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18541. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18542. // Check if 2 points can be merged
  18543. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  18544. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18545. uvs.push(uv.x, uv.y);
  18546. normals.push(normal.x, normal.y, normal.z);
  18547. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18548. }
  18549. indices.push(vertex_idx);
  18550. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18551. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18552. currentIndex++;
  18553. }
  18554. }
  18555. }
  18556. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18557. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18558. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18559. mesh.setIndices(indices);
  18560. if (keepSubMeshes) {
  18561. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18562. var materialIndexOffset = 0, materialMaxIndex;
  18563. mesh.subMeshes.length = 0;
  18564. for (var m in subMesh_dict) {
  18565. materialMaxIndex = -1;
  18566. for (var sm in subMesh_dict[m]) {
  18567. subMesh_obj = subMesh_dict[m][sm];
  18568. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18569. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18570. }
  18571. materialIndexOffset += ++materialMaxIndex;
  18572. }
  18573. }
  18574. return mesh;
  18575. };
  18576. // Build Mesh from CSG taking material and transforms into account
  18577. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18578. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18579. mesh.material = material;
  18580. mesh.position.copyFrom(this.position);
  18581. mesh.rotation.copyFrom(this.rotation);
  18582. mesh.scaling.copyFrom(this.scaling);
  18583. mesh.computeWorldMatrix(true);
  18584. return mesh;
  18585. };
  18586. return CSG;
  18587. })();
  18588. BABYLON.CSG = CSG;
  18589. })(BABYLON || (BABYLON = {}));
  18590. //# sourceMappingURL=babylon.csg.js.map
  18591. var BABYLON;
  18592. (function (BABYLON) {
  18593. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18594. __extends(OculusDistortionCorrectionPostProcess, _super);
  18595. //ANY
  18596. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18597. var _this = this;
  18598. _super.call(this, name, "oculusDistortionCorrection", [
  18599. 'LensCenter',
  18600. 'Scale',
  18601. 'ScaleIn',
  18602. 'HmdWarpParam'
  18603. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18604. this._isRightEye = isRightEye;
  18605. this._distortionFactors = cameraSettings.DistortionK;
  18606. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18607. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18608. this.onSizeChanged = function () {
  18609. _this.aspectRatio = _this.width * .5 / _this.height;
  18610. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18611. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18612. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18613. };
  18614. this.onApply = function (effect) {
  18615. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18616. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18617. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18618. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18619. };
  18620. }
  18621. return OculusDistortionCorrectionPostProcess;
  18622. })(BABYLON.PostProcess);
  18623. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18624. })(BABYLON || (BABYLON = {}));
  18625. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18626. // Mainly based on these 2 articles :
  18627. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  18628. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18629. var BABYLON;
  18630. (function (BABYLON) {
  18631. (function (JoystickAxis) {
  18632. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18633. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18634. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18635. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18636. var JoystickAxis = BABYLON.JoystickAxis;
  18637. var VirtualJoystick = (function () {
  18638. function VirtualJoystick(leftJoystick) {
  18639. var _this = this;
  18640. if (leftJoystick) {
  18641. this._leftJoystick = true;
  18642. } else {
  18643. this._leftJoystick = false;
  18644. }
  18645. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18646. VirtualJoystick._globalJoystickIndex++;
  18647. // By default left & right arrow keys are moving the X
  18648. // and up & down keys are moving the Y
  18649. this._axisTargetedByLeftAndRight = 0 /* X */;
  18650. this._axisTargetedByUpAndDown = 1 /* Y */;
  18651. this.reverseLeftRight = false;
  18652. this.reverseUpDown = false;
  18653. // collections of pointers
  18654. this._touches = new BABYLON.VirtualJoystick.Collection();
  18655. this.deltaPosition = BABYLON.Vector3.Zero();
  18656. this._joystickSensibility = 25;
  18657. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18658. this._rotationSpeed = 25;
  18659. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18660. this._rotateOnAxisRelativeToMesh = false;
  18661. // injecting a canvas element on top of the canvas 3D game
  18662. if (!VirtualJoystick.vjCanvas) {
  18663. window.addEventListener("resize", function () {
  18664. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18665. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18666. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18667. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18668. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18669. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18670. }, false);
  18671. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18672. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18673. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18674. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18675. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18676. VirtualJoystick.vjCanvas.style.width = "100%";
  18677. VirtualJoystick.vjCanvas.style.height = "100%";
  18678. VirtualJoystick.vjCanvas.style.position = "absolute";
  18679. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18680. VirtualJoystick.vjCanvas.style.top = "0px";
  18681. VirtualJoystick.vjCanvas.style.left = "0px";
  18682. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18683. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18684. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18685. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18686. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18687. document.body.appendChild(VirtualJoystick.vjCanvas);
  18688. }
  18689. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18690. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18691. this.pressed = false;
  18692. // default joystick color
  18693. this._joystickColor = "cyan";
  18694. this._joystickPointerID = -1;
  18695. // current joystick position
  18696. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18697. // origin joystick position
  18698. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18699. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18700. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18701. _this._onPointerDown(evt);
  18702. }, false);
  18703. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18704. _this._onPointerMove(evt);
  18705. }, false);
  18706. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18707. _this._onPointerUp(evt);
  18708. }, false);
  18709. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18710. _this._onPointerUp(evt);
  18711. }, false);
  18712. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18713. evt.preventDefault(); // Disables system menu
  18714. }, false);
  18715. requestAnimationFrame(function () {
  18716. _this._drawVirtualJoystick();
  18717. });
  18718. }
  18719. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18720. this._joystickSensibility = newJoystickSensibility;
  18721. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18722. };
  18723. VirtualJoystick.prototype._onPointerDown = function (e) {
  18724. var positionOnScreenCondition;
  18725. e.preventDefault();
  18726. if (this._leftJoystick === true) {
  18727. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18728. } else {
  18729. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18730. }
  18731. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18732. // First contact will be dedicated to the virtual joystick
  18733. this._joystickPointerID = e.pointerId;
  18734. this._joystickPointerStartPos.x = e.clientX;
  18735. this._joystickPointerStartPos.y = e.clientY;
  18736. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18737. this._deltaJoystickVector.x = 0;
  18738. this._deltaJoystickVector.y = 0;
  18739. this.pressed = true;
  18740. this._touches.add(e.pointerId.toString(), e);
  18741. } else {
  18742. // You can only trigger the action buttons with a joystick declared
  18743. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18744. this._action();
  18745. this._touches.add(e.pointerId.toString(), e);
  18746. }
  18747. }
  18748. };
  18749. VirtualJoystick.prototype._onPointerMove = function (e) {
  18750. // If the current pointer is the one associated to the joystick (first touch contact)
  18751. if (this._joystickPointerID == e.pointerId) {
  18752. this._joystickPointerPos.x = e.clientX;
  18753. this._joystickPointerPos.y = e.clientY;
  18754. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18755. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18756. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18757. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18758. switch (this._axisTargetedByLeftAndRight) {
  18759. case 0 /* X */:
  18760. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18761. break;
  18762. case 1 /* Y */:
  18763. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18764. break;
  18765. case 2 /* Z */:
  18766. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18767. break;
  18768. }
  18769. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18770. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18771. switch (this._axisTargetedByUpAndDown) {
  18772. case 0 /* X */:
  18773. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18774. break;
  18775. case 1 /* Y */:
  18776. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18777. break;
  18778. case 2 /* Z */:
  18779. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18780. break;
  18781. }
  18782. } else {
  18783. if (this._touches.item(e.pointerId.toString())) {
  18784. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18785. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18786. }
  18787. }
  18788. };
  18789. VirtualJoystick.prototype._onPointerUp = function (e) {
  18790. this._clearCanvas();
  18791. if (this._joystickPointerID == e.pointerId) {
  18792. this._joystickPointerID = -1;
  18793. this.pressed = false;
  18794. }
  18795. this._deltaJoystickVector.x = 0;
  18796. this._deltaJoystickVector.y = 0;
  18797. this._touches.remove(e.pointerId.toString());
  18798. };
  18799. /**
  18800. * Change the color of the virtual joystick
  18801. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18802. */
  18803. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18804. this._joystickColor = newColor;
  18805. };
  18806. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18807. this._action = action;
  18808. };
  18809. // Define which axis you'd like to control for left & right
  18810. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18811. switch (axis) {
  18812. case 0 /* X */:
  18813. case 1 /* Y */:
  18814. case 2 /* Z */:
  18815. this._axisTargetedByLeftAndRight = axis;
  18816. break;
  18817. default:
  18818. this._axisTargetedByLeftAndRight = 0 /* X */;
  18819. break;
  18820. }
  18821. };
  18822. // Define which axis you'd like to control for up & down
  18823. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18824. switch (axis) {
  18825. case 0 /* X */:
  18826. case 1 /* Y */:
  18827. case 2 /* Z */:
  18828. this._axisTargetedByUpAndDown = axis;
  18829. break;
  18830. default:
  18831. this._axisTargetedByUpAndDown = 1 /* Y */;
  18832. break;
  18833. }
  18834. };
  18835. VirtualJoystick.prototype._clearCanvas = function () {
  18836. if (this._leftJoystick) {
  18837. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18838. } else {
  18839. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18840. }
  18841. };
  18842. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18843. var _this = this;
  18844. if (this.pressed) {
  18845. this._clearCanvas();
  18846. this._touches.forEach(function (touch) {
  18847. if (touch.pointerId === _this._joystickPointerID) {
  18848. VirtualJoystick.vjCanvasContext.beginPath();
  18849. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18850. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18851. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18852. VirtualJoystick.vjCanvasContext.stroke();
  18853. VirtualJoystick.vjCanvasContext.beginPath();
  18854. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18855. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18856. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18857. VirtualJoystick.vjCanvasContext.stroke();
  18858. VirtualJoystick.vjCanvasContext.beginPath();
  18859. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18860. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18861. VirtualJoystick.vjCanvasContext.stroke();
  18862. } else {
  18863. VirtualJoystick.vjCanvasContext.beginPath();
  18864. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18865. VirtualJoystick.vjCanvasContext.beginPath();
  18866. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18867. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18868. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18869. VirtualJoystick.vjCanvasContext.stroke();
  18870. }
  18871. ;
  18872. });
  18873. }
  18874. requestAnimationFrame(function () {
  18875. _this._drawVirtualJoystick();
  18876. });
  18877. };
  18878. VirtualJoystick.prototype.releaseCanvas = function () {
  18879. if (VirtualJoystick.vjCanvas) {
  18880. document.body.removeChild(VirtualJoystick.vjCanvas);
  18881. VirtualJoystick.vjCanvas = null;
  18882. }
  18883. };
  18884. VirtualJoystick._globalJoystickIndex = 0;
  18885. return VirtualJoystick;
  18886. })();
  18887. BABYLON.VirtualJoystick = VirtualJoystick;
  18888. })(BABYLON || (BABYLON = {}));
  18889. var BABYLON;
  18890. (function (BABYLON) {
  18891. (function (VirtualJoystick) {
  18892. var Collection = (function () {
  18893. function Collection() {
  18894. this._count = 0;
  18895. this._collection = new Array();
  18896. }
  18897. Collection.prototype.Count = function () {
  18898. return this._count;
  18899. };
  18900. Collection.prototype.add = function (key, item) {
  18901. if (this._collection[key] != undefined) {
  18902. return undefined;
  18903. }
  18904. this._collection[key] = item;
  18905. return ++this._count;
  18906. };
  18907. Collection.prototype.remove = function (key) {
  18908. if (this._collection[key] == undefined) {
  18909. return undefined;
  18910. }
  18911. delete this._collection[key];
  18912. return --this._count;
  18913. };
  18914. Collection.prototype.item = function (key) {
  18915. return this._collection[key];
  18916. };
  18917. Collection.prototype.forEach = function (block) {
  18918. var key;
  18919. for (key in this._collection) {
  18920. if (this._collection.hasOwnProperty(key)) {
  18921. block(this._collection[key]);
  18922. }
  18923. }
  18924. };
  18925. return Collection;
  18926. })();
  18927. VirtualJoystick.Collection = Collection;
  18928. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18929. var VirtualJoystick = BABYLON.VirtualJoystick;
  18930. })(BABYLON || (BABYLON = {}));
  18931. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18932. var BABYLON;
  18933. (function (BABYLON) {
  18934. var OculusRiftDevKit2013_Metric = {
  18935. HResolution: 1280,
  18936. VResolution: 800,
  18937. HScreenSize: 0.149759993,
  18938. VScreenSize: 0.0935999975,
  18939. VScreenCenter: 0.0467999987,
  18940. EyeToScreenDistance: 0.0410000011,
  18941. LensSeparationDistance: 0.0635000020,
  18942. InterpupillaryDistance: 0.0640000030,
  18943. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18944. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18945. PostProcessScaleFactor: 1.714605507808412,
  18946. LensCenterOffset: 0.151976421
  18947. };
  18948. var _OculusInnerCamera = (function (_super) {
  18949. __extends(_OculusInnerCamera, _super);
  18950. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18951. _super.call(this, name, position, scene);
  18952. this._workMatrix = new BABYLON.Matrix();
  18953. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18954. // Constants
  18955. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18956. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18957. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18958. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18959. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18960. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18961. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18962. // Postprocess
  18963. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18964. }
  18965. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  18966. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18967. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18968. return this._projectionMatrix;
  18969. };
  18970. _OculusInnerCamera.prototype._getViewMatrix = function () {
  18971. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18972. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18973. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18974. // Computing target and final matrix
  18975. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18976. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18977. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18978. return this._viewMatrix;
  18979. };
  18980. return _OculusInnerCamera;
  18981. })(BABYLON.FreeCamera);
  18982. var OculusCamera = (function (_super) {
  18983. __extends(OculusCamera, _super);
  18984. function OculusCamera(name, position, scene) {
  18985. _super.call(this, name, position, scene);
  18986. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  18987. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  18988. this.subCameras.push(this._leftCamera);
  18989. this.subCameras.push(this._rightCamera);
  18990. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18991. }
  18992. OculusCamera.prototype._update = function () {
  18993. this._leftCamera.position.copyFrom(this.position);
  18994. this._rightCamera.position.copyFrom(this.position);
  18995. this._updateCamera(this._leftCamera);
  18996. this._updateCamera(this._rightCamera);
  18997. _super.prototype._update.call(this);
  18998. };
  18999. OculusCamera.prototype._updateCamera = function (camera) {
  19000. camera.minZ = this.minZ;
  19001. camera.maxZ = this.maxZ;
  19002. camera.rotation.x = this.rotation.x;
  19003. camera.rotation.y = this.rotation.y;
  19004. camera.rotation.z = this.rotation.z;
  19005. };
  19006. // Oculus events
  19007. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19008. var yaw = evt.alpha / 180 * Math.PI;
  19009. var pitch = evt.beta / 180 * Math.PI;
  19010. var roll = evt.gamma / 180 * Math.PI;
  19011. if (!this._offsetOrientation) {
  19012. this._offsetOrientation = {
  19013. yaw: yaw,
  19014. pitch: pitch,
  19015. roll: roll
  19016. };
  19017. return;
  19018. } else {
  19019. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19020. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19021. this.rotation.z += this._offsetOrientation.roll - roll;
  19022. this._offsetOrientation.yaw = yaw;
  19023. this._offsetOrientation.pitch = pitch;
  19024. this._offsetOrientation.roll = roll;
  19025. }
  19026. };
  19027. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19028. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19029. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19030. };
  19031. OculusCamera.prototype.detachControl = function (element) {
  19032. _super.prototype.detachControl.call(this, element);
  19033. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19034. };
  19035. return OculusCamera;
  19036. })(BABYLON.FreeCamera);
  19037. BABYLON.OculusCamera = OculusCamera;
  19038. })(BABYLON || (BABYLON = {}));
  19039. //# sourceMappingURL=babylon.oculusCamera.js.map
  19040. var BABYLON;
  19041. (function (BABYLON) {
  19042. var OculusRiftDevKit2013_Metric = {
  19043. HResolution: 1280,
  19044. VResolution: 800,
  19045. HScreenSize: 0.149759993,
  19046. VScreenSize: 0.0935999975,
  19047. VScreenCenter: 0.0467999987,
  19048. EyeToScreenDistance: 0.0410000011,
  19049. LensSeparationDistance: 0.0635000020,
  19050. InterpupillaryDistance: 0.0640000030,
  19051. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19052. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19053. PostProcessScaleFactor: 1.714605507808412,
  19054. LensCenterOffset: 0.151976421
  19055. };
  19056. var _OculusInnerGamepadCamera = (function (_super) {
  19057. __extends(_OculusInnerGamepadCamera, _super);
  19058. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19059. _super.call(this, name, position, scene);
  19060. this._workMatrix = new BABYLON.Matrix();
  19061. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19062. // Constants
  19063. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19064. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19065. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19066. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19067. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19068. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19069. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19070. // Postprocess
  19071. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19072. }
  19073. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19074. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19075. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19076. return this._projectionMatrix;
  19077. };
  19078. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19079. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19080. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19081. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19082. // Computing target and final matrix
  19083. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19084. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19085. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19086. return this._viewMatrix;
  19087. };
  19088. return _OculusInnerGamepadCamera;
  19089. })(BABYLON.FreeCamera);
  19090. var OculusGamepadCamera = (function (_super) {
  19091. __extends(OculusGamepadCamera, _super);
  19092. function OculusGamepadCamera(name, position, scene) {
  19093. var _this = this;
  19094. _super.call(this, name, position, scene);
  19095. this.angularSensibility = 200;
  19096. this.moveSensibility = 75;
  19097. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19098. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19099. this.subCameras.push(this._leftCamera);
  19100. this.subCameras.push(this._rightCamera);
  19101. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19102. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19103. _this._onNewGameConnected(gamepad);
  19104. });
  19105. }
  19106. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19107. // Only the first gamepad can control the camera
  19108. if (gamepad.index === 0) {
  19109. this._gamepad = gamepad;
  19110. }
  19111. };
  19112. OculusGamepadCamera.prototype._update = function () {
  19113. this._leftCamera.position.copyFrom(this.position);
  19114. this._rightCamera.position.copyFrom(this.position);
  19115. this._updateCamera(this._leftCamera);
  19116. this._updateCamera(this._rightCamera);
  19117. _super.prototype._update.call(this);
  19118. };
  19119. OculusGamepadCamera.prototype._checkInputs = function () {
  19120. if (!this._gamepad) {
  19121. return;
  19122. }
  19123. var LSValues = this._gamepad.leftStick;
  19124. var normalizedLX = LSValues.x / this.moveSensibility;
  19125. var normalizedLY = LSValues.y / this.moveSensibility;
  19126. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19127. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19128. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19129. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19130. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19131. };
  19132. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19133. camera.minZ = this.minZ;
  19134. camera.maxZ = this.maxZ;
  19135. camera.rotation.x = this.rotation.x;
  19136. camera.rotation.y = this.rotation.y;
  19137. camera.rotation.z = this.rotation.z;
  19138. };
  19139. // Oculus events
  19140. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19141. var yaw = evt.alpha / 180 * Math.PI;
  19142. var pitch = evt.beta / 180 * Math.PI;
  19143. var roll = evt.gamma / 180 * Math.PI;
  19144. if (!this._offsetOrientation) {
  19145. this._offsetOrientation = {
  19146. yaw: yaw,
  19147. pitch: pitch,
  19148. roll: roll
  19149. };
  19150. return;
  19151. } else {
  19152. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19153. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19154. this.rotation.z += this._offsetOrientation.roll - roll;
  19155. this._offsetOrientation.yaw = yaw;
  19156. this._offsetOrientation.pitch = pitch;
  19157. this._offsetOrientation.roll = roll;
  19158. }
  19159. };
  19160. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19161. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19162. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19163. };
  19164. OculusGamepadCamera.prototype.detachControl = function (element) {
  19165. _super.prototype.detachControl.call(this, element);
  19166. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19167. };
  19168. OculusGamepadCamera.prototype.dispose = function () {
  19169. this._gamepads.dispose();
  19170. _super.prototype.dispose.call(this);
  19171. };
  19172. return OculusGamepadCamera;
  19173. })(BABYLON.FreeCamera);
  19174. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19175. })(BABYLON || (BABYLON = {}));
  19176. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19177. var BABYLON;
  19178. (function (BABYLON) {
  19179. // We're mainly based on the logic defined into the FreeCamera code
  19180. var VirtualJoysticksCamera = (function (_super) {
  19181. __extends(VirtualJoysticksCamera, _super);
  19182. function VirtualJoysticksCamera(name, position, scene) {
  19183. _super.call(this, name, position, scene);
  19184. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19185. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19186. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19187. this._leftjoystick.setJoystickSensibility(0.15);
  19188. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19189. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19190. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19191. this._rightjoystick.reverseUpDown = true;
  19192. this._rightjoystick.setJoystickSensibility(0.05);
  19193. this._rightjoystick.setJoystickColor("yellow");
  19194. }
  19195. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19196. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19197. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19198. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19199. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19200. if (!this._leftjoystick.pressed) {
  19201. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19202. }
  19203. if (!this._rightjoystick.pressed) {
  19204. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19205. }
  19206. };
  19207. VirtualJoysticksCamera.prototype.dispose = function () {
  19208. this._leftjoystick.releaseCanvas();
  19209. _super.prototype.dispose.call(this);
  19210. };
  19211. return VirtualJoysticksCamera;
  19212. })(BABYLON.FreeCamera);
  19213. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19214. })(BABYLON || (BABYLON = {}));
  19215. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19216. var BABYLON;
  19217. (function (BABYLON) {
  19218. var ShaderMaterial = (function (_super) {
  19219. __extends(ShaderMaterial, _super);
  19220. function ShaderMaterial(name, scene, shaderPath, options) {
  19221. _super.call(this, name, scene);
  19222. this._textures = new Array();
  19223. this._floats = new Array();
  19224. this._floatsArrays = {};
  19225. this._colors3 = new Array();
  19226. this._colors4 = new Array();
  19227. this._vectors2 = new Array();
  19228. this._vectors3 = new Array();
  19229. this._matrices = new Array();
  19230. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19231. this._shaderPath = shaderPath;
  19232. options.needAlphaBlending = options.needAlphaBlending || false;
  19233. options.needAlphaTesting = options.needAlphaTesting || false;
  19234. options.attributes = options.attributes || ["position", "normal", "uv"];
  19235. options.uniforms = options.uniforms || ["worldViewProjection"];
  19236. options.samplers = options.samplers || [];
  19237. this._options = options;
  19238. }
  19239. ShaderMaterial.prototype.needAlphaBlending = function () {
  19240. return this._options.needAlphaBlending;
  19241. };
  19242. ShaderMaterial.prototype.needAlphaTesting = function () {
  19243. return this._options.needAlphaTesting;
  19244. };
  19245. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19246. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19247. this._options.uniforms.push(uniformName);
  19248. }
  19249. };
  19250. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19251. if (this._options.samplers.indexOf(name) === -1) {
  19252. this._options.samplers.push(name);
  19253. }
  19254. this._textures[name] = texture;
  19255. return this;
  19256. };
  19257. ShaderMaterial.prototype.setFloat = function (name, value) {
  19258. this._checkUniform(name);
  19259. this._floats[name] = value;
  19260. return this;
  19261. };
  19262. ShaderMaterial.prototype.setFloats = function (name, value) {
  19263. this._checkUniform(name);
  19264. this._floatsArrays[name] = value;
  19265. return this;
  19266. };
  19267. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19268. this._checkUniform(name);
  19269. this._colors3[name] = value;
  19270. return this;
  19271. };
  19272. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19273. this._checkUniform(name);
  19274. this._colors4[name] = value;
  19275. return this;
  19276. };
  19277. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19278. this._checkUniform(name);
  19279. this._vectors2[name] = value;
  19280. return this;
  19281. };
  19282. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19283. this._checkUniform(name);
  19284. this._vectors3[name] = value;
  19285. return this;
  19286. };
  19287. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19288. this._checkUniform(name);
  19289. this._matrices[name] = value;
  19290. return this;
  19291. };
  19292. ShaderMaterial.prototype.isReady = function () {
  19293. var scene = this.getScene();
  19294. var engine = scene.getEngine();
  19295. if (!this.checkReadyOnEveryCall) {
  19296. if (this._renderId === scene.getRenderId()) {
  19297. return true;
  19298. }
  19299. }
  19300. var previousEffect = this._effect;
  19301. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19302. if (!this._effect.isReady()) {
  19303. return false;
  19304. }
  19305. if (previousEffect !== this._effect) {
  19306. scene.resetCachedMaterial();
  19307. }
  19308. this._renderId = scene.getRenderId();
  19309. return true;
  19310. };
  19311. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19312. var scene = this.getScene();
  19313. if (this._options.uniforms.indexOf("world") !== -1) {
  19314. this._effect.setMatrix("world", world);
  19315. }
  19316. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19317. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19318. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19319. }
  19320. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19321. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19322. }
  19323. };
  19324. ShaderMaterial.prototype.bind = function (world) {
  19325. // Std values
  19326. this.bindOnlyWorldMatrix(world);
  19327. if (this.getScene().getCachedMaterial() !== this) {
  19328. if (this._options.uniforms.indexOf("view") !== -1) {
  19329. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19330. }
  19331. if (this._options.uniforms.indexOf("projection") !== -1) {
  19332. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19333. }
  19334. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19335. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19336. }
  19337. for (var name in this._textures) {
  19338. this._effect.setTexture(name, this._textures[name]);
  19339. }
  19340. for (name in this._floats) {
  19341. this._effect.setFloat(name, this._floats[name]);
  19342. }
  19343. for (name in this._floatsArrays) {
  19344. this._effect.setArray(name, this._floatsArrays[name]);
  19345. }
  19346. for (name in this._colors3) {
  19347. this._effect.setColor3(name, this._colors3[name]);
  19348. }
  19349. for (name in this._colors4) {
  19350. var color = this._colors4[name];
  19351. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19352. }
  19353. for (name in this._vectors2) {
  19354. this._effect.setVector2(name, this._vectors2[name]);
  19355. }
  19356. for (name in this._vectors3) {
  19357. this._effect.setVector3(name, this._vectors3[name]);
  19358. }
  19359. for (name in this._matrices) {
  19360. this._effect.setMatrix(name, this._matrices[name]);
  19361. }
  19362. }
  19363. _super.prototype.bind.call(this, world, null);
  19364. };
  19365. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19366. for (var name in this._textures) {
  19367. this._textures[name].dispose();
  19368. }
  19369. this._textures = [];
  19370. _super.prototype.dispose.call(this, forceDisposeEffect);
  19371. };
  19372. return ShaderMaterial;
  19373. })(BABYLON.Material);
  19374. BABYLON.ShaderMaterial = ShaderMaterial;
  19375. })(BABYLON || (BABYLON = {}));
  19376. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19377. var BABYLON;
  19378. (function (BABYLON) {
  19379. var VertexData = (function () {
  19380. function VertexData() {
  19381. }
  19382. VertexData.prototype.set = function (data, kind) {
  19383. switch (kind) {
  19384. case BABYLON.VertexBuffer.PositionKind:
  19385. this.positions = data;
  19386. break;
  19387. case BABYLON.VertexBuffer.NormalKind:
  19388. this.normals = data;
  19389. break;
  19390. case BABYLON.VertexBuffer.UVKind:
  19391. this.uvs = data;
  19392. break;
  19393. case BABYLON.VertexBuffer.UV2Kind:
  19394. this.uv2s = data;
  19395. break;
  19396. case BABYLON.VertexBuffer.ColorKind:
  19397. this.colors = data;
  19398. break;
  19399. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19400. this.matricesIndices = data;
  19401. break;
  19402. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19403. this.matricesWeights = data;
  19404. break;
  19405. }
  19406. };
  19407. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19408. this._applyTo(mesh, updatable);
  19409. };
  19410. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19411. this._applyTo(geometry, updatable);
  19412. };
  19413. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19414. this._update(mesh);
  19415. };
  19416. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19417. this._update(geometry);
  19418. };
  19419. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19420. if (this.positions) {
  19421. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19422. }
  19423. if (this.normals) {
  19424. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19425. }
  19426. if (this.uvs) {
  19427. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19428. }
  19429. if (this.uv2s) {
  19430. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19431. }
  19432. if (this.colors) {
  19433. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19434. }
  19435. if (this.matricesIndices) {
  19436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19437. }
  19438. if (this.matricesWeights) {
  19439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19440. }
  19441. if (this.indices) {
  19442. meshOrGeometry.setIndices(this.indices);
  19443. }
  19444. };
  19445. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19446. if (this.positions) {
  19447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19448. }
  19449. if (this.normals) {
  19450. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19451. }
  19452. if (this.uvs) {
  19453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19454. }
  19455. if (this.uv2s) {
  19456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19457. }
  19458. if (this.colors) {
  19459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19460. }
  19461. if (this.matricesIndices) {
  19462. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19463. }
  19464. if (this.matricesWeights) {
  19465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19466. }
  19467. if (this.indices) {
  19468. meshOrGeometry.setIndices(this.indices);
  19469. }
  19470. };
  19471. VertexData.prototype.transform = function (matrix) {
  19472. var transformed = BABYLON.Vector3.Zero();
  19473. if (this.positions) {
  19474. var position = BABYLON.Vector3.Zero();
  19475. for (var index = 0; index < this.positions.length; index += 3) {
  19476. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19477. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19478. this.positions[index] = transformed.x;
  19479. this.positions[index + 1] = transformed.y;
  19480. this.positions[index + 2] = transformed.z;
  19481. }
  19482. }
  19483. if (this.normals) {
  19484. var normal = BABYLON.Vector3.Zero();
  19485. for (index = 0; index < this.normals.length; index += 3) {
  19486. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19487. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19488. this.normals[index] = transformed.x;
  19489. this.normals[index + 1] = transformed.y;
  19490. this.normals[index + 2] = transformed.z;
  19491. }
  19492. }
  19493. };
  19494. VertexData.prototype.merge = function (other) {
  19495. if (other.indices) {
  19496. if (!this.indices) {
  19497. this.indices = [];
  19498. }
  19499. var offset = this.positions ? this.positions.length / 3 : 0;
  19500. for (var index = 0; index < other.indices.length; index++) {
  19501. this.indices.push(other.indices[index] + offset);
  19502. }
  19503. }
  19504. if (other.positions) {
  19505. if (!this.positions) {
  19506. this.positions = [];
  19507. }
  19508. for (index = 0; index < other.positions.length; index++) {
  19509. this.positions.push(other.positions[index]);
  19510. }
  19511. }
  19512. if (other.normals) {
  19513. if (!this.normals) {
  19514. this.normals = [];
  19515. }
  19516. for (index = 0; index < other.normals.length; index++) {
  19517. this.normals.push(other.normals[index]);
  19518. }
  19519. }
  19520. if (other.uvs) {
  19521. if (!this.uvs) {
  19522. this.uvs = [];
  19523. }
  19524. for (index = 0; index < other.uvs.length; index++) {
  19525. this.uvs.push(other.uvs[index]);
  19526. }
  19527. }
  19528. if (other.uv2s) {
  19529. if (!this.uv2s) {
  19530. this.uv2s = [];
  19531. }
  19532. for (index = 0; index < other.uv2s.length; index++) {
  19533. this.uv2s.push(other.uv2s[index]);
  19534. }
  19535. }
  19536. if (other.matricesIndices) {
  19537. if (!this.matricesIndices) {
  19538. this.matricesIndices = [];
  19539. }
  19540. for (index = 0; index < other.matricesIndices.length; index++) {
  19541. this.matricesIndices.push(other.matricesIndices[index]);
  19542. }
  19543. }
  19544. if (other.matricesWeights) {
  19545. if (!this.matricesWeights) {
  19546. this.matricesWeights = [];
  19547. }
  19548. for (index = 0; index < other.matricesWeights.length; index++) {
  19549. this.matricesWeights.push(other.matricesWeights[index]);
  19550. }
  19551. }
  19552. if (other.colors) {
  19553. if (!this.colors) {
  19554. this.colors = [];
  19555. }
  19556. for (index = 0; index < other.colors.length; index++) {
  19557. this.colors.push(other.colors[index]);
  19558. }
  19559. }
  19560. };
  19561. // Statics
  19562. VertexData.ExtractFromMesh = function (mesh) {
  19563. return VertexData._ExtractFrom(mesh);
  19564. };
  19565. VertexData.ExtractFromGeometry = function (geometry) {
  19566. return VertexData._ExtractFrom(geometry);
  19567. };
  19568. VertexData._ExtractFrom = function (meshOrGeometry) {
  19569. var result = new BABYLON.VertexData();
  19570. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19571. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19572. }
  19573. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19574. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19575. }
  19576. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19577. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19578. }
  19579. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19580. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19581. }
  19582. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19583. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19584. }
  19585. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19586. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19587. }
  19588. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19589. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19590. }
  19591. result.indices = meshOrGeometry.getIndices();
  19592. return result;
  19593. };
  19594. VertexData.CreateBox = function (size) {
  19595. var normalsSource = [
  19596. new BABYLON.Vector3(0, 0, 1),
  19597. new BABYLON.Vector3(0, 0, -1),
  19598. new BABYLON.Vector3(1, 0, 0),
  19599. new BABYLON.Vector3(-1, 0, 0),
  19600. new BABYLON.Vector3(0, 1, 0),
  19601. new BABYLON.Vector3(0, -1, 0)
  19602. ];
  19603. var indices = [];
  19604. var positions = [];
  19605. var normals = [];
  19606. var uvs = [];
  19607. size = size || 1;
  19608. for (var index = 0; index < normalsSource.length; index++) {
  19609. var normal = normalsSource[index];
  19610. // Get two vectors perpendicular to the face normal and to each other.
  19611. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19612. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19613. // Six indices (two triangles) per face.
  19614. var verticesLength = positions.length / 3;
  19615. indices.push(verticesLength);
  19616. indices.push(verticesLength + 1);
  19617. indices.push(verticesLength + 2);
  19618. indices.push(verticesLength);
  19619. indices.push(verticesLength + 2);
  19620. indices.push(verticesLength + 3);
  19621. // Four vertices per face.
  19622. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19623. positions.push(vertex.x, vertex.y, vertex.z);
  19624. normals.push(normal.x, normal.y, normal.z);
  19625. uvs.push(1.0, 1.0);
  19626. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19627. positions.push(vertex.x, vertex.y, vertex.z);
  19628. normals.push(normal.x, normal.y, normal.z);
  19629. uvs.push(0.0, 1.0);
  19630. vertex = normal.add(side1).add(side2).scale(size / 2);
  19631. positions.push(vertex.x, vertex.y, vertex.z);
  19632. normals.push(normal.x, normal.y, normal.z);
  19633. uvs.push(0.0, 0.0);
  19634. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19635. positions.push(vertex.x, vertex.y, vertex.z);
  19636. normals.push(normal.x, normal.y, normal.z);
  19637. uvs.push(1.0, 0.0);
  19638. }
  19639. // Result
  19640. var vertexData = new BABYLON.VertexData();
  19641. vertexData.indices = indices;
  19642. vertexData.positions = positions;
  19643. vertexData.normals = normals;
  19644. vertexData.uvs = uvs;
  19645. return vertexData;
  19646. };
  19647. VertexData.CreateSphere = function (segments, diameter) {
  19648. segments = segments || 32;
  19649. diameter = diameter || 1;
  19650. var radius = diameter / 2;
  19651. var totalZRotationSteps = 2 + segments;
  19652. var totalYRotationSteps = 2 * totalZRotationSteps;
  19653. var indices = [];
  19654. var positions = [];
  19655. var normals = [];
  19656. var uvs = [];
  19657. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19658. var normalizedZ = zRotationStep / totalZRotationSteps;
  19659. var angleZ = (normalizedZ * Math.PI);
  19660. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19661. var normalizedY = yRotationStep / totalYRotationSteps;
  19662. var angleY = normalizedY * Math.PI * 2;
  19663. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19664. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19665. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19666. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19667. var vertex = complete.scale(radius);
  19668. var normal = BABYLON.Vector3.Normalize(vertex);
  19669. positions.push(vertex.x, vertex.y, vertex.z);
  19670. normals.push(normal.x, normal.y, normal.z);
  19671. uvs.push(normalizedZ, normalizedY);
  19672. }
  19673. if (zRotationStep > 0) {
  19674. var verticesCount = positions.length / 3;
  19675. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19676. indices.push((firstIndex));
  19677. indices.push((firstIndex + 1));
  19678. indices.push(firstIndex + totalYRotationSteps + 1);
  19679. indices.push((firstIndex + totalYRotationSteps + 1));
  19680. indices.push((firstIndex + 1));
  19681. indices.push((firstIndex + totalYRotationSteps + 2));
  19682. }
  19683. }
  19684. }
  19685. // Result
  19686. var vertexData = new BABYLON.VertexData();
  19687. vertexData.indices = indices;
  19688. vertexData.positions = positions;
  19689. vertexData.normals = normals;
  19690. vertexData.uvs = uvs;
  19691. return vertexData;
  19692. };
  19693. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19694. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19695. var radiusTop = diameterTop / 2;
  19696. var radiusBottom = diameterBottom / 2;
  19697. var indices = [];
  19698. var positions = [];
  19699. var normals = [];
  19700. var uvs = [];
  19701. height = height || 1;
  19702. diameterTop = diameterTop || 0.5;
  19703. diameterBottom = diameterBottom || 1;
  19704. tessellation = tessellation || 16;
  19705. subdivisions = subdivisions || 1;
  19706. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19707. var getCircleVector = function (i) {
  19708. var angle = (i * 2.0 * Math.PI / tessellation);
  19709. var dx = Math.cos(angle);
  19710. var dz = Math.sin(angle);
  19711. return new BABYLON.Vector3(dx, 0, dz);
  19712. };
  19713. var createCylinderCap = function (isTop) {
  19714. var radius = isTop ? radiusTop : radiusBottom;
  19715. if (radius == 0) {
  19716. return;
  19717. }
  19718. var vbase = positions.length / 3;
  19719. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19720. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19721. if (!isTop) {
  19722. offset.scaleInPlace(-1);
  19723. textureScale.x = -textureScale.x;
  19724. }
  19725. for (i = 0; i < tessellation; i++) {
  19726. var circleVector = getCircleVector(i);
  19727. var position = circleVector.scale(radius).add(offset);
  19728. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19729. positions.push(position.x, position.y, position.z);
  19730. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19731. }
  19732. for (var i = 0; i < tessellation - 2; i++) {
  19733. if (!isTop) {
  19734. indices.push(vbase);
  19735. indices.push(vbase + (i + 2) % tessellation);
  19736. indices.push(vbase + (i + 1) % tessellation);
  19737. } else {
  19738. indices.push(vbase);
  19739. indices.push(vbase + (i + 1) % tessellation);
  19740. indices.push(vbase + (i + 2) % tessellation);
  19741. }
  19742. }
  19743. };
  19744. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19745. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19746. var stride = tessellation + 1;
  19747. for (var i = 0; i <= tessellation; i++) {
  19748. var circleVector = getCircleVector(i);
  19749. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19750. var position, radius = radiusBottom;
  19751. for (var s = 0; s <= subdivisions; s++) {
  19752. // Update variables
  19753. position = circleVector.scale(radius);
  19754. position.addInPlace(base.add(offset.scale(s)));
  19755. textureCoordinate.y += 1 / subdivisions;
  19756. radius += (radiusTop - radiusBottom) / subdivisions;
  19757. // Push in arrays
  19758. positions.push(position.x, position.y, position.z);
  19759. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19760. }
  19761. }
  19762. subdivisions += 1;
  19763. for (var s = 0; s < subdivisions - 1; s++) {
  19764. for (var i = 0; i <= tessellation; i++) {
  19765. indices.push(i * subdivisions + s);
  19766. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19767. indices.push(i * subdivisions + (s + 1));
  19768. indices.push(i * subdivisions + (s + 1));
  19769. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19770. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19771. }
  19772. }
  19773. // Create flat triangle fan caps to seal the top and bottom.
  19774. createCylinderCap(true);
  19775. createCylinderCap(false);
  19776. // Normals
  19777. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19778. // Result
  19779. var vertexData = new BABYLON.VertexData();
  19780. vertexData.indices = indices;
  19781. vertexData.positions = positions;
  19782. vertexData.normals = normals;
  19783. vertexData.uvs = uvs;
  19784. return vertexData;
  19785. };
  19786. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19787. var indices = [];
  19788. var positions = [];
  19789. var normals = [];
  19790. var uvs = [];
  19791. diameter = diameter || 1;
  19792. thickness = thickness || 0.5;
  19793. tessellation = tessellation || 16;
  19794. var stride = tessellation + 1;
  19795. for (var i = 0; i <= tessellation; i++) {
  19796. var u = i / tessellation;
  19797. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19798. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19799. for (var j = 0; j <= tessellation; j++) {
  19800. var v = 1 - j / tessellation;
  19801. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19802. var dx = Math.cos(innerAngle);
  19803. var dy = Math.sin(innerAngle);
  19804. // Create a vertex.
  19805. var normal = new BABYLON.Vector3(dx, dy, 0);
  19806. var position = normal.scale(thickness / 2);
  19807. var textureCoordinate = new BABYLON.Vector2(u, v);
  19808. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19809. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19810. positions.push(position.x, position.y, position.z);
  19811. normals.push(normal.x, normal.y, normal.z);
  19812. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19813. // And create indices for two triangles.
  19814. var nextI = (i + 1) % stride;
  19815. var nextJ = (j + 1) % stride;
  19816. indices.push(i * stride + j);
  19817. indices.push(i * stride + nextJ);
  19818. indices.push(nextI * stride + j);
  19819. indices.push(i * stride + nextJ);
  19820. indices.push(nextI * stride + nextJ);
  19821. indices.push(nextI * stride + j);
  19822. }
  19823. }
  19824. // Result
  19825. var vertexData = new BABYLON.VertexData();
  19826. vertexData.indices = indices;
  19827. vertexData.positions = positions;
  19828. vertexData.normals = normals;
  19829. vertexData.uvs = uvs;
  19830. return vertexData;
  19831. };
  19832. VertexData.CreateLines = function (points) {
  19833. var indices = [];
  19834. var positions = [];
  19835. for (var index = 0; index < points.length; index++) {
  19836. positions.push(points[index].x, points[index].y, points[index].z);
  19837. if (index > 0) {
  19838. indices.push(index - 1);
  19839. indices.push(index);
  19840. }
  19841. }
  19842. // Result
  19843. var vertexData = new BABYLON.VertexData();
  19844. vertexData.indices = indices;
  19845. vertexData.positions = positions;
  19846. return vertexData;
  19847. };
  19848. VertexData.CreateGround = function (width, height, subdivisions) {
  19849. var indices = [];
  19850. var positions = [];
  19851. var normals = [];
  19852. var uvs = [];
  19853. var row, col;
  19854. width = width || 1;
  19855. height = height || 1;
  19856. subdivisions = subdivisions || 1;
  19857. for (row = 0; row <= subdivisions; row++) {
  19858. for (col = 0; col <= subdivisions; col++) {
  19859. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19860. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19861. positions.push(position.x, position.y, position.z);
  19862. normals.push(normal.x, normal.y, normal.z);
  19863. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19864. }
  19865. }
  19866. for (row = 0; row < subdivisions; row++) {
  19867. for (col = 0; col < subdivisions; col++) {
  19868. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19869. indices.push(col + 1 + row * (subdivisions + 1));
  19870. indices.push(col + row * (subdivisions + 1));
  19871. indices.push(col + (row + 1) * (subdivisions + 1));
  19872. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19873. indices.push(col + row * (subdivisions + 1));
  19874. }
  19875. }
  19876. // Result
  19877. var vertexData = new BABYLON.VertexData();
  19878. vertexData.indices = indices;
  19879. vertexData.positions = positions;
  19880. vertexData.normals = normals;
  19881. vertexData.uvs = uvs;
  19882. return vertexData;
  19883. };
  19884. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19885. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19886. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19887. var indices = [];
  19888. var positions = [];
  19889. var normals = [];
  19890. var uvs = [];
  19891. var row, col, tileRow, tileCol;
  19892. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19893. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19894. precision.w = (precision.w < 1) ? 1 : precision.w;
  19895. precision.h = (precision.h < 1) ? 1 : precision.h;
  19896. var tileSize = {
  19897. 'w': (xmax - xmin) / subdivisions.w,
  19898. 'h': (zmax - zmin) / subdivisions.h
  19899. };
  19900. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19901. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19902. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19903. }
  19904. }
  19905. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19906. // Indices
  19907. var base = positions.length / 3;
  19908. var rowLength = precision.w + 1;
  19909. for (row = 0; row < precision.h; row++) {
  19910. for (col = 0; col < precision.w; col++) {
  19911. var square = [
  19912. base + col + row * rowLength,
  19913. base + (col + 1) + row * rowLength,
  19914. base + (col + 1) + (row + 1) * rowLength,
  19915. base + col + (row + 1) * rowLength
  19916. ];
  19917. indices.push(square[1]);
  19918. indices.push(square[2]);
  19919. indices.push(square[3]);
  19920. indices.push(square[0]);
  19921. indices.push(square[1]);
  19922. indices.push(square[3]);
  19923. }
  19924. }
  19925. // Position, normals and uvs
  19926. var position = BABYLON.Vector3.Zero();
  19927. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19928. for (row = 0; row <= precision.h; row++) {
  19929. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19930. for (col = 0; col <= precision.w; col++) {
  19931. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19932. position.y = 0;
  19933. positions.push(position.x, position.y, position.z);
  19934. normals.push(normal.x, normal.y, normal.z);
  19935. uvs.push(col / precision.w, row / precision.h);
  19936. }
  19937. }
  19938. }
  19939. // Result
  19940. var vertexData = new BABYLON.VertexData();
  19941. vertexData.indices = indices;
  19942. vertexData.positions = positions;
  19943. vertexData.normals = normals;
  19944. vertexData.uvs = uvs;
  19945. return vertexData;
  19946. };
  19947. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19948. var indices = [];
  19949. var positions = [];
  19950. var normals = [];
  19951. var uvs = [];
  19952. var row, col;
  19953. for (row = 0; row <= subdivisions; row++) {
  19954. for (col = 0; col <= subdivisions; col++) {
  19955. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19956. // Compute height
  19957. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  19958. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  19959. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  19960. var r = buffer[pos] / 255.0;
  19961. var g = buffer[pos + 1] / 255.0;
  19962. var b = buffer[pos + 2] / 255.0;
  19963. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19964. position.y = minHeight + (maxHeight - minHeight) * gradient;
  19965. // Add vertex
  19966. positions.push(position.x, position.y, position.z);
  19967. normals.push(0, 0, 0);
  19968. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19969. }
  19970. }
  19971. for (row = 0; row < subdivisions; row++) {
  19972. for (col = 0; col < subdivisions; col++) {
  19973. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19974. indices.push(col + 1 + row * (subdivisions + 1));
  19975. indices.push(col + row * (subdivisions + 1));
  19976. indices.push(col + (row + 1) * (subdivisions + 1));
  19977. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19978. indices.push(col + row * (subdivisions + 1));
  19979. }
  19980. }
  19981. // Normals
  19982. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19983. // Result
  19984. var vertexData = new BABYLON.VertexData();
  19985. vertexData.indices = indices;
  19986. vertexData.positions = positions;
  19987. vertexData.normals = normals;
  19988. vertexData.uvs = uvs;
  19989. return vertexData;
  19990. };
  19991. VertexData.CreatePlane = function (size) {
  19992. var indices = [];
  19993. var positions = [];
  19994. var normals = [];
  19995. var uvs = [];
  19996. size = size || 1;
  19997. // Vertices
  19998. var halfSize = size / 2.0;
  19999. positions.push(-halfSize, -halfSize, 0);
  20000. normals.push(0, 0, -1.0);
  20001. uvs.push(0.0, 0.0);
  20002. positions.push(halfSize, -halfSize, 0);
  20003. normals.push(0, 0, -1.0);
  20004. uvs.push(1.0, 0.0);
  20005. positions.push(halfSize, halfSize, 0);
  20006. normals.push(0, 0, -1.0);
  20007. uvs.push(1.0, 1.0);
  20008. positions.push(-halfSize, halfSize, 0);
  20009. normals.push(0, 0, -1.0);
  20010. uvs.push(0.0, 1.0);
  20011. // Indices
  20012. indices.push(0);
  20013. indices.push(1);
  20014. indices.push(2);
  20015. indices.push(0);
  20016. indices.push(2);
  20017. indices.push(3);
  20018. // Result
  20019. var vertexData = new BABYLON.VertexData();
  20020. vertexData.indices = indices;
  20021. vertexData.positions = positions;
  20022. vertexData.normals = normals;
  20023. vertexData.uvs = uvs;
  20024. return vertexData;
  20025. };
  20026. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20027. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20028. var indices = [];
  20029. var positions = [];
  20030. var normals = [];
  20031. var uvs = [];
  20032. radius = radius || 2;
  20033. tube = tube || 0.5;
  20034. radialSegments = radialSegments || 32;
  20035. tubularSegments = tubularSegments || 32;
  20036. p = p || 2;
  20037. q = q || 3;
  20038. // Helper
  20039. var getPos = function (angle) {
  20040. var cu = Math.cos(angle);
  20041. var su = Math.sin(angle);
  20042. var quOverP = q / p * angle;
  20043. var cs = Math.cos(quOverP);
  20044. var tx = radius * (2 + cs) * 0.5 * cu;
  20045. var ty = radius * (2 + cs) * su * 0.5;
  20046. var tz = radius * Math.sin(quOverP) * 0.5;
  20047. return new BABYLON.Vector3(tx, ty, tz);
  20048. };
  20049. for (var i = 0; i <= radialSegments; i++) {
  20050. var modI = i % radialSegments;
  20051. var u = modI / radialSegments * 2 * p * Math.PI;
  20052. var p1 = getPos(u);
  20053. var p2 = getPos(u + 0.01);
  20054. var tang = p2.subtract(p1);
  20055. var n = p2.add(p1);
  20056. var bitan = BABYLON.Vector3.Cross(tang, n);
  20057. n = BABYLON.Vector3.Cross(bitan, tang);
  20058. bitan.normalize();
  20059. n.normalize();
  20060. for (var j = 0; j < tubularSegments; j++) {
  20061. var modJ = j % tubularSegments;
  20062. var v = modJ / tubularSegments * 2 * Math.PI;
  20063. var cx = -tube * Math.cos(v);
  20064. var cy = tube * Math.sin(v);
  20065. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20066. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20067. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20068. uvs.push(i / radialSegments);
  20069. uvs.push(j / tubularSegments);
  20070. }
  20071. }
  20072. for (i = 0; i < radialSegments; i++) {
  20073. for (j = 0; j < tubularSegments; j++) {
  20074. var jNext = (j + 1) % tubularSegments;
  20075. var a = i * tubularSegments + j;
  20076. var b = (i + 1) * tubularSegments + j;
  20077. var c = (i + 1) * tubularSegments + jNext;
  20078. var d = i * tubularSegments + jNext;
  20079. indices.push(d);
  20080. indices.push(b);
  20081. indices.push(a);
  20082. indices.push(d);
  20083. indices.push(c);
  20084. indices.push(b);
  20085. }
  20086. }
  20087. // Normals
  20088. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20089. // Result
  20090. var vertexData = new BABYLON.VertexData();
  20091. vertexData.indices = indices;
  20092. vertexData.positions = positions;
  20093. vertexData.normals = normals;
  20094. vertexData.uvs = uvs;
  20095. return vertexData;
  20096. };
  20097. // Tools
  20098. VertexData.ComputeNormals = function (positions, indices, normals) {
  20099. var positionVectors = [];
  20100. var facesOfVertices = [];
  20101. var index;
  20102. for (index = 0; index < positions.length; index += 3) {
  20103. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20104. positionVectors.push(vector3);
  20105. facesOfVertices.push([]);
  20106. }
  20107. // Compute normals
  20108. var facesNormals = [];
  20109. for (index = 0; index < indices.length / 3; index++) {
  20110. var i1 = indices[index * 3];
  20111. var i2 = indices[index * 3 + 1];
  20112. var i3 = indices[index * 3 + 2];
  20113. var p1 = positionVectors[i1];
  20114. var p2 = positionVectors[i2];
  20115. var p3 = positionVectors[i3];
  20116. var p1p2 = p1.subtract(p2);
  20117. var p3p2 = p3.subtract(p2);
  20118. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20119. facesOfVertices[i1].push(index);
  20120. facesOfVertices[i2].push(index);
  20121. facesOfVertices[i3].push(index);
  20122. }
  20123. for (index = 0; index < positionVectors.length; index++) {
  20124. var faces = facesOfVertices[index];
  20125. var normal = BABYLON.Vector3.Zero();
  20126. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20127. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20128. }
  20129. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20130. normals[index * 3] = normal.x;
  20131. normals[index * 3 + 1] = normal.y;
  20132. normals[index * 3 + 2] = normal.z;
  20133. }
  20134. };
  20135. return VertexData;
  20136. })();
  20137. BABYLON.VertexData = VertexData;
  20138. })(BABYLON || (BABYLON = {}));
  20139. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20140. var BABYLON;
  20141. (function (BABYLON) {
  20142. var buildCamera = function (that, name) {
  20143. that._leftCamera.isIntermediate = true;
  20144. that.subCameras.push(that._leftCamera);
  20145. that.subCameras.push(that._rightCamera);
  20146. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20147. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20148. that._anaglyphPostProcess.onApply = function (effect) {
  20149. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20150. };
  20151. that._update();
  20152. };
  20153. var AnaglyphArcRotateCamera = (function (_super) {
  20154. __extends(AnaglyphArcRotateCamera, _super);
  20155. // ANY
  20156. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20157. _super.call(this, name, alpha, beta, radius, target, scene);
  20158. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20159. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20160. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20161. buildCamera(this, name);
  20162. }
  20163. AnaglyphArcRotateCamera.prototype._update = function () {
  20164. this._updateCamera(this._leftCamera);
  20165. this._updateCamera(this._rightCamera);
  20166. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20167. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20168. _super.prototype._update.call(this);
  20169. };
  20170. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20171. camera.beta = this.beta;
  20172. camera.radius = this.radius;
  20173. camera.minZ = this.minZ;
  20174. camera.maxZ = this.maxZ;
  20175. camera.fov = this.fov;
  20176. camera.target = this.target;
  20177. };
  20178. return AnaglyphArcRotateCamera;
  20179. })(BABYLON.ArcRotateCamera);
  20180. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20181. var AnaglyphFreeCamera = (function (_super) {
  20182. __extends(AnaglyphFreeCamera, _super);
  20183. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20184. _super.call(this, name, position, scene);
  20185. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20186. this._transformMatrix = new BABYLON.Matrix();
  20187. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20188. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20189. buildCamera(this, name);
  20190. }
  20191. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20192. var target = this.getTarget();
  20193. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20194. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20195. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20196. };
  20197. AnaglyphFreeCamera.prototype._update = function () {
  20198. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20199. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20200. this._updateCamera(this._leftCamera);
  20201. this._updateCamera(this._rightCamera);
  20202. _super.prototype._update.call(this);
  20203. };
  20204. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20205. camera.minZ = this.minZ;
  20206. camera.maxZ = this.maxZ;
  20207. camera.fov = this.fov;
  20208. camera.viewport = this.viewport;
  20209. camera.setTarget(this.getTarget());
  20210. };
  20211. return AnaglyphFreeCamera;
  20212. })(BABYLON.FreeCamera);
  20213. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20214. })(BABYLON || (BABYLON = {}));
  20215. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20216. var BABYLON;
  20217. (function (BABYLON) {
  20218. var AnaglyphPostProcess = (function (_super) {
  20219. __extends(AnaglyphPostProcess, _super);
  20220. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20221. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20222. }
  20223. return AnaglyphPostProcess;
  20224. })(BABYLON.PostProcess);
  20225. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20226. })(BABYLON || (BABYLON = {}));
  20227. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20228. var BABYLON;
  20229. (function (BABYLON) {
  20230. var Tags = (function () {
  20231. function Tags() {
  20232. }
  20233. Tags.EnableFor = function (obj) {
  20234. obj._tags = obj._tags || {};
  20235. obj.hasTags = function () {
  20236. return Tags.HasTags(obj);
  20237. };
  20238. obj.addTags = function (tagsString) {
  20239. return Tags.AddTagsTo(obj, tagsString);
  20240. };
  20241. obj.removeTags = function (tagsString) {
  20242. return Tags.RemoveTagsFrom(obj, tagsString);
  20243. };
  20244. obj.matchesTagsQuery = function (tagsQuery) {
  20245. return Tags.MatchesQuery(obj, tagsQuery);
  20246. };
  20247. };
  20248. Tags.DisableFor = function (obj) {
  20249. delete obj._tags;
  20250. delete obj.hasTags;
  20251. delete obj.addTags;
  20252. delete obj.removeTags;
  20253. delete obj.matchesTagsQuery;
  20254. };
  20255. Tags.HasTags = function (obj) {
  20256. if (!obj._tags) {
  20257. return false;
  20258. }
  20259. return !BABYLON.Tools.IsEmpty(obj._tags);
  20260. };
  20261. Tags.GetTags = function (obj) {
  20262. if (!obj._tags) {
  20263. return null;
  20264. }
  20265. return obj._tags;
  20266. };
  20267. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20268. // a tag cannot start with '||', '&&', and '!'
  20269. // it cannot contain whitespaces
  20270. Tags.AddTagsTo = function (obj, tagsString) {
  20271. if (!tagsString) {
  20272. return;
  20273. }
  20274. var tags = tagsString.split(" ");
  20275. for (var t in tags) {
  20276. Tags._AddTagTo(obj, tags[t]);
  20277. }
  20278. };
  20279. Tags._AddTagTo = function (obj, tag) {
  20280. tag = tag.trim();
  20281. if (tag === "" || tag === "true" || tag === "false") {
  20282. return;
  20283. }
  20284. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20285. return;
  20286. }
  20287. Tags.EnableFor(obj);
  20288. obj._tags[tag] = true;
  20289. };
  20290. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20291. if (!Tags.HasTags(obj)) {
  20292. return;
  20293. }
  20294. var tags = tagsString.split(" ");
  20295. for (var t in tags) {
  20296. Tags._RemoveTagFrom(obj, tags[t]);
  20297. }
  20298. };
  20299. Tags._RemoveTagFrom = function (obj, tag) {
  20300. delete obj._tags[tag];
  20301. };
  20302. Tags.MatchesQuery = function (obj, tagsQuery) {
  20303. if (tagsQuery === undefined) {
  20304. return true;
  20305. }
  20306. if (tagsQuery === "") {
  20307. return Tags.HasTags(obj);
  20308. }
  20309. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20310. return Tags.HasTags(obj) && obj._tags[r];
  20311. });
  20312. };
  20313. return Tags;
  20314. })();
  20315. BABYLON.Tags = Tags;
  20316. })(BABYLON || (BABYLON = {}));
  20317. //# sourceMappingURL=babylon.tags.js.map
  20318. var BABYLON;
  20319. (function (BABYLON) {
  20320. (function (Internals) {
  20321. var AndOrNotEvaluator = (function () {
  20322. function AndOrNotEvaluator() {
  20323. }
  20324. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20325. if (!query.match(/\([^\(\)]*\)/g)) {
  20326. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20327. } else {
  20328. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20329. // remove parenthesis
  20330. r = r.slice(1, r.length - 1);
  20331. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20332. });
  20333. }
  20334. if (query === "true") {
  20335. return true;
  20336. }
  20337. if (query === "false") {
  20338. return false;
  20339. }
  20340. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20341. };
  20342. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20343. evaluateCallback = evaluateCallback || (function (r) {
  20344. return r === "true" ? true : false;
  20345. });
  20346. var result;
  20347. var or = parenthesisContent.split("||");
  20348. for (var i in or) {
  20349. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20350. var and = ori.split("&&");
  20351. if (and.length > 1) {
  20352. for (var j = 0; j < and.length; ++j) {
  20353. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20354. if (andj !== "true" && andj !== "false") {
  20355. if (andj[0] === "!") {
  20356. result = !evaluateCallback(andj.substring(1));
  20357. } else {
  20358. result = evaluateCallback(andj);
  20359. }
  20360. } else {
  20361. result = andj === "true" ? true : false;
  20362. }
  20363. if (!result) {
  20364. ori = "false";
  20365. break;
  20366. }
  20367. }
  20368. }
  20369. if (result || ori === "true") {
  20370. result = true;
  20371. break;
  20372. }
  20373. // result equals false (or undefined)
  20374. if (ori !== "true" && ori !== "false") {
  20375. if (ori[0] === "!") {
  20376. result = !evaluateCallback(ori.substring(1));
  20377. } else {
  20378. result = evaluateCallback(ori);
  20379. }
  20380. } else {
  20381. result = ori === "true" ? true : false;
  20382. }
  20383. }
  20384. // the whole parenthesis scope is replaced by 'true' or 'false'
  20385. return result ? "true" : "false";
  20386. };
  20387. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20388. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20389. // remove whitespaces
  20390. r = r.replace(/[\s]/g, function () {
  20391. return "";
  20392. });
  20393. return r.length % 2 ? "!" : "";
  20394. });
  20395. booleanString = booleanString.trim();
  20396. if (booleanString === "!true") {
  20397. booleanString = "false";
  20398. } else if (booleanString === "!false") {
  20399. booleanString = "true";
  20400. }
  20401. return booleanString;
  20402. };
  20403. return AndOrNotEvaluator;
  20404. })();
  20405. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20406. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20407. var Internals = BABYLON.Internals;
  20408. })(BABYLON || (BABYLON = {}));
  20409. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20410. var BABYLON;
  20411. (function (BABYLON) {
  20412. var PostProcessRenderPass = (function () {
  20413. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20414. this._enabled = true;
  20415. this._refCount = 0;
  20416. this._name = name;
  20417. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20418. this.setRenderList(renderList);
  20419. this._renderTexture.onBeforeRender = beforeRender;
  20420. this._renderTexture.onAfterRender = afterRender;
  20421. this._scene = scene;
  20422. this._renderList = renderList;
  20423. }
  20424. // private
  20425. PostProcessRenderPass.prototype._incRefCount = function () {
  20426. if (this._refCount === 0) {
  20427. this._scene.customRenderTargets.push(this._renderTexture);
  20428. }
  20429. return ++this._refCount;
  20430. };
  20431. PostProcessRenderPass.prototype._decRefCount = function () {
  20432. this._refCount--;
  20433. if (this._refCount <= 0) {
  20434. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20435. }
  20436. return this._refCount;
  20437. };
  20438. PostProcessRenderPass.prototype._update = function () {
  20439. this.setRenderList(this._renderList);
  20440. };
  20441. // public
  20442. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20443. this._renderTexture.renderList = renderList;
  20444. };
  20445. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20446. return this._renderTexture;
  20447. };
  20448. return PostProcessRenderPass;
  20449. })();
  20450. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20451. })(BABYLON || (BABYLON = {}));
  20452. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20453. var BABYLON;
  20454. (function (BABYLON) {
  20455. var PostProcessRenderEffect = (function () {
  20456. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20457. this._engine = engine;
  20458. this._name = name;
  20459. this._singleInstance = singleInstance || true;
  20460. this._getPostProcess = getPostProcess;
  20461. this._cameras = [];
  20462. this._indicesForCamera = [];
  20463. this._postProcesses = {};
  20464. this._renderPasses = {};
  20465. this._renderEffectAsPasses = {};
  20466. }
  20467. PostProcessRenderEffect.prototype._update = function () {
  20468. for (var renderPassName in this._renderPasses) {
  20469. this._renderPasses[renderPassName]._update();
  20470. }
  20471. };
  20472. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20473. this._renderPasses[renderPass._name] = renderPass;
  20474. this._linkParameters();
  20475. };
  20476. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20477. delete this._renderPasses[renderPass._name];
  20478. this._linkParameters();
  20479. };
  20480. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20481. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20482. this._linkParameters();
  20483. };
  20484. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20485. for (var renderPassName in this._renderPasses) {
  20486. if (renderPassName === passName) {
  20487. return this._renderPasses[passName];
  20488. }
  20489. }
  20490. };
  20491. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20492. this._renderPasses = {};
  20493. this._linkParameters();
  20494. };
  20495. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20496. var cameraKey;
  20497. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20498. for (var i = 0; i < _cam.length; i++) {
  20499. var camera = _cam[i];
  20500. var cameraName = camera.name;
  20501. if (this._singleInstance) {
  20502. cameraKey = 0;
  20503. } else {
  20504. cameraKey = cameraName;
  20505. }
  20506. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20507. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20508. if (!this._indicesForCamera[cameraName]) {
  20509. this._indicesForCamera[cameraName] = [];
  20510. }
  20511. this._indicesForCamera[cameraName].push(index);
  20512. if (this._cameras.indexOf(camera) === -1) {
  20513. this._cameras[cameraName] = camera;
  20514. }
  20515. for (var passName in this._renderPasses) {
  20516. this._renderPasses[passName]._incRefCount();
  20517. }
  20518. }
  20519. this._linkParameters();
  20520. };
  20521. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20522. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20523. for (var i = 0; i < _cam.length; i++) {
  20524. var camera = _cam[i];
  20525. var cameraName = camera.name;
  20526. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20527. var index = this._cameras.indexOf(cameraName);
  20528. this._indicesForCamera.splice(index, 1);
  20529. this._cameras.splice(index, 1);
  20530. for (var passName in this._renderPasses) {
  20531. this._renderPasses[passName]._decRefCount();
  20532. }
  20533. }
  20534. };
  20535. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20536. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20537. for (var i = 0; i < _cam.length; i++) {
  20538. var camera = _cam[i];
  20539. var cameraName = camera.name;
  20540. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20541. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20542. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20543. }
  20544. }
  20545. for (var passName in this._renderPasses) {
  20546. this._renderPasses[passName]._incRefCount();
  20547. }
  20548. }
  20549. };
  20550. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20551. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20552. for (var i = 0; i < _cam.length; i++) {
  20553. var camera = _cam[i];
  20554. var cameraName = camera.Name;
  20555. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20556. for (var passName in this._renderPasses) {
  20557. this._renderPasses[passName]._decRefCount();
  20558. }
  20559. }
  20560. };
  20561. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20562. if (this._singleInstance) {
  20563. return this._postProcesses[0];
  20564. } else {
  20565. return this._postProcesses[camera.name];
  20566. }
  20567. };
  20568. PostProcessRenderEffect.prototype._linkParameters = function () {
  20569. var _this = this;
  20570. for (var index in this._postProcesses) {
  20571. if (this.applyParameters) {
  20572. this.applyParameters(this._postProcesses[index]);
  20573. }
  20574. this._postProcesses[index].onBeforeRender = function (effect) {
  20575. _this._linkTextures(effect);
  20576. };
  20577. }
  20578. };
  20579. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20580. for (var renderPassName in this._renderPasses) {
  20581. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20582. }
  20583. for (var renderEffectName in this._renderEffectAsPasses) {
  20584. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20585. }
  20586. };
  20587. return PostProcessRenderEffect;
  20588. })();
  20589. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20590. })(BABYLON || (BABYLON = {}));
  20591. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20592. var BABYLON;
  20593. (function (BABYLON) {
  20594. var PostProcessRenderPipeline = (function () {
  20595. function PostProcessRenderPipeline(engine, name) {
  20596. this._engine = engine;
  20597. this._name = name;
  20598. this._renderEffects = {};
  20599. this._renderEffectsForIsolatedPass = {};
  20600. this._cameras = [];
  20601. }
  20602. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20603. this._renderEffects[renderEffect._name] = renderEffect;
  20604. };
  20605. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20606. var renderEffects = this._renderEffects[renderEffectName];
  20607. if (!renderEffects) {
  20608. return;
  20609. }
  20610. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20611. };
  20612. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20613. var renderEffects = this._renderEffects[renderEffectName];
  20614. if (!renderEffects) {
  20615. return;
  20616. }
  20617. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20618. };
  20619. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20620. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20621. var indicesToDelete = [];
  20622. for (var i = 0; i < _cam.length; i++) {
  20623. var camera = _cam[i];
  20624. var cameraName = camera.name;
  20625. if (this._cameras.indexOf(camera) === -1) {
  20626. this._cameras[cameraName] = camera;
  20627. } else if (unique) {
  20628. indicesToDelete.push(i);
  20629. }
  20630. }
  20631. for (var i = 0; i < indicesToDelete.length; i++) {
  20632. cameras.splice(indicesToDelete[i], 1);
  20633. }
  20634. for (var renderEffectName in this._renderEffects) {
  20635. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20636. }
  20637. };
  20638. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20639. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20640. for (var renderEffectName in this._renderEffects) {
  20641. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20642. }
  20643. for (var i = 0; i < _cam.length; i++) {
  20644. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20645. }
  20646. };
  20647. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20648. var _this = this;
  20649. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20650. var pass = null;
  20651. for (var renderEffectName in this._renderEffects) {
  20652. pass = this._renderEffects[renderEffectName].getPass(passName);
  20653. if (pass != null) {
  20654. break;
  20655. }
  20656. }
  20657. if (pass === null) {
  20658. return;
  20659. }
  20660. for (var renderEffectName in this._renderEffects) {
  20661. this._renderEffects[renderEffectName]._disable(_cam);
  20662. }
  20663. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20664. for (var i = 0; i < _cam.length; i++) {
  20665. var camera = _cam[i];
  20666. var cameraName = camera.name;
  20667. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20668. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20669. });
  20670. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20671. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20672. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20673. }
  20674. };
  20675. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20676. var _this = this;
  20677. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20678. for (var i = 0; i < _cam.length; i++) {
  20679. var camera = _cam[i];
  20680. var cameraName = camera.name;
  20681. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20682. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20683. });
  20684. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20685. }
  20686. for (var renderEffectName in this._renderEffects) {
  20687. this._renderEffects[renderEffectName]._enable(_cam);
  20688. }
  20689. };
  20690. PostProcessRenderPipeline.prototype._update = function () {
  20691. for (var renderEffectName in this._renderEffects) {
  20692. this._renderEffects[renderEffectName]._update();
  20693. }
  20694. for (var i = 0; i < this._cameras.length; i++) {
  20695. var cameraName = this._cameras[i].name;
  20696. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20697. this._renderEffectsForIsolatedPass[cameraName]._update();
  20698. }
  20699. }
  20700. };
  20701. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20702. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20703. return PostProcessRenderPipeline;
  20704. })();
  20705. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20706. })(BABYLON || (BABYLON = {}));
  20707. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20708. var BABYLON;
  20709. (function (BABYLON) {
  20710. var PostProcessRenderPipelineManager = (function () {
  20711. function PostProcessRenderPipelineManager() {
  20712. this._renderPipelines = {};
  20713. }
  20714. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20715. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20716. };
  20717. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20718. var renderPipeline = this._renderPipelines[renderPipelineName];
  20719. if (!renderPipeline) {
  20720. return;
  20721. }
  20722. renderPipeline._attachCameras(cameras, unique);
  20723. };
  20724. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20725. var renderPipeline = this._renderPipelines[renderPipelineName];
  20726. if (!renderPipeline) {
  20727. return;
  20728. }
  20729. renderPipeline._detachCameras(cameras);
  20730. };
  20731. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20732. var renderPipeline = this._renderPipelines[renderPipelineName];
  20733. if (!renderPipeline) {
  20734. return;
  20735. }
  20736. renderPipeline._enableEffect(renderEffectName, cameras);
  20737. };
  20738. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20739. var renderPipeline = this._renderPipelines[renderPipelineName];
  20740. if (!renderPipeline) {
  20741. return;
  20742. }
  20743. renderPipeline._disableEffect(renderEffectName, cameras);
  20744. };
  20745. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20746. var renderPipeline = this._renderPipelines[renderPipelineName];
  20747. if (!renderPipeline) {
  20748. return;
  20749. }
  20750. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20751. };
  20752. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20753. var renderPipeline = this._renderPipelines[renderPipelineName];
  20754. if (!renderPipeline) {
  20755. return;
  20756. }
  20757. renderPipeline._disableDisplayOnlyPass(cameras);
  20758. };
  20759. PostProcessRenderPipelineManager.prototype.update = function () {
  20760. for (var renderPipelineName in this._renderPipelines) {
  20761. this._renderPipelines[renderPipelineName]._update();
  20762. }
  20763. };
  20764. return PostProcessRenderPipelineManager;
  20765. })();
  20766. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20767. })(BABYLON || (BABYLON = {}));
  20768. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20769. var BABYLON;
  20770. (function (BABYLON) {
  20771. var DisplayPassPostProcess = (function (_super) {
  20772. __extends(DisplayPassPostProcess, _super);
  20773. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20774. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20775. }
  20776. return DisplayPassPostProcess;
  20777. })(BABYLON.PostProcess);
  20778. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20779. })(BABYLON || (BABYLON = {}));
  20780. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20781. var BABYLON;
  20782. (function (BABYLON) {
  20783. var BoundingBoxRenderer = (function () {
  20784. function BoundingBoxRenderer(scene) {
  20785. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20786. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20787. this.showBackLines = true;
  20788. this.renderList = new BABYLON.SmartArray(32);
  20789. this._scene = scene;
  20790. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20791. attributes: ["position"],
  20792. uniforms: ["worldViewProjection", "color"]
  20793. });
  20794. var engine = this._scene.getEngine();
  20795. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20796. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20797. 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]);
  20798. }
  20799. BoundingBoxRenderer.prototype.reset = function () {
  20800. this.renderList.reset();
  20801. };
  20802. BoundingBoxRenderer.prototype.render = function () {
  20803. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20804. return;
  20805. }
  20806. var engine = this._scene.getEngine();
  20807. engine.setDepthWrite(false);
  20808. this._colorShader._preBind();
  20809. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20810. var boundingBox = this.renderList.data[boundingBoxIndex];
  20811. var min = boundingBox.minimum;
  20812. var max = boundingBox.maximum;
  20813. var diff = max.subtract(min);
  20814. var median = min.add(diff.scale(0.5));
  20815. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20816. // VBOs
  20817. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20818. if (this.showBackLines) {
  20819. // Back
  20820. engine.setDepthFunctionToGreaterOrEqual();
  20821. this._scene.resetCachedMaterial();
  20822. this._colorShader.setColor4("color", this.backColor.toColor4());
  20823. this._colorShader.bind(worldMatrix);
  20824. // Draw order
  20825. engine.draw(false, 0, 24);
  20826. }
  20827. // Front
  20828. engine.setDepthFunctionToLess();
  20829. this._scene.resetCachedMaterial();
  20830. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20831. this._colorShader.bind(worldMatrix);
  20832. // Draw order
  20833. engine.draw(false, 0, 24);
  20834. }
  20835. this._colorShader.unbind();
  20836. engine.setDepthFunctionToLessOrEqual();
  20837. engine.setDepthWrite(true);
  20838. };
  20839. BoundingBoxRenderer.prototype.dispose = function () {
  20840. this._colorShader.dispose();
  20841. this._vb.dispose();
  20842. this._scene.getEngine()._releaseBuffer(this._ib);
  20843. };
  20844. return BoundingBoxRenderer;
  20845. })();
  20846. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20847. })(BABYLON || (BABYLON = {}));
  20848. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20849. /**
  20850. * Based on jsTGALoader - Javascript loader for TGA file
  20851. * By Vincent Thibault
  20852. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20853. */
  20854. var BABYLON;
  20855. (function (BABYLON) {
  20856. (function (Internals) {
  20857. var TGATools = (function () {
  20858. function TGATools() {
  20859. }
  20860. TGATools.GetTGAHeader = function (data) {
  20861. var offset = 0;
  20862. var header = {
  20863. id_length: data[offset++],
  20864. colormap_type: data[offset++],
  20865. image_type: data[offset++],
  20866. colormap_index: data[offset++] | data[offset++] << 8,
  20867. colormap_length: data[offset++] | data[offset++] << 8,
  20868. colormap_size: data[offset++],
  20869. origin: [
  20870. data[offset++] | data[offset++] << 8,
  20871. data[offset++] | data[offset++] << 8
  20872. ],
  20873. width: data[offset++] | data[offset++] << 8,
  20874. height: data[offset++] | data[offset++] << 8,
  20875. pixel_size: data[offset++],
  20876. flags: data[offset++]
  20877. };
  20878. return header;
  20879. };
  20880. TGATools.UploadContent = function (gl, data) {
  20881. // Not enough data to contain header ?
  20882. if (data.length < 19) {
  20883. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20884. return;
  20885. }
  20886. // Read Header
  20887. var offset = 18;
  20888. var header = TGATools.GetTGAHeader(data);
  20889. // Assume it's a valid Targa file.
  20890. if (header.id_length + offset > data.length) {
  20891. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20892. return;
  20893. }
  20894. // Skip not needed data
  20895. offset += header.id_length;
  20896. var use_rle = false;
  20897. var use_pal = false;
  20898. var use_rgb = false;
  20899. var use_grey = false;
  20900. switch (header.image_type) {
  20901. case TGATools._TYPE_RLE_INDEXED:
  20902. use_rle = true;
  20903. case TGATools._TYPE_INDEXED:
  20904. use_pal = true;
  20905. break;
  20906. case TGATools._TYPE_RLE_RGB:
  20907. use_rle = true;
  20908. case TGATools._TYPE_RGB:
  20909. use_rgb = true;
  20910. break;
  20911. case TGATools._TYPE_RLE_GREY:
  20912. use_rle = true;
  20913. case TGATools._TYPE_GREY:
  20914. use_grey = true;
  20915. break;
  20916. }
  20917. var pixel_data;
  20918. var numAlphaBits = header.flags & 0xf;
  20919. var pixel_size = header.pixel_size >> 3;
  20920. var pixel_total = header.width * header.height * pixel_size;
  20921. // Read palettes
  20922. var palettes;
  20923. if (use_pal) {
  20924. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20925. }
  20926. // Read LRE
  20927. if (use_rle) {
  20928. pixel_data = new Uint8Array(pixel_total);
  20929. var c, count, i;
  20930. var localOffset = 0;
  20931. var pixels = new Uint8Array(pixel_size);
  20932. while (offset < pixel_total && localOffset < pixel_total) {
  20933. c = data[offset++];
  20934. count = (c & 0x7f) + 1;
  20935. // RLE pixels
  20936. if (c & 0x80) {
  20937. for (i = 0; i < pixel_size; ++i) {
  20938. pixels[i] = data[offset++];
  20939. }
  20940. for (i = 0; i < count; ++i) {
  20941. pixel_data.set(pixels, localOffset + i * pixel_size);
  20942. }
  20943. localOffset += pixel_size * count;
  20944. } else {
  20945. count *= pixel_size;
  20946. for (i = 0; i < count; ++i) {
  20947. pixel_data[localOffset + i] = data[offset++];
  20948. }
  20949. localOffset += count;
  20950. }
  20951. }
  20952. } else {
  20953. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  20954. }
  20955. // Load to texture
  20956. var x_start, y_start, x_step, y_step, y_end, x_end;
  20957. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  20958. default:
  20959. case TGATools._ORIGIN_UL:
  20960. x_start = 0;
  20961. x_step = 1;
  20962. x_end = header.width;
  20963. y_start = 0;
  20964. y_step = 1;
  20965. y_end = header.height;
  20966. break;
  20967. case TGATools._ORIGIN_BL:
  20968. x_start = 0;
  20969. x_step = 1;
  20970. x_end = header.width;
  20971. y_start = header.height - 1;
  20972. y_step = -1;
  20973. y_end = -1;
  20974. break;
  20975. case TGATools._ORIGIN_UR:
  20976. x_start = header.width - 1;
  20977. x_step = -1;
  20978. x_end = -1;
  20979. y_start = 0;
  20980. y_step = 1;
  20981. y_end = header.height;
  20982. break;
  20983. case TGATools._ORIGIN_BR:
  20984. x_start = header.width - 1;
  20985. x_step = -1;
  20986. x_end = -1;
  20987. y_start = header.height - 1;
  20988. y_step = -1;
  20989. y_end = -1;
  20990. break;
  20991. }
  20992. // Load the specify method
  20993. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  20994. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  20995. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  20996. };
  20997. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20998. var image = pixel_data, colormap = palettes;
  20999. var width = header.width, height = header.height;
  21000. var color, i = 0, x, y;
  21001. var imageData = new Uint8Array(width * height * 4);
  21002. for (y = y_start; y !== y_end; y += y_step) {
  21003. for (x = x_start; x !== x_end; x += x_step, i++) {
  21004. color = image[i];
  21005. imageData[(x + width * y) * 4 + 3] = 255;
  21006. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21007. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21008. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21009. }
  21010. }
  21011. return imageData;
  21012. };
  21013. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21014. var image = pixel_data;
  21015. var width = header.width, height = header.height;
  21016. var color, i = 0, x, y;
  21017. var imageData = new Uint8Array(width * height * 4);
  21018. for (y = y_start; y !== y_end; y += y_step) {
  21019. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21020. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21021. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21022. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21023. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21024. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21025. }
  21026. }
  21027. return imageData;
  21028. };
  21029. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21030. var image = pixel_data;
  21031. var width = header.width, height = header.height;
  21032. var i = 0, x, y;
  21033. var imageData = new Uint8Array(width * height * 4);
  21034. for (y = y_start; y !== y_end; y += y_step) {
  21035. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21036. imageData[(x + width * y) * 4 + 3] = 255;
  21037. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21038. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21039. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21040. }
  21041. }
  21042. return imageData;
  21043. };
  21044. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21045. var image = pixel_data;
  21046. var width = header.width, height = header.height;
  21047. var i = 0, x, y;
  21048. var imageData = new Uint8Array(width * height * 4);
  21049. for (y = y_start; y !== y_end; y += y_step) {
  21050. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21051. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21052. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21053. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21054. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21055. }
  21056. }
  21057. return imageData;
  21058. };
  21059. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21060. var image = pixel_data;
  21061. var width = header.width, height = header.height;
  21062. var color, i = 0, x, y;
  21063. var imageData = new Uint8Array(width * height * 4);
  21064. for (y = y_start; y !== y_end; y += y_step) {
  21065. for (x = x_start; x !== x_end; x += x_step, i++) {
  21066. color = image[i];
  21067. imageData[(x + width * y) * 4 + 0] = color;
  21068. imageData[(x + width * y) * 4 + 1] = color;
  21069. imageData[(x + width * y) * 4 + 2] = color;
  21070. imageData[(x + width * y) * 4 + 3] = 255;
  21071. }
  21072. }
  21073. return imageData;
  21074. };
  21075. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21076. var image = pixel_data;
  21077. var width = header.width, height = header.height;
  21078. var i = 0, x, y;
  21079. var imageData = new Uint8Array(width * height * 4);
  21080. for (y = y_start; y !== y_end; y += y_step) {
  21081. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21082. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21083. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21084. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21085. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21086. }
  21087. }
  21088. return imageData;
  21089. };
  21090. TGATools._TYPE_NO_DATA = 0;
  21091. TGATools._TYPE_INDEXED = 1;
  21092. TGATools._TYPE_RGB = 2;
  21093. TGATools._TYPE_GREY = 3;
  21094. TGATools._TYPE_RLE_INDEXED = 9;
  21095. TGATools._TYPE_RLE_RGB = 10;
  21096. TGATools._TYPE_RLE_GREY = 11;
  21097. TGATools._ORIGIN_MASK = 0x30;
  21098. TGATools._ORIGIN_SHIFT = 0x04;
  21099. TGATools._ORIGIN_BL = 0x00;
  21100. TGATools._ORIGIN_BR = 0x01;
  21101. TGATools._ORIGIN_UL = 0x02;
  21102. TGATools._ORIGIN_UR = 0x03;
  21103. return TGATools;
  21104. })();
  21105. Internals.TGATools = TGATools;
  21106. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21107. var Internals = BABYLON.Internals;
  21108. })(BABYLON || (BABYLON = {}));
  21109. //# sourceMappingURL=babylon.tools.tga.js.map
  21110. var BABYLON;
  21111. (function (BABYLON) {
  21112. (function (Internals) {
  21113. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21114. // All values and structures referenced from:
  21115. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21116. var DDS_MAGIC = 0x20534444;
  21117. 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;
  21118. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21119. 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;
  21120. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21121. function FourCCToInt32(value) {
  21122. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21123. }
  21124. function Int32ToFourCC(value) {
  21125. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21126. }
  21127. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21128. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21129. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21130. var headerLengthInt = 31;
  21131. // Offsets into the header array
  21132. var off_magic = 0;
  21133. var off_size = 1;
  21134. var off_flags = 2;
  21135. var off_height = 3;
  21136. var off_width = 4;
  21137. var off_mipmapCount = 7;
  21138. var off_pfFlags = 20;
  21139. var off_pfFourCC = 21;
  21140. var off_RGBbpp = 22;
  21141. var off_RMask = 23;
  21142. var off_GMask = 24;
  21143. var off_BMask = 25;
  21144. var off_AMask = 26;
  21145. var off_caps1 = 27;
  21146. var off_caps2 = 28;
  21147. ;
  21148. var DDSTools = (function () {
  21149. function DDSTools() {
  21150. }
  21151. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21152. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21153. var mipmapCount = 1;
  21154. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21155. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21156. }
  21157. return {
  21158. width: header[off_width],
  21159. height: header[off_height],
  21160. mipmapCount: mipmapCount,
  21161. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21162. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21163. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21164. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21165. };
  21166. };
  21167. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21168. var byteArray = new Uint8Array(dataLength);
  21169. var srcData = new Uint8Array(arrayBuffer);
  21170. var index = 0;
  21171. for (var y = height - 1; y >= 0; y--) {
  21172. for (var x = 0; x < width; x++) {
  21173. var srcPos = dataOffset + (x + y * width) * 4;
  21174. byteArray[index + 2] = srcData[srcPos];
  21175. byteArray[index + 1] = srcData[srcPos + 1];
  21176. byteArray[index] = srcData[srcPos + 2];
  21177. byteArray[index + 3] = srcData[srcPos + 3];
  21178. index += 4;
  21179. }
  21180. }
  21181. return byteArray;
  21182. };
  21183. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21184. var byteArray = new Uint8Array(dataLength);
  21185. var srcData = new Uint8Array(arrayBuffer);
  21186. var index = 0;
  21187. for (var y = height - 1; y >= 0; y--) {
  21188. for (var x = 0; x < width; x++) {
  21189. var srcPos = dataOffset + (x + y * width) * 3;
  21190. byteArray[index + 2] = srcData[srcPos];
  21191. byteArray[index + 1] = srcData[srcPos + 1];
  21192. byteArray[index] = srcData[srcPos + 2];
  21193. index += 3;
  21194. }
  21195. }
  21196. return byteArray;
  21197. };
  21198. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21199. var byteArray = new Uint8Array(dataLength);
  21200. var srcData = new Uint8Array(arrayBuffer);
  21201. var index = 0;
  21202. for (var y = height - 1; y >= 0; y--) {
  21203. for (var x = 0; x < width; x++) {
  21204. var srcPos = dataOffset + (x + y * width);
  21205. byteArray[index] = srcData[srcPos];
  21206. index++;
  21207. }
  21208. }
  21209. return byteArray;
  21210. };
  21211. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21212. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21213. if (header[off_magic] != DDS_MAGIC) {
  21214. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21215. return;
  21216. }
  21217. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21218. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21219. return;
  21220. }
  21221. if (info.isFourCC) {
  21222. fourCC = header[off_pfFourCC];
  21223. switch (fourCC) {
  21224. case FOURCC_DXT1:
  21225. blockBytes = 8;
  21226. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21227. break;
  21228. case FOURCC_DXT3:
  21229. blockBytes = 16;
  21230. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21231. break;
  21232. case FOURCC_DXT5:
  21233. blockBytes = 16;
  21234. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21235. break;
  21236. default:
  21237. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21238. return;
  21239. }
  21240. }
  21241. mipmapCount = 1;
  21242. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21243. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21244. }
  21245. var bpp = header[off_RGBbpp];
  21246. for (var face = 0; face < faces; face++) {
  21247. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21248. width = header[off_width];
  21249. height = header[off_height];
  21250. dataOffset = header[off_size] + 4;
  21251. for (i = 0; i < mipmapCount; ++i) {
  21252. if (info.isRGB) {
  21253. if (bpp == 24) {
  21254. dataLength = width * height * 3;
  21255. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21256. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21257. } else {
  21258. dataLength = width * height * 4;
  21259. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21260. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21261. }
  21262. } else if (info.isLuminance) {
  21263. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21264. var unpaddedRowSize = width;
  21265. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21266. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21267. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21268. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21269. } else {
  21270. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21271. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21272. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21273. }
  21274. dataOffset += dataLength;
  21275. width *= 0.5;
  21276. height *= 0.5;
  21277. width = Math.max(1.0, width);
  21278. height = Math.max(1.0, height);
  21279. }
  21280. }
  21281. };
  21282. return DDSTools;
  21283. })();
  21284. Internals.DDSTools = DDSTools;
  21285. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21286. var Internals = BABYLON.Internals;
  21287. })(BABYLON || (BABYLON = {}));
  21288. //# sourceMappingURL=babylon.tools.dds.js.map
  21289. var BABYLON;
  21290. (function (BABYLON) {
  21291. var SmartArray = (function () {
  21292. function SmartArray(capacity) {
  21293. this.length = 0;
  21294. this._duplicateId = 0;
  21295. this.data = new Array(capacity);
  21296. this._id = SmartArray._GlobalId++;
  21297. }
  21298. SmartArray.prototype.push = function (value) {
  21299. this.data[this.length++] = value;
  21300. if (this.length > this.data.length) {
  21301. this.data.length *= 2;
  21302. }
  21303. if (!value.__smartArrayFlags) {
  21304. value.__smartArrayFlags = {};
  21305. }
  21306. value.__smartArrayFlags[this._id] = this._duplicateId;
  21307. };
  21308. SmartArray.prototype.pushNoDuplicate = function (value) {
  21309. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21310. return;
  21311. }
  21312. this.push(value);
  21313. };
  21314. SmartArray.prototype.sort = function (compareFn) {
  21315. this.data.sort(compareFn);
  21316. };
  21317. SmartArray.prototype.reset = function () {
  21318. this.length = 0;
  21319. this._duplicateId++;
  21320. };
  21321. SmartArray.prototype.concat = function (array) {
  21322. if (array.length === 0) {
  21323. return;
  21324. }
  21325. if (this.length + array.length > this.data.length) {
  21326. this.data.length = (this.length + array.length) * 2;
  21327. }
  21328. for (var index = 0; index < array.length; index++) {
  21329. this.data[this.length++] = (array.data || array)[index];
  21330. }
  21331. };
  21332. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21333. if (array.length === 0) {
  21334. return;
  21335. }
  21336. if (this.length + array.length > this.data.length) {
  21337. this.data.length = (this.length + array.length) * 2;
  21338. }
  21339. for (var index = 0; index < array.length; index++) {
  21340. var item = (array.data || array)[index];
  21341. this.pushNoDuplicate(item);
  21342. }
  21343. };
  21344. SmartArray.prototype.indexOf = function (value) {
  21345. var position = this.data.indexOf(value);
  21346. if (position >= this.length) {
  21347. return -1;
  21348. }
  21349. return position;
  21350. };
  21351. SmartArray._GlobalId = 0;
  21352. return SmartArray;
  21353. })();
  21354. BABYLON.SmartArray = SmartArray;
  21355. })(BABYLON || (BABYLON = {}));
  21356. //# sourceMappingURL=babylon.smartArray.js.map
  21357. var BABYLON;
  21358. (function (BABYLON) {
  21359. var CannonJSPlugin = (function () {
  21360. function CannonJSPlugin() {
  21361. this._registeredMeshes = [];
  21362. this._physicsMaterials = [];
  21363. this.updateBodyPosition = function (mesh) {
  21364. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21365. var registeredMesh = this._registeredMeshes[index];
  21366. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21367. var body = registeredMesh.body;
  21368. var center = mesh.getBoundingInfo().boundingBox.center;
  21369. body.position.set(center.x, center.z, center.y);
  21370. body.quaternion.x = mesh.rotationQuaternion.x;
  21371. body.quaternion.z = mesh.rotationQuaternion.y;
  21372. body.quaternion.y = mesh.rotationQuaternion.z;
  21373. body.quaternion.w = -mesh.rotationQuaternion.w;
  21374. return;
  21375. }
  21376. }
  21377. };
  21378. }
  21379. CannonJSPlugin.prototype.initialize = function (iterations) {
  21380. if (typeof iterations === "undefined") { iterations = 10; }
  21381. this._world = new CANNON.World();
  21382. this._world.broadphase = new CANNON.NaiveBroadphase();
  21383. this._world.solver.iterations = iterations;
  21384. };
  21385. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21386. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21387. };
  21388. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21389. this._world.step(delta);
  21390. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21391. var registeredMesh = this._registeredMeshes[index];
  21392. if (registeredMesh.isChild) {
  21393. continue;
  21394. }
  21395. // Body position
  21396. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21397. var deltaPos = registeredMesh.delta;
  21398. if (deltaPos) {
  21399. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21400. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21401. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21402. } else {
  21403. registeredMesh.mesh.position.x = bodyX;
  21404. registeredMesh.mesh.position.y = bodyZ;
  21405. registeredMesh.mesh.position.z = bodyY;
  21406. }
  21407. if (!registeredMesh.mesh.rotationQuaternion) {
  21408. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21409. }
  21410. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21411. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21412. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21413. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21414. }
  21415. };
  21416. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21417. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21418. };
  21419. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21420. this.unregisterMesh(mesh);
  21421. mesh.computeWorldMatrix(true);
  21422. switch (impostor) {
  21423. case BABYLON.PhysicsEngine.SphereImpostor:
  21424. var bbox = mesh.getBoundingInfo().boundingBox;
  21425. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21426. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21427. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21428. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21429. case BABYLON.PhysicsEngine.BoxImpostor:
  21430. bbox = mesh.getBoundingInfo().boundingBox;
  21431. var min = bbox.minimumWorld;
  21432. var max = bbox.maximumWorld;
  21433. var box = max.subtract(min).scale(0.5);
  21434. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21435. case BABYLON.PhysicsEngine.PlaneImpostor:
  21436. return this._createPlane(mesh, options);
  21437. case BABYLON.PhysicsEngine.MeshImpostor:
  21438. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21439. var rawFaces = mesh.getIndices();
  21440. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21441. }
  21442. return null;
  21443. };
  21444. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21445. var shape = new CANNON.Sphere(radius);
  21446. if (!options) {
  21447. return shape;
  21448. }
  21449. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21450. };
  21451. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21452. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21453. if (!options) {
  21454. return shape;
  21455. }
  21456. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21457. };
  21458. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21459. var shape = new CANNON.Plane();
  21460. if (!options) {
  21461. return shape;
  21462. }
  21463. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21464. };
  21465. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21466. var verts = [], faces = [];
  21467. mesh.computeWorldMatrix(true);
  21468. for (var i = 0; i < rawVerts.length; i += 3) {
  21469. var transformed = BABYLON.Vector3.Zero();
  21470. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21471. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21472. }
  21473. for (var j = 0; j < rawFaces.length; j += 3) {
  21474. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21475. }
  21476. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21477. if (!options) {
  21478. return shape;
  21479. }
  21480. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21481. };
  21482. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21483. var index;
  21484. var mat;
  21485. for (index = 0; index < this._physicsMaterials.length; index++) {
  21486. mat = this._physicsMaterials[index];
  21487. if (mat.friction === friction && mat.restitution === restitution) {
  21488. return mat;
  21489. }
  21490. }
  21491. var currentMat = new CANNON.Material();
  21492. currentMat.friction = friction;
  21493. currentMat.restitution = restitution;
  21494. this._physicsMaterials.push(currentMat);
  21495. for (index = 0; index < this._physicsMaterials.length; index++) {
  21496. mat = this._physicsMaterials[index];
  21497. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21498. contactMaterial.contactEquationStiffness = 1e10;
  21499. contactMaterial.contactEquationRegularizationTime = 10;
  21500. this._world.addContactMaterial(contactMaterial);
  21501. }
  21502. return currentMat;
  21503. };
  21504. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21505. var initialRotation = null;
  21506. if (mesh.rotationQuaternion) {
  21507. initialRotation = mesh.rotationQuaternion.clone();
  21508. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21509. }
  21510. // The delta between the mesh position and the mesh bounding box center
  21511. var bbox = mesh.getBoundingInfo().boundingBox;
  21512. var deltaPosition = mesh.position.subtract(bbox.center);
  21513. var material = this._addMaterial(friction, restitution);
  21514. var body = new CANNON.RigidBody(mass, shape, material);
  21515. if (initialRotation) {
  21516. body.quaternion.x = initialRotation.x;
  21517. body.quaternion.z = initialRotation.y;
  21518. body.quaternion.y = initialRotation.z;
  21519. body.quaternion.w = -initialRotation.w;
  21520. }
  21521. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21522. this._world.add(body);
  21523. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21524. return body;
  21525. };
  21526. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21527. var compoundShape = new CANNON.Compound();
  21528. for (var index = 0; index < parts.length; index++) {
  21529. var mesh = parts[index].mesh;
  21530. var shape = this.registerMesh(mesh, parts[index].impostor);
  21531. if (index == 0) {
  21532. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21533. } else {
  21534. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21535. }
  21536. }
  21537. var initialMesh = parts[0].mesh;
  21538. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21539. body.parts = parts;
  21540. return body;
  21541. };
  21542. CannonJSPlugin.prototype._unbindBody = function (body) {
  21543. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21544. var registeredMesh = this._registeredMeshes[index];
  21545. if (registeredMesh.body === body) {
  21546. registeredMesh.body = null;
  21547. registeredMesh.delta = 0;
  21548. }
  21549. }
  21550. };
  21551. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21552. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21553. var registeredMesh = this._registeredMeshes[index];
  21554. if (registeredMesh.mesh === mesh) {
  21555. // Remove body
  21556. if (registeredMesh.body) {
  21557. this._world.remove(registeredMesh.body);
  21558. this._unbindBody(registeredMesh.body);
  21559. }
  21560. this._registeredMeshes.splice(index, 1);
  21561. return;
  21562. }
  21563. }
  21564. };
  21565. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21566. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21567. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21568. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21569. var registeredMesh = this._registeredMeshes[index];
  21570. if (registeredMesh.mesh === mesh) {
  21571. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21572. return;
  21573. }
  21574. }
  21575. };
  21576. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21577. var body1 = null, body2 = null;
  21578. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21579. var registeredMesh = this._registeredMeshes[index];
  21580. if (registeredMesh.mesh === mesh1) {
  21581. body1 = registeredMesh.body;
  21582. } else if (registeredMesh.mesh === mesh2) {
  21583. body2 = registeredMesh.body;
  21584. }
  21585. }
  21586. if (!body1 || !body2) {
  21587. return false;
  21588. }
  21589. 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));
  21590. this._world.addConstraint(constraint);
  21591. return true;
  21592. };
  21593. CannonJSPlugin.prototype.dispose = function () {
  21594. while (this._registeredMeshes.length) {
  21595. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21596. }
  21597. };
  21598. CannonJSPlugin.prototype.isSupported = function () {
  21599. return window.CANNON !== undefined;
  21600. };
  21601. return CannonJSPlugin;
  21602. })();
  21603. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21604. })(BABYLON || (BABYLON = {}));
  21605. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21606. var BABYLON;
  21607. (function (BABYLON) {
  21608. var Condition = (function () {
  21609. function Condition(actionManager) {
  21610. this._actionManager = actionManager;
  21611. }
  21612. Condition.prototype.isValid = function () {
  21613. return true;
  21614. };
  21615. Condition.prototype._getProperty = function (propertyPath) {
  21616. return this._actionManager._getProperty(propertyPath);
  21617. };
  21618. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21619. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21620. };
  21621. return Condition;
  21622. })();
  21623. BABYLON.Condition = Condition;
  21624. var ValueCondition = (function (_super) {
  21625. __extends(ValueCondition, _super);
  21626. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21627. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21628. _super.call(this, actionManager);
  21629. this.propertyPath = propertyPath;
  21630. this.value = value;
  21631. this.operator = operator;
  21632. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21633. this._property = this._getProperty(this.propertyPath);
  21634. }
  21635. Object.defineProperty(ValueCondition, "IsEqual", {
  21636. get: function () {
  21637. return ValueCondition._IsEqual;
  21638. },
  21639. enumerable: true,
  21640. configurable: true
  21641. });
  21642. Object.defineProperty(ValueCondition, "IsDifferent", {
  21643. get: function () {
  21644. return ValueCondition._IsDifferent;
  21645. },
  21646. enumerable: true,
  21647. configurable: true
  21648. });
  21649. Object.defineProperty(ValueCondition, "IsGreater", {
  21650. get: function () {
  21651. return ValueCondition._IsGreater;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(ValueCondition, "IsLesser", {
  21657. get: function () {
  21658. return ValueCondition._IsLesser;
  21659. },
  21660. enumerable: true,
  21661. configurable: true
  21662. });
  21663. // Methods
  21664. ValueCondition.prototype.isValid = function () {
  21665. switch (this.operator) {
  21666. case ValueCondition.IsGreater:
  21667. return this._target[this._property] > this.value;
  21668. case ValueCondition.IsLesser:
  21669. return this._target[this._property] < this.value;
  21670. case ValueCondition.IsEqual:
  21671. case ValueCondition.IsDifferent:
  21672. var check;
  21673. if (this.value.equals) {
  21674. check = this.value.equals(this._target[this._property]);
  21675. } else {
  21676. check = this.value === this._target[this._property];
  21677. }
  21678. return this.operator === ValueCondition.IsEqual ? check : !check;
  21679. }
  21680. return false;
  21681. };
  21682. ValueCondition._IsEqual = 0;
  21683. ValueCondition._IsDifferent = 1;
  21684. ValueCondition._IsGreater = 2;
  21685. ValueCondition._IsLesser = 3;
  21686. return ValueCondition;
  21687. })(Condition);
  21688. BABYLON.ValueCondition = ValueCondition;
  21689. var PredicateCondition = (function (_super) {
  21690. __extends(PredicateCondition, _super);
  21691. function PredicateCondition(actionManager, predicate) {
  21692. _super.call(this, actionManager);
  21693. this.predicate = predicate;
  21694. }
  21695. PredicateCondition.prototype.isValid = function () {
  21696. return this.predicate();
  21697. };
  21698. return PredicateCondition;
  21699. })(Condition);
  21700. BABYLON.PredicateCondition = PredicateCondition;
  21701. var StateCondition = (function (_super) {
  21702. __extends(StateCondition, _super);
  21703. function StateCondition(actionManager, target, value) {
  21704. _super.call(this, actionManager);
  21705. this.value = value;
  21706. this._target = target;
  21707. }
  21708. // Methods
  21709. StateCondition.prototype.isValid = function () {
  21710. return this._target.state === this.value;
  21711. };
  21712. return StateCondition;
  21713. })(Condition);
  21714. BABYLON.StateCondition = StateCondition;
  21715. })(BABYLON || (BABYLON = {}));
  21716. //# sourceMappingURL=babylon.condition.js.map
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var Action = (function () {
  21720. function Action(triggerOptions, condition) {
  21721. this.triggerOptions = triggerOptions;
  21722. if (triggerOptions.parameter) {
  21723. this.trigger = triggerOptions.trigger;
  21724. this._triggerParameter = triggerOptions.parameter;
  21725. } else {
  21726. this.trigger = triggerOptions;
  21727. }
  21728. this._nextActiveAction = this;
  21729. this._condition = condition;
  21730. }
  21731. // Methods
  21732. Action.prototype._prepare = function () {
  21733. };
  21734. Action.prototype.getTriggerParameter = function () {
  21735. return this._triggerParameter;
  21736. };
  21737. Action.prototype._executeCurrent = function (evt) {
  21738. if (this._condition) {
  21739. var currentRenderId = this._actionManager.getScene().getRenderId();
  21740. // We cache the current evaluation for the current frame
  21741. if (this._condition._evaluationId === currentRenderId) {
  21742. if (!this._condition._currentResult) {
  21743. return;
  21744. }
  21745. } else {
  21746. this._condition._evaluationId = currentRenderId;
  21747. if (!this._condition.isValid()) {
  21748. this._condition._currentResult = false;
  21749. return;
  21750. }
  21751. this._condition._currentResult = true;
  21752. }
  21753. }
  21754. this._nextActiveAction.execute(evt);
  21755. if (this._nextActiveAction._child) {
  21756. if (!this._nextActiveAction._child._actionManager) {
  21757. this._nextActiveAction._child._actionManager = this._actionManager;
  21758. }
  21759. this._nextActiveAction = this._nextActiveAction._child;
  21760. } else {
  21761. this._nextActiveAction = this;
  21762. }
  21763. };
  21764. Action.prototype.execute = function (evt) {
  21765. };
  21766. Action.prototype.then = function (action) {
  21767. this._child = action;
  21768. action._actionManager = this._actionManager;
  21769. action._prepare();
  21770. return action;
  21771. };
  21772. Action.prototype._getProperty = function (propertyPath) {
  21773. return this._actionManager._getProperty(propertyPath);
  21774. };
  21775. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21776. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21777. };
  21778. return Action;
  21779. })();
  21780. BABYLON.Action = Action;
  21781. })(BABYLON || (BABYLON = {}));
  21782. //# sourceMappingURL=babylon.action.js.map
  21783. var BABYLON;
  21784. (function (BABYLON) {
  21785. var ActionEvent = (function () {
  21786. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21787. this.source = source;
  21788. this.pointerX = pointerX;
  21789. this.pointerY = pointerY;
  21790. this.meshUnderPointer = meshUnderPointer;
  21791. this.sourceEvent = sourceEvent;
  21792. }
  21793. ActionEvent.CreateNew = function (source, evt) {
  21794. var scene = source.getScene();
  21795. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21796. };
  21797. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21798. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21799. };
  21800. return ActionEvent;
  21801. })();
  21802. BABYLON.ActionEvent = ActionEvent;
  21803. var ActionManager = (function () {
  21804. function ActionManager(scene) {
  21805. // Members
  21806. this.actions = new Array();
  21807. this._scene = scene;
  21808. scene._actionManagers.push(this);
  21809. }
  21810. Object.defineProperty(ActionManager, "NothingTrigger", {
  21811. get: function () {
  21812. return ActionManager._NothingTrigger;
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21818. get: function () {
  21819. return ActionManager._OnPickTrigger;
  21820. },
  21821. enumerable: true,
  21822. configurable: true
  21823. });
  21824. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21825. get: function () {
  21826. return ActionManager._OnLeftPickTrigger;
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21832. get: function () {
  21833. return ActionManager._OnRightPickTrigger;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21839. get: function () {
  21840. return ActionManager._OnCenterPickTrigger;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21846. get: function () {
  21847. return ActionManager._OnPointerOverTrigger;
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21853. get: function () {
  21854. return ActionManager._OnPointerOutTrigger;
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21860. get: function () {
  21861. return ActionManager._OnEveryFrameTrigger;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21867. get: function () {
  21868. return ActionManager._OnIntersectionEnterTrigger;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21874. get: function () {
  21875. return ActionManager._OnIntersectionExitTrigger;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21881. get: function () {
  21882. return ActionManager._OnKeyDownTrigger;
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21888. get: function () {
  21889. return ActionManager._OnKeyUpTrigger;
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. // Methods
  21895. ActionManager.prototype.dispose = function () {
  21896. var index = this._scene._actionManagers.indexOf(this);
  21897. if (index > -1) {
  21898. this._scene._actionManagers.splice(index, 1);
  21899. }
  21900. };
  21901. ActionManager.prototype.getScene = function () {
  21902. return this._scene;
  21903. };
  21904. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21905. for (var index = 0; index < this.actions.length; index++) {
  21906. var action = this.actions[index];
  21907. if (triggers.indexOf(action.trigger) > -1) {
  21908. return true;
  21909. }
  21910. }
  21911. return false;
  21912. };
  21913. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21914. get: function () {
  21915. for (var index = 0; index < this.actions.length; index++) {
  21916. var action = this.actions[index];
  21917. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21918. return true;
  21919. }
  21920. }
  21921. return false;
  21922. },
  21923. enumerable: true,
  21924. configurable: true
  21925. });
  21926. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21927. get: function () {
  21928. for (var index = 0; index < this.actions.length; index++) {
  21929. var action = this.actions[index];
  21930. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21931. return true;
  21932. }
  21933. }
  21934. return false;
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. ActionManager.prototype.registerAction = function (action) {
  21940. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21941. if (this.getScene().actionManager !== this) {
  21942. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21943. return null;
  21944. }
  21945. }
  21946. this.actions.push(action);
  21947. action._actionManager = this;
  21948. action._prepare();
  21949. return action;
  21950. };
  21951. ActionManager.prototype.processTrigger = function (trigger, evt) {
  21952. for (var index = 0; index < this.actions.length; index++) {
  21953. var action = this.actions[index];
  21954. if (action.trigger === trigger) {
  21955. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  21956. var parameter = action.getTriggerParameter();
  21957. if (parameter) {
  21958. if (evt.sourceEvent.key !== parameter) {
  21959. continue;
  21960. }
  21961. }
  21962. }
  21963. action._executeCurrent(evt);
  21964. }
  21965. }
  21966. };
  21967. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  21968. var properties = propertyPath.split(".");
  21969. for (var index = 0; index < properties.length - 1; index++) {
  21970. target = target[properties[index]];
  21971. }
  21972. return target;
  21973. };
  21974. ActionManager.prototype._getProperty = function (propertyPath) {
  21975. var properties = propertyPath.split(".");
  21976. return properties[properties.length - 1];
  21977. };
  21978. ActionManager._NothingTrigger = 0;
  21979. ActionManager._OnPickTrigger = 1;
  21980. ActionManager._OnLeftPickTrigger = 2;
  21981. ActionManager._OnRightPickTrigger = 3;
  21982. ActionManager._OnCenterPickTrigger = 4;
  21983. ActionManager._OnPointerOverTrigger = 5;
  21984. ActionManager._OnPointerOutTrigger = 6;
  21985. ActionManager._OnEveryFrameTrigger = 7;
  21986. ActionManager._OnIntersectionEnterTrigger = 8;
  21987. ActionManager._OnIntersectionExitTrigger = 9;
  21988. ActionManager._OnKeyDownTrigger = 10;
  21989. ActionManager._OnKeyUpTrigger = 11;
  21990. return ActionManager;
  21991. })();
  21992. BABYLON.ActionManager = ActionManager;
  21993. })(BABYLON || (BABYLON = {}));
  21994. //# sourceMappingURL=babylon.actionManager.js.map
  21995. var BABYLON;
  21996. (function (BABYLON) {
  21997. var InterpolateValueAction = (function (_super) {
  21998. __extends(InterpolateValueAction, _super);
  21999. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22000. if (typeof duration === "undefined") { duration = 1000; }
  22001. _super.call(this, triggerOptions, condition);
  22002. this.propertyPath = propertyPath;
  22003. this.value = value;
  22004. this.duration = duration;
  22005. this.stopOtherAnimations = stopOtherAnimations;
  22006. this._target = target;
  22007. }
  22008. InterpolateValueAction.prototype._prepare = function () {
  22009. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22010. this._property = this._getProperty(this.propertyPath);
  22011. };
  22012. InterpolateValueAction.prototype.execute = function () {
  22013. var scene = this._actionManager.getScene();
  22014. var keys = [
  22015. {
  22016. frame: 0,
  22017. value: this._target[this._property]
  22018. }, {
  22019. frame: 100,
  22020. value: this.value
  22021. }
  22022. ];
  22023. var dataType;
  22024. if (typeof this.value === "number") {
  22025. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22026. } else if (this.value instanceof BABYLON.Color3) {
  22027. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22028. } else if (this.value instanceof BABYLON.Vector3) {
  22029. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22030. } else if (this.value instanceof BABYLON.Matrix) {
  22031. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22032. } else if (this.value instanceof BABYLON.Quaternion) {
  22033. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22034. } else {
  22035. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22036. return;
  22037. }
  22038. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22039. animation.setKeys(keys);
  22040. if (this.stopOtherAnimations) {
  22041. scene.stopAnimation(this._target);
  22042. }
  22043. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22044. };
  22045. return InterpolateValueAction;
  22046. })(BABYLON.Action);
  22047. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22048. })(BABYLON || (BABYLON = {}));
  22049. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22050. var BABYLON;
  22051. (function (BABYLON) {
  22052. var SwitchBooleanAction = (function (_super) {
  22053. __extends(SwitchBooleanAction, _super);
  22054. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22055. _super.call(this, triggerOptions, condition);
  22056. this.propertyPath = propertyPath;
  22057. this._target = target;
  22058. }
  22059. SwitchBooleanAction.prototype._prepare = function () {
  22060. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22061. this._property = this._getProperty(this.propertyPath);
  22062. };
  22063. SwitchBooleanAction.prototype.execute = function () {
  22064. this._target[this._property] = !this._target[this._property];
  22065. };
  22066. return SwitchBooleanAction;
  22067. })(BABYLON.Action);
  22068. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22069. var SetStateAction = (function (_super) {
  22070. __extends(SetStateAction, _super);
  22071. function SetStateAction(triggerOptions, target, value, condition) {
  22072. _super.call(this, triggerOptions, condition);
  22073. this.value = value;
  22074. this._target = target;
  22075. }
  22076. SetStateAction.prototype.execute = function () {
  22077. this._target.state = this.value;
  22078. };
  22079. return SetStateAction;
  22080. })(BABYLON.Action);
  22081. BABYLON.SetStateAction = SetStateAction;
  22082. var SetValueAction = (function (_super) {
  22083. __extends(SetValueAction, _super);
  22084. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22085. _super.call(this, triggerOptions, condition);
  22086. this.propertyPath = propertyPath;
  22087. this.value = value;
  22088. this._target = target;
  22089. }
  22090. SetValueAction.prototype._prepare = function () {
  22091. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22092. this._property = this._getProperty(this.propertyPath);
  22093. };
  22094. SetValueAction.prototype.execute = function () {
  22095. this._target[this._property] = this.value;
  22096. };
  22097. return SetValueAction;
  22098. })(BABYLON.Action);
  22099. BABYLON.SetValueAction = SetValueAction;
  22100. var IncrementValueAction = (function (_super) {
  22101. __extends(IncrementValueAction, _super);
  22102. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22103. _super.call(this, triggerOptions, condition);
  22104. this.propertyPath = propertyPath;
  22105. this.value = value;
  22106. this._target = target;
  22107. }
  22108. IncrementValueAction.prototype._prepare = function () {
  22109. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22110. this._property = this._getProperty(this.propertyPath);
  22111. if (typeof this._target[this._property] !== "number") {
  22112. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22113. }
  22114. };
  22115. IncrementValueAction.prototype.execute = function () {
  22116. this._target[this._property] += this.value;
  22117. };
  22118. return IncrementValueAction;
  22119. })(BABYLON.Action);
  22120. BABYLON.IncrementValueAction = IncrementValueAction;
  22121. var PlayAnimationAction = (function (_super) {
  22122. __extends(PlayAnimationAction, _super);
  22123. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22124. _super.call(this, triggerOptions, condition);
  22125. this.from = from;
  22126. this.to = to;
  22127. this.loop = loop;
  22128. this._target = target;
  22129. }
  22130. PlayAnimationAction.prototype._prepare = function () {
  22131. };
  22132. PlayAnimationAction.prototype.execute = function () {
  22133. var scene = this._actionManager.getScene();
  22134. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22135. };
  22136. return PlayAnimationAction;
  22137. })(BABYLON.Action);
  22138. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22139. var StopAnimationAction = (function (_super) {
  22140. __extends(StopAnimationAction, _super);
  22141. function StopAnimationAction(triggerOptions, target, condition) {
  22142. _super.call(this, triggerOptions, condition);
  22143. this._target = target;
  22144. }
  22145. StopAnimationAction.prototype._prepare = function () {
  22146. };
  22147. StopAnimationAction.prototype.execute = function () {
  22148. var scene = this._actionManager.getScene();
  22149. scene.stopAnimation(this._target);
  22150. };
  22151. return StopAnimationAction;
  22152. })(BABYLON.Action);
  22153. BABYLON.StopAnimationAction = StopAnimationAction;
  22154. var DoNothingAction = (function (_super) {
  22155. __extends(DoNothingAction, _super);
  22156. function DoNothingAction(triggerOptions, condition) {
  22157. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22158. _super.call(this, triggerOptions, condition);
  22159. }
  22160. DoNothingAction.prototype.execute = function () {
  22161. };
  22162. return DoNothingAction;
  22163. })(BABYLON.Action);
  22164. BABYLON.DoNothingAction = DoNothingAction;
  22165. var CombineAction = (function (_super) {
  22166. __extends(CombineAction, _super);
  22167. function CombineAction(triggerOptions, children, condition) {
  22168. _super.call(this, triggerOptions, condition);
  22169. this.children = children;
  22170. }
  22171. CombineAction.prototype._prepare = function () {
  22172. for (var index = 0; index < this.children.length; index++) {
  22173. this.children[index]._actionManager = this._actionManager;
  22174. this.children[index]._prepare();
  22175. }
  22176. };
  22177. CombineAction.prototype.execute = function (evt) {
  22178. for (var index = 0; index < this.children.length; index++) {
  22179. this.children[index].execute(evt);
  22180. }
  22181. };
  22182. return CombineAction;
  22183. })(BABYLON.Action);
  22184. BABYLON.CombineAction = CombineAction;
  22185. var ExecuteCodeAction = (function (_super) {
  22186. __extends(ExecuteCodeAction, _super);
  22187. function ExecuteCodeAction(triggerOptions, func, condition) {
  22188. _super.call(this, triggerOptions, condition);
  22189. this.func = func;
  22190. }
  22191. ExecuteCodeAction.prototype.execute = function (evt) {
  22192. this.func(evt);
  22193. };
  22194. return ExecuteCodeAction;
  22195. })(BABYLON.Action);
  22196. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22197. var SetParentAction = (function (_super) {
  22198. __extends(SetParentAction, _super);
  22199. function SetParentAction(triggerOptions, target, parent, condition) {
  22200. _super.call(this, triggerOptions, condition);
  22201. this._target = target;
  22202. this._parent = parent;
  22203. }
  22204. SetParentAction.prototype._prepare = function () {
  22205. };
  22206. SetParentAction.prototype.execute = function () {
  22207. if (this._target.parent === this._parent) {
  22208. return;
  22209. }
  22210. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22211. invertParentWorldMatrix.invert();
  22212. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22213. this._target.parent = this._parent;
  22214. };
  22215. return SetParentAction;
  22216. })(BABYLON.Action);
  22217. BABYLON.SetParentAction = SetParentAction;
  22218. })(BABYLON || (BABYLON = {}));
  22219. //# sourceMappingURL=babylon.directActions.js.map
  22220. var BABYLON;
  22221. (function (BABYLON) {
  22222. var Geometry = (function () {
  22223. function Geometry(id, scene, vertexData, updatable, mesh) {
  22224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22225. this._totalVertices = 0;
  22226. this._indices = [];
  22227. this.id = id;
  22228. this._engine = scene.getEngine();
  22229. this._meshes = [];
  22230. this._scene = scene;
  22231. // vertexData
  22232. if (vertexData) {
  22233. this.setAllVerticesData(vertexData, updatable);
  22234. } else {
  22235. this._totalVertices = 0;
  22236. this._indices = [];
  22237. }
  22238. // applyToMesh
  22239. if (mesh) {
  22240. this.applyToMesh(mesh);
  22241. }
  22242. }
  22243. Geometry.prototype.getScene = function () {
  22244. return this._scene;
  22245. };
  22246. Geometry.prototype.getEngine = function () {
  22247. return this._engine;
  22248. };
  22249. Geometry.prototype.isReady = function () {
  22250. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22251. };
  22252. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22253. vertexData.applyToGeometry(this, updatable);
  22254. };
  22255. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22256. this._vertexBuffers = this._vertexBuffers || {};
  22257. if (this._vertexBuffers[kind]) {
  22258. this._vertexBuffers[kind].dispose();
  22259. }
  22260. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22261. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22262. stride = this._vertexBuffers[kind].getStrideSize();
  22263. this._totalVertices = data.length / stride;
  22264. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22265. var meshes = this._meshes;
  22266. var numOfMeshes = meshes.length;
  22267. for (var index = 0; index < numOfMeshes; index++) {
  22268. var mesh = meshes[index];
  22269. mesh._resetPointsArrayCache();
  22270. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22271. mesh._createGlobalSubMesh();
  22272. mesh.computeWorldMatrix(true);
  22273. }
  22274. }
  22275. };
  22276. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22277. var vertexBuffer = this.getVertexBuffer(kind);
  22278. if (!vertexBuffer) {
  22279. return;
  22280. }
  22281. vertexBuffer.updateDirectly(data, offset);
  22282. };
  22283. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22284. var vertexBuffer = this.getVertexBuffer(kind);
  22285. if (!vertexBuffer) {
  22286. return;
  22287. }
  22288. vertexBuffer.update(data);
  22289. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22290. var extend;
  22291. var stride = vertexBuffer.getStrideSize();
  22292. this._totalVertices = data.length / stride;
  22293. if (updateExtends) {
  22294. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22295. }
  22296. var meshes = this._meshes;
  22297. var numOfMeshes = meshes.length;
  22298. for (var index = 0; index < numOfMeshes; index++) {
  22299. var mesh = meshes[index];
  22300. mesh._resetPointsArrayCache();
  22301. if (updateExtends) {
  22302. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22303. }
  22304. }
  22305. }
  22306. };
  22307. Geometry.prototype.getTotalVertices = function () {
  22308. if (!this.isReady()) {
  22309. return 0;
  22310. }
  22311. return this._totalVertices;
  22312. };
  22313. Geometry.prototype.getVerticesData = function (kind) {
  22314. var vertexBuffer = this.getVertexBuffer(kind);
  22315. if (!vertexBuffer) {
  22316. return null;
  22317. }
  22318. return vertexBuffer.getData();
  22319. };
  22320. Geometry.prototype.getVertexBuffer = function (kind) {
  22321. if (!this.isReady()) {
  22322. return null;
  22323. }
  22324. return this._vertexBuffers[kind];
  22325. };
  22326. Geometry.prototype.getVertexBuffers = function () {
  22327. if (!this.isReady()) {
  22328. return null;
  22329. }
  22330. return this._vertexBuffers;
  22331. };
  22332. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22333. if (!this._vertexBuffers) {
  22334. if (this._delayInfo) {
  22335. return this._delayInfo.indexOf(kind) !== -1;
  22336. }
  22337. return false;
  22338. }
  22339. return this._vertexBuffers[kind] !== undefined;
  22340. };
  22341. Geometry.prototype.getVerticesDataKinds = function () {
  22342. var result = [];
  22343. if (!this._vertexBuffers && this._delayInfo) {
  22344. for (var kind in this._delayInfo) {
  22345. result.push(kind);
  22346. }
  22347. } else {
  22348. for (kind in this._vertexBuffers) {
  22349. result.push(kind);
  22350. }
  22351. }
  22352. return result;
  22353. };
  22354. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22355. if (this._indexBuffer) {
  22356. this._engine._releaseBuffer(this._indexBuffer);
  22357. }
  22358. this._indices = indices;
  22359. if (this._meshes.length !== 0 && this._indices) {
  22360. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22361. }
  22362. if (totalVertices !== undefined) {
  22363. this._totalVertices = totalVertices;
  22364. }
  22365. var meshes = this._meshes;
  22366. var numOfMeshes = meshes.length;
  22367. for (var index = 0; index < numOfMeshes; index++) {
  22368. meshes[index]._createGlobalSubMesh();
  22369. }
  22370. };
  22371. Geometry.prototype.getTotalIndices = function () {
  22372. if (!this.isReady()) {
  22373. return 0;
  22374. }
  22375. return this._indices.length;
  22376. };
  22377. Geometry.prototype.getIndices = function () {
  22378. if (!this.isReady()) {
  22379. return null;
  22380. }
  22381. return this._indices;
  22382. };
  22383. Geometry.prototype.getIndexBuffer = function () {
  22384. if (!this.isReady()) {
  22385. return null;
  22386. }
  22387. return this._indexBuffer;
  22388. };
  22389. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22390. var meshes = this._meshes;
  22391. var index = meshes.indexOf(mesh);
  22392. if (index === -1) {
  22393. return;
  22394. }
  22395. for (var kind in this._vertexBuffers) {
  22396. this._vertexBuffers[kind].dispose();
  22397. }
  22398. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22399. this._indexBuffer = null;
  22400. }
  22401. meshes.splice(index, 1);
  22402. mesh._geometry = null;
  22403. if (meshes.length == 0 && shouldDispose) {
  22404. this.dispose();
  22405. }
  22406. };
  22407. Geometry.prototype.applyToMesh = function (mesh) {
  22408. if (mesh._geometry === this) {
  22409. return;
  22410. }
  22411. var previousGeometry = mesh._geometry;
  22412. if (previousGeometry) {
  22413. previousGeometry.releaseForMesh(mesh);
  22414. }
  22415. var meshes = this._meshes;
  22416. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22417. mesh._geometry = this;
  22418. this._scene.pushGeometry(this);
  22419. meshes.push(mesh);
  22420. if (this.isReady()) {
  22421. this._applyToMesh(mesh);
  22422. } else {
  22423. mesh._boundingInfo = this._boundingInfo;
  22424. }
  22425. };
  22426. Geometry.prototype._applyToMesh = function (mesh) {
  22427. var numOfMeshes = this._meshes.length;
  22428. for (var kind in this._vertexBuffers) {
  22429. if (numOfMeshes === 1) {
  22430. this._vertexBuffers[kind].create();
  22431. }
  22432. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22434. mesh._resetPointsArrayCache();
  22435. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22436. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22437. mesh._createGlobalSubMesh();
  22438. }
  22439. }
  22440. // indexBuffer
  22441. if (numOfMeshes === 1 && this._indices) {
  22442. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22443. }
  22444. if (this._indexBuffer) {
  22445. this._indexBuffer.references = numOfMeshes;
  22446. }
  22447. };
  22448. Geometry.prototype.load = function (scene, onLoaded) {
  22449. var _this = this;
  22450. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22451. return;
  22452. }
  22453. if (this.isReady()) {
  22454. if (onLoaded) {
  22455. onLoaded();
  22456. }
  22457. return;
  22458. }
  22459. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22460. scene._addPendingData(this);
  22461. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22462. _this._delayLoadingFunction(JSON.parse(data), _this);
  22463. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22464. _this._delayInfo = [];
  22465. scene._removePendingData(_this);
  22466. var meshes = _this._meshes;
  22467. var numOfMeshes = meshes.length;
  22468. for (var index = 0; index < numOfMeshes; index++) {
  22469. _this._applyToMesh(meshes[index]);
  22470. }
  22471. if (onLoaded) {
  22472. onLoaded();
  22473. }
  22474. }, function () {
  22475. }, scene.database);
  22476. };
  22477. Geometry.prototype.dispose = function () {
  22478. var meshes = this._meshes;
  22479. var numOfMeshes = meshes.length;
  22480. for (var index = 0; index < numOfMeshes; index++) {
  22481. this.releaseForMesh(meshes[index]);
  22482. }
  22483. this._meshes = [];
  22484. for (var kind in this._vertexBuffers) {
  22485. this._vertexBuffers[kind].dispose();
  22486. }
  22487. this._vertexBuffers = [];
  22488. this._totalVertices = 0;
  22489. if (this._indexBuffer) {
  22490. this._engine._releaseBuffer(this._indexBuffer);
  22491. }
  22492. this._indexBuffer = null;
  22493. this._indices = [];
  22494. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22495. this.delayLoadingFile = null;
  22496. this._delayLoadingFunction = null;
  22497. this._delayInfo = [];
  22498. this._boundingInfo = null; // todo: .dispose()
  22499. var geometries = this._scene.getGeometries();
  22500. index = geometries.indexOf(this);
  22501. if (index > -1) {
  22502. geometries.splice(index, 1);
  22503. }
  22504. };
  22505. Geometry.prototype.copy = function (id) {
  22506. var vertexData = new BABYLON.VertexData();
  22507. vertexData.indices = [];
  22508. var indices = this.getIndices();
  22509. for (var index = 0; index < indices.length; index++) {
  22510. vertexData.indices.push(indices[index]);
  22511. }
  22512. var updatable = false;
  22513. var stopChecking = false;
  22514. for (var kind in this._vertexBuffers) {
  22515. vertexData.set(this.getVerticesData(kind), kind);
  22516. if (!stopChecking) {
  22517. updatable = this.getVertexBuffer(kind).isUpdatable();
  22518. stopChecking = !updatable;
  22519. }
  22520. }
  22521. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  22522. geometry.delayLoadState = this.delayLoadState;
  22523. geometry.delayLoadingFile = this.delayLoadingFile;
  22524. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22525. for (kind in this._delayInfo) {
  22526. geometry._delayInfo = geometry._delayInfo || [];
  22527. geometry._delayInfo.push(kind);
  22528. }
  22529. // Bounding info
  22530. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22531. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22532. return geometry;
  22533. };
  22534. // Statics
  22535. Geometry.ExtractFromMesh = function (mesh, id) {
  22536. var geometry = mesh._geometry;
  22537. if (!geometry) {
  22538. return null;
  22539. }
  22540. return geometry.copy(id);
  22541. };
  22542. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22543. // be aware Math.random() could cause collisions
  22544. Geometry.RandomId = function () {
  22545. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22546. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  22547. return v.toString(16);
  22548. });
  22549. };
  22550. return Geometry;
  22551. })();
  22552. BABYLON.Geometry = Geometry;
  22553. (function (Geometry) {
  22554. /////// Primitives //////////////////////////////////////////////
  22555. (function (Primitives) {
  22556. /// Abstract class
  22557. var _Primitive = (function (_super) {
  22558. __extends(_Primitive, _super);
  22559. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22560. this._beingRegenerated = true;
  22561. this._canBeRegenerated = canBeRegenerated;
  22562. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22563. this._beingRegenerated = false;
  22564. }
  22565. _Primitive.prototype.canBeRegenerated = function () {
  22566. return this._canBeRegenerated;
  22567. };
  22568. _Primitive.prototype.regenerate = function () {
  22569. if (!this._canBeRegenerated) {
  22570. return;
  22571. }
  22572. this._beingRegenerated = true;
  22573. this.setAllVerticesData(this._regenerateVertexData(), false);
  22574. this._beingRegenerated = false;
  22575. };
  22576. _Primitive.prototype.asNewGeometry = function (id) {
  22577. return _super.prototype.copy.call(this, id);
  22578. };
  22579. // overrides
  22580. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22581. if (!this._beingRegenerated) {
  22582. return;
  22583. }
  22584. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22585. };
  22586. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22587. if (!this._beingRegenerated) {
  22588. return;
  22589. }
  22590. _super.prototype.setVerticesData.call(this, kind, data, false);
  22591. };
  22592. // to override
  22593. // protected
  22594. _Primitive.prototype._regenerateVertexData = function () {
  22595. throw new Error("Abstract method");
  22596. };
  22597. _Primitive.prototype.copy = function (id) {
  22598. throw new Error("Must be overriden in sub-classes.");
  22599. };
  22600. return _Primitive;
  22601. })(Geometry);
  22602. Primitives._Primitive = _Primitive;
  22603. var Box = (function (_super) {
  22604. __extends(Box, _super);
  22605. function Box(id, scene, size, canBeRegenerated, mesh) {
  22606. this.size = size;
  22607. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22608. }
  22609. Box.prototype._regenerateVertexData = function () {
  22610. return BABYLON.VertexData.CreateBox(this.size);
  22611. };
  22612. Box.prototype.copy = function (id) {
  22613. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22614. };
  22615. return Box;
  22616. })(_Primitive);
  22617. Primitives.Box = Box;
  22618. var Sphere = (function (_super) {
  22619. __extends(Sphere, _super);
  22620. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22621. this.segments = segments;
  22622. this.diameter = diameter;
  22623. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22624. }
  22625. Sphere.prototype._regenerateVertexData = function () {
  22626. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22627. };
  22628. Sphere.prototype.copy = function (id) {
  22629. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22630. };
  22631. return Sphere;
  22632. })(_Primitive);
  22633. Primitives.Sphere = Sphere;
  22634. var Cylinder = (function (_super) {
  22635. __extends(Cylinder, _super);
  22636. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22637. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22638. this.height = height;
  22639. this.diameterTop = diameterTop;
  22640. this.diameterBottom = diameterBottom;
  22641. this.tessellation = tessellation;
  22642. this.subdivisions = subdivisions;
  22643. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22644. }
  22645. Cylinder.prototype._regenerateVertexData = function () {
  22646. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22647. };
  22648. Cylinder.prototype.copy = function (id) {
  22649. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22650. };
  22651. return Cylinder;
  22652. })(_Primitive);
  22653. Primitives.Cylinder = Cylinder;
  22654. var Torus = (function (_super) {
  22655. __extends(Torus, _super);
  22656. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22657. this.diameter = diameter;
  22658. this.thickness = thickness;
  22659. this.tessellation = tessellation;
  22660. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22661. }
  22662. Torus.prototype._regenerateVertexData = function () {
  22663. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22664. };
  22665. Torus.prototype.copy = function (id) {
  22666. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22667. };
  22668. return Torus;
  22669. })(_Primitive);
  22670. Primitives.Torus = Torus;
  22671. var Ground = (function (_super) {
  22672. __extends(Ground, _super);
  22673. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22674. this.width = width;
  22675. this.height = height;
  22676. this.subdivisions = subdivisions;
  22677. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22678. }
  22679. Ground.prototype._regenerateVertexData = function () {
  22680. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22681. };
  22682. Ground.prototype.copy = function (id) {
  22683. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22684. };
  22685. return Ground;
  22686. })(_Primitive);
  22687. Primitives.Ground = Ground;
  22688. var TiledGround = (function (_super) {
  22689. __extends(TiledGround, _super);
  22690. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22691. this.xmin = xmin;
  22692. this.zmin = zmin;
  22693. this.xmax = xmax;
  22694. this.zmax = zmax;
  22695. this.subdivisions = subdivisions;
  22696. this.precision = precision;
  22697. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22698. }
  22699. TiledGround.prototype._regenerateVertexData = function () {
  22700. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22701. };
  22702. TiledGround.prototype.copy = function (id) {
  22703. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22704. };
  22705. return TiledGround;
  22706. })(_Primitive);
  22707. Primitives.TiledGround = TiledGround;
  22708. var Plane = (function (_super) {
  22709. __extends(Plane, _super);
  22710. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22711. this.size = size;
  22712. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22713. }
  22714. Plane.prototype._regenerateVertexData = function () {
  22715. return BABYLON.VertexData.CreatePlane(this.size);
  22716. };
  22717. Plane.prototype.copy = function (id) {
  22718. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22719. };
  22720. return Plane;
  22721. })(_Primitive);
  22722. Primitives.Plane = Plane;
  22723. var TorusKnot = (function (_super) {
  22724. __extends(TorusKnot, _super);
  22725. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22726. this.radius = radius;
  22727. this.tube = tube;
  22728. this.radialSegments = radialSegments;
  22729. this.tubularSegments = tubularSegments;
  22730. this.p = p;
  22731. this.q = q;
  22732. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22733. }
  22734. TorusKnot.prototype._regenerateVertexData = function () {
  22735. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22736. };
  22737. TorusKnot.prototype.copy = function (id) {
  22738. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22739. };
  22740. return TorusKnot;
  22741. })(_Primitive);
  22742. Primitives.TorusKnot = TorusKnot;
  22743. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22744. var Primitives = Geometry.Primitives;
  22745. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22746. var Geometry = BABYLON.Geometry;
  22747. })(BABYLON || (BABYLON = {}));
  22748. //# sourceMappingURL=babylon.geometry.js.map
  22749. var BABYLON;
  22750. (function (BABYLON) {
  22751. var Gamepads = (function () {
  22752. function Gamepads(ongamedpadconnected) {
  22753. var _this = this;
  22754. this.babylonGamepads = [];
  22755. this.oneGamepadConnected = false;
  22756. this.isMonitoring = false;
  22757. this.gamepadEventSupported = 'GamepadEvent' in window;
  22758. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22759. 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=";
  22760. this._callbackGamepadConnected = ongamedpadconnected;
  22761. if (this.gamepadSupportAvailable) {
  22762. // Checking if the gamepad connected event is supported (like in Firefox)
  22763. if (this.gamepadEventSupported) {
  22764. window.addEventListener('gamepadconnected', function (evt) {
  22765. _this._onGamepadConnected(evt);
  22766. }, false);
  22767. window.addEventListener('gamepaddisconnected', function (evt) {
  22768. _this._onGamepadDisconnected(evt);
  22769. }, false);
  22770. } else {
  22771. this._startMonitoringGamepads();
  22772. }
  22773. if (!this.oneGamepadConnected) {
  22774. this._insertGamepadDOMInstructions();
  22775. }
  22776. } else {
  22777. this._insertGamepadDOMNotSupported();
  22778. }
  22779. }
  22780. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22781. Gamepads.gamepadDOMInfo = document.createElement("div");
  22782. var buttonAImage = document.createElement("img");
  22783. buttonAImage.src = this.buttonADataURL;
  22784. var spanMessage = document.createElement("span");
  22785. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22786. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22787. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22788. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22789. Gamepads.gamepadDOMInfo.style.width = "100%";
  22790. Gamepads.gamepadDOMInfo.style.height = "48px";
  22791. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22792. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22793. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22794. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22795. buttonAImage.style.position = "relative";
  22796. buttonAImage.style.bottom = "8px";
  22797. spanMessage.style.position = "relative";
  22798. spanMessage.style.fontSize = "32px";
  22799. spanMessage.style.bottom = "32px";
  22800. spanMessage.style.color = "green";
  22801. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22802. };
  22803. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22804. Gamepads.gamepadDOMInfo = document.createElement("div");
  22805. var spanMessage = document.createElement("span");
  22806. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22807. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22808. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22809. Gamepads.gamepadDOMInfo.style.width = "100%";
  22810. Gamepads.gamepadDOMInfo.style.height = "40px";
  22811. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22812. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22813. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22814. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22815. spanMessage.style.position = "relative";
  22816. spanMessage.style.fontSize = "32px";
  22817. spanMessage.style.color = "red";
  22818. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22819. };
  22820. Gamepads.prototype.dispose = function () {
  22821. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22822. };
  22823. Gamepads.prototype._onGamepadConnected = function (evt) {
  22824. var newGamepad = this._addNewGamepad(evt.gamepad);
  22825. if (this._callbackGamepadConnected)
  22826. this._callbackGamepadConnected(newGamepad);
  22827. this._startMonitoringGamepads();
  22828. };
  22829. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22830. if (!this.oneGamepadConnected) {
  22831. this.oneGamepadConnected = true;
  22832. if (Gamepads.gamepadDOMInfo) {
  22833. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22834. Gamepads.gamepadDOMInfo = null;
  22835. }
  22836. }
  22837. var newGamepad;
  22838. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22839. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22840. } else {
  22841. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22842. }
  22843. this.babylonGamepads.push(newGamepad);
  22844. return newGamepad;
  22845. };
  22846. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22847. for (var i in this.babylonGamepads) {
  22848. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22849. this.babylonGamepads.splice(i, 1);
  22850. break;
  22851. }
  22852. }
  22853. // If no gamepads are left, stop the polling loop.
  22854. if (this.babylonGamepads.length == 0) {
  22855. this._stopMonitoringGamepads();
  22856. }
  22857. };
  22858. Gamepads.prototype._startMonitoringGamepads = function () {
  22859. if (!this.isMonitoring) {
  22860. this.isMonitoring = true;
  22861. this._checkGamepadsStatus();
  22862. }
  22863. };
  22864. Gamepads.prototype._stopMonitoringGamepads = function () {
  22865. this.isMonitoring = false;
  22866. };
  22867. Gamepads.prototype._checkGamepadsStatus = function () {
  22868. var _this = this;
  22869. // updating gamepad objects
  22870. this._updateGamepadObjects();
  22871. for (var i in this.babylonGamepads) {
  22872. this.babylonGamepads[i].update();
  22873. }
  22874. if (this.isMonitoring) {
  22875. if (window.requestAnimationFrame) {
  22876. window.requestAnimationFrame(function () {
  22877. _this._checkGamepadsStatus();
  22878. });
  22879. } else if (window.mozRequestAnimationFrame) {
  22880. window.mozRequestAnimationFrame(function () {
  22881. _this._checkGamepadsStatus();
  22882. });
  22883. } else if (window.webkitRequestAnimationFrame) {
  22884. window.webkitRequestAnimationFrame(function () {
  22885. _this._checkGamepadsStatus();
  22886. });
  22887. }
  22888. }
  22889. };
  22890. // This function is called only on Chrome, which does not yet support
  22891. // connection/disconnection events, but requires you to monitor
  22892. // an array for changes.
  22893. Gamepads.prototype._updateGamepadObjects = function () {
  22894. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22895. for (var i = 0; i < gamepads.length; i++) {
  22896. if (gamepads[i]) {
  22897. if (!(gamepads[i].index in this.babylonGamepads)) {
  22898. var newGamepad = this._addNewGamepad(gamepads[i]);
  22899. if (this._callbackGamepadConnected) {
  22900. this._callbackGamepadConnected(newGamepad);
  22901. }
  22902. } else {
  22903. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22904. }
  22905. }
  22906. }
  22907. };
  22908. return Gamepads;
  22909. })();
  22910. BABYLON.Gamepads = Gamepads;
  22911. var StickValues = (function () {
  22912. function StickValues(x, y) {
  22913. this.x = x;
  22914. this.y = y;
  22915. }
  22916. return StickValues;
  22917. })();
  22918. BABYLON.StickValues = StickValues;
  22919. var Gamepad = (function () {
  22920. function Gamepad(id, index, browserGamepad) {
  22921. this.id = id;
  22922. this.index = index;
  22923. this.browserGamepad = browserGamepad;
  22924. if (this.browserGamepad.axes.length >= 2) {
  22925. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22926. }
  22927. if (this.browserGamepad.axes.length >= 4) {
  22928. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22929. }
  22930. }
  22931. Gamepad.prototype.onleftstickchanged = function (callback) {
  22932. this._onleftstickchanged = callback;
  22933. };
  22934. Gamepad.prototype.onrightstickchanged = function (callback) {
  22935. this._onrightstickchanged = callback;
  22936. };
  22937. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22938. get: function () {
  22939. return this._leftStick;
  22940. },
  22941. set: function (newValues) {
  22942. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22943. this._onleftstickchanged(newValues);
  22944. }
  22945. this._leftStick = newValues;
  22946. },
  22947. enumerable: true,
  22948. configurable: true
  22949. });
  22950. Object.defineProperty(Gamepad.prototype, "rightStick", {
  22951. get: function () {
  22952. return this._rightStick;
  22953. },
  22954. set: function (newValues) {
  22955. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  22956. this._onrightstickchanged(newValues);
  22957. }
  22958. this._rightStick = newValues;
  22959. },
  22960. enumerable: true,
  22961. configurable: true
  22962. });
  22963. Gamepad.prototype.update = function () {
  22964. if (this._leftStick) {
  22965. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22966. }
  22967. if (this._rightStick) {
  22968. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22969. }
  22970. };
  22971. return Gamepad;
  22972. })();
  22973. BABYLON.Gamepad = Gamepad;
  22974. var GenericPad = (function (_super) {
  22975. __extends(GenericPad, _super);
  22976. function GenericPad(id, index, gamepad) {
  22977. _super.call(this, id, index, gamepad);
  22978. this.id = id;
  22979. this.index = index;
  22980. this.gamepad = gamepad;
  22981. this._buttons = new Array(gamepad.buttons.length);
  22982. }
  22983. GenericPad.prototype.onbuttondown = function (callback) {
  22984. this._onbuttondown = callback;
  22985. };
  22986. GenericPad.prototype.onbuttonup = function (callback) {
  22987. this._onbuttonup = callback;
  22988. };
  22989. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  22990. if (newValue !== currentValue) {
  22991. if (this._onbuttondown && newValue === 1) {
  22992. this._onbuttondown(buttonIndex);
  22993. }
  22994. if (this._onbuttonup && newValue === 0) {
  22995. this._onbuttonup(buttonIndex);
  22996. }
  22997. }
  22998. return newValue;
  22999. };
  23000. GenericPad.prototype.update = function () {
  23001. _super.prototype.update.call(this);
  23002. for (var index = 0; index < this._buttons.length; index++) {
  23003. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23004. }
  23005. };
  23006. return GenericPad;
  23007. })(Gamepad);
  23008. BABYLON.GenericPad = GenericPad;
  23009. (function (Xbox360Button) {
  23010. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23011. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23012. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23013. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23014. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23015. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23016. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23017. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23018. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23019. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23020. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23021. var Xbox360Button = BABYLON.Xbox360Button;
  23022. (function (Xbox360Dpad) {
  23023. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23024. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23025. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23026. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23027. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23028. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23029. var Xbox360Pad = (function (_super) {
  23030. __extends(Xbox360Pad, _super);
  23031. function Xbox360Pad() {
  23032. _super.apply(this, arguments);
  23033. this._leftTrigger = 0;
  23034. this._rightTrigger = 0;
  23035. this._buttonA = 0;
  23036. this._buttonB = 0;
  23037. this._buttonX = 0;
  23038. this._buttonY = 0;
  23039. this._buttonBack = 0;
  23040. this._buttonStart = 0;
  23041. this._buttonLB = 0;
  23042. this._buttonRB = 0;
  23043. this._buttonLeftStick = 0;
  23044. this._buttonRightStick = 0;
  23045. this._dPadUp = 0;
  23046. this._dPadDown = 0;
  23047. this._dPadLeft = 0;
  23048. this._dPadRight = 0;
  23049. }
  23050. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23051. this._onlefttriggerchanged = callback;
  23052. };
  23053. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23054. this._onrighttriggerchanged = callback;
  23055. };
  23056. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23057. get: function () {
  23058. return this._leftTrigger;
  23059. },
  23060. set: function (newValue) {
  23061. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23062. this._onlefttriggerchanged(newValue);
  23063. }
  23064. this._leftTrigger = newValue;
  23065. },
  23066. enumerable: true,
  23067. configurable: true
  23068. });
  23069. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23070. get: function () {
  23071. return this._rightTrigger;
  23072. },
  23073. set: function (newValue) {
  23074. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23075. this._onrighttriggerchanged(newValue);
  23076. }
  23077. this._rightTrigger = newValue;
  23078. },
  23079. enumerable: true,
  23080. configurable: true
  23081. });
  23082. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23083. this._onbuttondown = callback;
  23084. };
  23085. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23086. this._onbuttonup = callback;
  23087. };
  23088. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23089. this._ondpaddown = callback;
  23090. };
  23091. Xbox360Pad.prototype.ondpadup = function (callback) {
  23092. this._ondpadup = callback;
  23093. };
  23094. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23095. if (newValue !== currentValue) {
  23096. if (this._onbuttondown && newValue === 1) {
  23097. this._onbuttondown(buttonType);
  23098. }
  23099. if (this._onbuttonup && newValue === 0) {
  23100. this._onbuttonup(buttonType);
  23101. }
  23102. }
  23103. return newValue;
  23104. };
  23105. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23106. if (newValue !== currentValue) {
  23107. if (this._ondpaddown && newValue === 1) {
  23108. this._ondpaddown(buttonType);
  23109. }
  23110. if (this._ondpadup && newValue === 0) {
  23111. this._ondpadup(buttonType);
  23112. }
  23113. }
  23114. return newValue;
  23115. };
  23116. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23117. get: function () {
  23118. return this._buttonA;
  23119. },
  23120. set: function (value) {
  23121. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23122. },
  23123. enumerable: true,
  23124. configurable: true
  23125. });
  23126. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23127. get: function () {
  23128. return this._buttonB;
  23129. },
  23130. set: function (value) {
  23131. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23132. },
  23133. enumerable: true,
  23134. configurable: true
  23135. });
  23136. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23137. get: function () {
  23138. return this._buttonX;
  23139. },
  23140. set: function (value) {
  23141. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23142. },
  23143. enumerable: true,
  23144. configurable: true
  23145. });
  23146. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23147. get: function () {
  23148. return this._buttonY;
  23149. },
  23150. set: function (value) {
  23151. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23152. },
  23153. enumerable: true,
  23154. configurable: true
  23155. });
  23156. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23157. get: function () {
  23158. return this._buttonStart;
  23159. },
  23160. set: function (value) {
  23161. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23162. },
  23163. enumerable: true,
  23164. configurable: true
  23165. });
  23166. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23167. get: function () {
  23168. return this._buttonBack;
  23169. },
  23170. set: function (value) {
  23171. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23172. },
  23173. enumerable: true,
  23174. configurable: true
  23175. });
  23176. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23177. get: function () {
  23178. return this._buttonLB;
  23179. },
  23180. set: function (value) {
  23181. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23182. },
  23183. enumerable: true,
  23184. configurable: true
  23185. });
  23186. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23187. get: function () {
  23188. return this._buttonRB;
  23189. },
  23190. set: function (value) {
  23191. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23192. },
  23193. enumerable: true,
  23194. configurable: true
  23195. });
  23196. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23197. get: function () {
  23198. return this._buttonLeftStick;
  23199. },
  23200. set: function (value) {
  23201. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23202. },
  23203. enumerable: true,
  23204. configurable: true
  23205. });
  23206. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23207. get: function () {
  23208. return this._buttonRightStick;
  23209. },
  23210. set: function (value) {
  23211. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23212. },
  23213. enumerable: true,
  23214. configurable: true
  23215. });
  23216. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23217. get: function () {
  23218. return this._dPadUp;
  23219. },
  23220. set: function (value) {
  23221. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23222. },
  23223. enumerable: true,
  23224. configurable: true
  23225. });
  23226. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23227. get: function () {
  23228. return this._dPadDown;
  23229. },
  23230. set: function (value) {
  23231. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23232. },
  23233. enumerable: true,
  23234. configurable: true
  23235. });
  23236. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23237. get: function () {
  23238. return this._dPadLeft;
  23239. },
  23240. set: function (value) {
  23241. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23242. },
  23243. enumerable: true,
  23244. configurable: true
  23245. });
  23246. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23247. get: function () {
  23248. return this._dPadRight;
  23249. },
  23250. set: function (value) {
  23251. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23252. },
  23253. enumerable: true,
  23254. configurable: true
  23255. });
  23256. Xbox360Pad.prototype.update = function () {
  23257. _super.prototype.update.call(this);
  23258. this.buttonA = this.browserGamepad.buttons[0].value;
  23259. this.buttonB = this.browserGamepad.buttons[1].value;
  23260. this.buttonX = this.browserGamepad.buttons[2].value;
  23261. this.buttonY = this.browserGamepad.buttons[3].value;
  23262. this.buttonLB = this.browserGamepad.buttons[4].value;
  23263. this.buttonRB = this.browserGamepad.buttons[5].value;
  23264. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23265. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23266. this.buttonBack = this.browserGamepad.buttons[8].value;
  23267. this.buttonStart = this.browserGamepad.buttons[9].value;
  23268. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23269. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23270. this.dPadUp = this.browserGamepad.buttons[12].value;
  23271. this.dPadDown = this.browserGamepad.buttons[13].value;
  23272. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23273. this.dPadRight = this.browserGamepad.buttons[15].value;
  23274. };
  23275. return Xbox360Pad;
  23276. })(Gamepad);
  23277. BABYLON.Xbox360Pad = Xbox360Pad;
  23278. })(BABYLON || (BABYLON = {}));
  23279. //# sourceMappingURL=babylon.gamepads.js.map
  23280. var BABYLON;
  23281. (function (BABYLON) {
  23282. // We're mainly based on the logic defined into the FreeCamera code
  23283. var GamepadCamera = (function (_super) {
  23284. __extends(GamepadCamera, _super);
  23285. function GamepadCamera(name, position, scene) {
  23286. var _this = this;
  23287. _super.call(this, name, position, scene);
  23288. this.angularSensibility = 200;
  23289. this.moveSensibility = 75;
  23290. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23291. _this._onNewGameConnected(gamepad);
  23292. });
  23293. }
  23294. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23295. // Only the first gamepad can control the camera
  23296. if (gamepad.index === 0) {
  23297. this._gamepad = gamepad;
  23298. }
  23299. };
  23300. GamepadCamera.prototype._checkInputs = function () {
  23301. if (!this._gamepad) {
  23302. return;
  23303. }
  23304. var LSValues = this._gamepad.leftStick;
  23305. var normalizedLX = LSValues.x / this.moveSensibility;
  23306. var normalizedLY = LSValues.y / this.moveSensibility;
  23307. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23308. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23309. var RSValues = this._gamepad.rightStick;
  23310. var normalizedRX = RSValues.x / this.angularSensibility;
  23311. var normalizedRY = RSValues.y / this.angularSensibility;
  23312. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23313. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23314. ;
  23315. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23316. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23317. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23318. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23319. };
  23320. GamepadCamera.prototype.dispose = function () {
  23321. this._gamepads.dispose();
  23322. _super.prototype.dispose.call(this);
  23323. };
  23324. return GamepadCamera;
  23325. })(BABYLON.FreeCamera);
  23326. BABYLON.GamepadCamera = GamepadCamera;
  23327. })(BABYLON || (BABYLON = {}));
  23328. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23329. var BABYLON;
  23330. (function (BABYLON) {
  23331. var LinesMesh = (function (_super) {
  23332. __extends(LinesMesh, _super);
  23333. function LinesMesh(name, scene, updatable) {
  23334. if (typeof updatable === "undefined") { updatable = false; }
  23335. _super.call(this, name, scene);
  23336. this.color = new BABYLON.Color3(1, 1, 1);
  23337. this.alpha = 1;
  23338. this._indices = new Array();
  23339. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23340. attributes: ["position"],
  23341. uniforms: ["worldViewProjection", "color"],
  23342. needAlphaBlending: true
  23343. });
  23344. }
  23345. Object.defineProperty(LinesMesh.prototype, "material", {
  23346. get: function () {
  23347. return this._colorShader;
  23348. },
  23349. enumerable: true,
  23350. configurable: true
  23351. });
  23352. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23353. get: function () {
  23354. return false;
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23360. get: function () {
  23361. return false;
  23362. },
  23363. enumerable: true,
  23364. configurable: true
  23365. });
  23366. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23367. var engine = this.getScene().getEngine();
  23368. var indexToBind = this._geometry.getIndexBuffer();
  23369. // VBOs
  23370. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23371. // Color
  23372. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23373. };
  23374. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23375. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23376. return;
  23377. }
  23378. var engine = this.getScene().getEngine();
  23379. // Draw order
  23380. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23381. };
  23382. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23383. return null;
  23384. };
  23385. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23386. this._colorShader.dispose();
  23387. _super.prototype.dispose.call(this, doNotRecurse);
  23388. };
  23389. return LinesMesh;
  23390. })(BABYLON.Mesh);
  23391. BABYLON.LinesMesh = LinesMesh;
  23392. })(BABYLON || (BABYLON = {}));
  23393. //# sourceMappingURL=babylon.linesMesh.js.map
  23394. var BABYLON;
  23395. (function (BABYLON) {
  23396. var OutlineRenderer = (function () {
  23397. function OutlineRenderer(scene) {
  23398. this._scene = scene;
  23399. }
  23400. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23401. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23402. var scene = this._scene;
  23403. var engine = this._scene.getEngine();
  23404. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23405. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23406. return;
  23407. }
  23408. var mesh = subMesh.getRenderingMesh();
  23409. var material = subMesh.getMaterial();
  23410. engine.enableEffect(this._effect);
  23411. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23412. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23413. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23414. // Bones
  23415. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23416. if (useBones) {
  23417. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23418. }
  23419. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23420. // Alpha test
  23421. if (material && material.needAlphaTesting()) {
  23422. var alphaTexture = material.getAlphaTestTexture();
  23423. this._effect.setTexture("diffuseSampler", alphaTexture);
  23424. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23425. }
  23426. if (hardwareInstancedRendering) {
  23427. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23428. } else {
  23429. if (batch.renderSelf[subMesh._id]) {
  23430. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23431. // Draw
  23432. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23433. }
  23434. if (batch.visibleInstances[subMesh._id]) {
  23435. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23436. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23437. this._effect.setMatrix("world", instance.getWorldMatrix());
  23438. // Draw
  23439. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23440. }
  23441. }
  23442. }
  23443. };
  23444. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23445. var defines = [];
  23446. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23447. var mesh = subMesh.getMesh();
  23448. var material = subMesh.getMaterial();
  23449. // Alpha test
  23450. if (material && material.needAlphaTesting()) {
  23451. defines.push("#define ALPHATEST");
  23452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23453. attribs.push(BABYLON.VertexBuffer.UVKind);
  23454. defines.push("#define UV1");
  23455. }
  23456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23457. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23458. defines.push("#define UV2");
  23459. }
  23460. }
  23461. // Bones
  23462. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23465. defines.push("#define BONES");
  23466. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23467. }
  23468. // Instances
  23469. if (useInstances) {
  23470. defines.push("#define INSTANCES");
  23471. attribs.push("world0");
  23472. attribs.push("world1");
  23473. attribs.push("world2");
  23474. attribs.push("world3");
  23475. }
  23476. // Get correct effect
  23477. var join = defines.join("\n");
  23478. if (this._cachedDefines != join) {
  23479. this._cachedDefines = join;
  23480. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23481. }
  23482. return this._effect.isReady();
  23483. };
  23484. return OutlineRenderer;
  23485. })();
  23486. BABYLON.OutlineRenderer = OutlineRenderer;
  23487. })(BABYLON || (BABYLON = {}));
  23488. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23489. var BABYLON;
  23490. (function (BABYLON) {
  23491. var MeshAssetTask = (function () {
  23492. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23493. this.name = name;
  23494. this.meshesNames = meshesNames;
  23495. this.rootUrl = rootUrl;
  23496. this.sceneFilename = sceneFilename;
  23497. this.isCompleted = false;
  23498. }
  23499. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23500. var _this = this;
  23501. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23502. _this.loadedMeshes = meshes;
  23503. _this.loadedParticleSystems = particleSystems;
  23504. _this.loadedSkeletons = skeletons;
  23505. _this.isCompleted = true;
  23506. if (_this.onSuccess) {
  23507. _this.onSuccess(_this);
  23508. }
  23509. onSuccess();
  23510. }, null, function () {
  23511. if (_this.onError) {
  23512. _this.onError(_this);
  23513. }
  23514. onError();
  23515. });
  23516. };
  23517. return MeshAssetTask;
  23518. })();
  23519. BABYLON.MeshAssetTask = MeshAssetTask;
  23520. var TextFileAssetTask = (function () {
  23521. function TextFileAssetTask(name, url) {
  23522. this.name = name;
  23523. this.url = url;
  23524. this.isCompleted = false;
  23525. }
  23526. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23527. var _this = this;
  23528. BABYLON.Tools.LoadFile(this.url, function (data) {
  23529. _this.text = data;
  23530. _this.isCompleted = true;
  23531. if (_this.onSuccess) {
  23532. _this.onSuccess(_this);
  23533. }
  23534. onSuccess();
  23535. }, null, scene.database, false, function () {
  23536. if (_this.onError) {
  23537. _this.onError(_this);
  23538. }
  23539. onError();
  23540. });
  23541. };
  23542. return TextFileAssetTask;
  23543. })();
  23544. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23545. var BinaryFileAssetTask = (function () {
  23546. function BinaryFileAssetTask(name, url) {
  23547. this.name = name;
  23548. this.url = url;
  23549. this.isCompleted = false;
  23550. }
  23551. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23552. var _this = this;
  23553. BABYLON.Tools.LoadFile(this.url, function (data) {
  23554. _this.data = data;
  23555. _this.isCompleted = true;
  23556. if (_this.onSuccess) {
  23557. _this.onSuccess(_this);
  23558. }
  23559. onSuccess();
  23560. }, null, scene.database, true, function () {
  23561. if (_this.onError) {
  23562. _this.onError(_this);
  23563. }
  23564. onError();
  23565. });
  23566. };
  23567. return BinaryFileAssetTask;
  23568. })();
  23569. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23570. var ImageAssetTask = (function () {
  23571. function ImageAssetTask(name, url) {
  23572. this.name = name;
  23573. this.url = url;
  23574. this.isCompleted = false;
  23575. }
  23576. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23577. var _this = this;
  23578. var img = new Image();
  23579. img.onload = function () {
  23580. _this.image = img;
  23581. _this.isCompleted = true;
  23582. if (_this.onSuccess) {
  23583. _this.onSuccess(_this);
  23584. }
  23585. onSuccess();
  23586. };
  23587. img.onerror = function () {
  23588. if (_this.onError) {
  23589. _this.onError(_this);
  23590. }
  23591. onError();
  23592. };
  23593. img.src = this.url;
  23594. };
  23595. return ImageAssetTask;
  23596. })();
  23597. BABYLON.ImageAssetTask = ImageAssetTask;
  23598. var TextureAssetTask = (function () {
  23599. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23600. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23601. this.name = name;
  23602. this.url = url;
  23603. this.noMipmap = noMipmap;
  23604. this.invertY = invertY;
  23605. this.samplingMode = samplingMode;
  23606. this.isCompleted = false;
  23607. }
  23608. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23609. var _this = this;
  23610. var onload = function () {
  23611. _this.isCompleted = true;
  23612. if (_this.onSuccess) {
  23613. _this.onSuccess(_this);
  23614. }
  23615. onSuccess();
  23616. };
  23617. var onerror = function () {
  23618. if (_this.onError) {
  23619. _this.onError(_this);
  23620. }
  23621. onError();
  23622. };
  23623. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23624. };
  23625. return TextureAssetTask;
  23626. })();
  23627. BABYLON.TextureAssetTask = TextureAssetTask;
  23628. var AssetsManager = (function () {
  23629. function AssetsManager(scene) {
  23630. this._tasks = new Array();
  23631. this._waitingTasksCount = 0;
  23632. this.useDefaultLoadingScreen = true;
  23633. this._scene = scene;
  23634. }
  23635. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23636. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23637. this._tasks.push(task);
  23638. return task;
  23639. };
  23640. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23641. var task = new TextFileAssetTask(taskName, url);
  23642. this._tasks.push(task);
  23643. return task;
  23644. };
  23645. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23646. var task = new BinaryFileAssetTask(taskName, url);
  23647. this._tasks.push(task);
  23648. return task;
  23649. };
  23650. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23651. var task = new ImageAssetTask(taskName, url);
  23652. this._tasks.push(task);
  23653. return task;
  23654. };
  23655. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23656. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23657. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23658. this._tasks.push(task);
  23659. return task;
  23660. };
  23661. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23662. this._waitingTasksCount--;
  23663. if (this._waitingTasksCount === 0) {
  23664. if (this.onFinish) {
  23665. this.onFinish(this._tasks);
  23666. }
  23667. this._scene.getEngine().hideLoadingUI();
  23668. }
  23669. };
  23670. AssetsManager.prototype._runTask = function (task) {
  23671. var _this = this;
  23672. task.run(this._scene, function () {
  23673. if (_this.onTaskSuccess) {
  23674. _this.onTaskSuccess(task);
  23675. }
  23676. _this._decreaseWaitingTasksCount();
  23677. }, function () {
  23678. if (_this.onTaskError) {
  23679. _this.onTaskError(task);
  23680. }
  23681. _this._decreaseWaitingTasksCount();
  23682. });
  23683. };
  23684. AssetsManager.prototype.reset = function () {
  23685. this._tasks = new Array();
  23686. return this;
  23687. };
  23688. AssetsManager.prototype.load = function () {
  23689. this._waitingTasksCount = this._tasks.length;
  23690. if (this._waitingTasksCount === 0) {
  23691. if (this.onFinish) {
  23692. this.onFinish(this._tasks);
  23693. }
  23694. return this;
  23695. }
  23696. if (this.useDefaultLoadingScreen) {
  23697. this._scene.getEngine().displayLoadingUI();
  23698. }
  23699. for (var index = 0; index < this._tasks.length; index++) {
  23700. var task = this._tasks[index];
  23701. this._runTask(task);
  23702. }
  23703. return this;
  23704. };
  23705. return AssetsManager;
  23706. })();
  23707. BABYLON.AssetsManager = AssetsManager;
  23708. })(BABYLON || (BABYLON = {}));
  23709. //# sourceMappingURL=babylon.assetsManager.js.map
  23710. var BABYLON;
  23711. (function (BABYLON) {
  23712. var VRDeviceOrientationCamera = (function (_super) {
  23713. __extends(VRDeviceOrientationCamera, _super);
  23714. function VRDeviceOrientationCamera(name, position, scene) {
  23715. _super.call(this, name, position, scene);
  23716. this._alpha = 0;
  23717. this._beta = 0;
  23718. this._gamma = 0;
  23719. }
  23720. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23721. this._alpha = +evt.alpha | 0;
  23722. this._beta = +evt.beta | 0;
  23723. this._gamma = +evt.gamma | 0;
  23724. if (this._gamma < 0) {
  23725. this._gamma = 90 + this._gamma;
  23726. } else {
  23727. // Incline it in the correct angle.
  23728. this._gamma = 270 - this._gamma;
  23729. }
  23730. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23731. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23732. this.rotation.z = this._beta / 180.0 * Math.PI;
  23733. };
  23734. return VRDeviceOrientationCamera;
  23735. })(BABYLON.OculusCamera);
  23736. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23737. })(BABYLON || (BABYLON = {}));
  23738. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23739. var BABYLON;
  23740. (function (BABYLON) {
  23741. var WebVRCamera = (function (_super) {
  23742. __extends(WebVRCamera, _super);
  23743. function WebVRCamera(name, position, scene) {
  23744. _super.call(this, name, position, scene);
  23745. this._hmdDevice = null;
  23746. this._sensorDevice = null;
  23747. this._cacheState = null;
  23748. this._cacheQuaternion = new BABYLON.Quaternion();
  23749. this._cacheRotation = BABYLON.Vector3.Zero();
  23750. this._vrEnabled = false;
  23751. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23752. }
  23753. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23754. var size = devices.length;
  23755. var i = 0;
  23756. // Reset devices.
  23757. this._sensorDevice = null;
  23758. this._hmdDevice = null;
  23759. while (i < size && this._hmdDevice === null) {
  23760. if (devices[i] instanceof HMDVRDevice) {
  23761. this._hmdDevice = devices[i];
  23762. }
  23763. i++;
  23764. }
  23765. i = 0;
  23766. while (i < size && this._sensorDevice === null) {
  23767. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23768. this._sensorDevice = devices[i];
  23769. }
  23770. i++;
  23771. }
  23772. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23773. };
  23774. WebVRCamera.prototype._update = function () {
  23775. if (this._vrEnabled) {
  23776. this._cacheState = this._sensorDevice.getState();
  23777. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23778. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23779. this.rotation.x = -this._cacheRotation.z;
  23780. this.rotation.y = -this._cacheRotation.y;
  23781. this.rotation.z = this._cacheRotation.x;
  23782. }
  23783. _super.prototype._update.call(this);
  23784. };
  23785. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23786. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23787. if (navigator.getVRDevices) {
  23788. navigator.getVRDevices().then(this._getWebVRDevices);
  23789. } else if (navigator.mozGetVRDevices) {
  23790. navigator.mozGetVRDevices(this._getWebVRDevices);
  23791. }
  23792. };
  23793. WebVRCamera.prototype.detachControl = function (element) {
  23794. _super.prototype.detachControl.call(this, element);
  23795. this._vrEnabled = false;
  23796. };
  23797. return WebVRCamera;
  23798. })(BABYLON.OculusCamera);
  23799. BABYLON.WebVRCamera = WebVRCamera;
  23800. })(BABYLON || (BABYLON = {}));
  23801. //# sourceMappingURL=babylon.webVRCamera.js.map
  23802. var BABYLON;
  23803. (function (BABYLON) {
  23804. // Standard optimizations
  23805. var SceneOptimization = (function () {
  23806. function SceneOptimization(priority) {
  23807. if (typeof priority === "undefined") { priority = 0; }
  23808. this.priority = priority;
  23809. this.apply = function (scene) {
  23810. return true;
  23811. };
  23812. }
  23813. return SceneOptimization;
  23814. })();
  23815. BABYLON.SceneOptimization = SceneOptimization;
  23816. var TextureOptimization = (function (_super) {
  23817. __extends(TextureOptimization, _super);
  23818. function TextureOptimization(priority, maximumSize) {
  23819. if (typeof priority === "undefined") { priority = 0; }
  23820. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23821. var _this = this;
  23822. _super.call(this, priority);
  23823. this.priority = priority;
  23824. this.maximumSize = maximumSize;
  23825. this.apply = function (scene) {
  23826. var allDone = true;
  23827. for (var index = 0; index < scene.textures.length; index++) {
  23828. var texture = scene.textures[index];
  23829. if (!texture.canRescale) {
  23830. continue;
  23831. }
  23832. var currentSize = texture.getSize();
  23833. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23834. if (maxDimension > _this.maximumSize) {
  23835. texture.scale(0.5);
  23836. allDone = false;
  23837. }
  23838. }
  23839. return allDone;
  23840. };
  23841. }
  23842. return TextureOptimization;
  23843. })(SceneOptimization);
  23844. BABYLON.TextureOptimization = TextureOptimization;
  23845. var HardwareScalingOptimization = (function (_super) {
  23846. __extends(HardwareScalingOptimization, _super);
  23847. function HardwareScalingOptimization(priority, maximumScale) {
  23848. if (typeof priority === "undefined") { priority = 0; }
  23849. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23850. var _this = this;
  23851. _super.call(this, priority);
  23852. this.priority = priority;
  23853. this.maximumScale = maximumScale;
  23854. this._currentScale = 1;
  23855. this.apply = function (scene) {
  23856. _this._currentScale++;
  23857. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23858. return _this._currentScale >= _this.maximumScale;
  23859. };
  23860. }
  23861. return HardwareScalingOptimization;
  23862. })(SceneOptimization);
  23863. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23864. var ShadowsOptimization = (function (_super) {
  23865. __extends(ShadowsOptimization, _super);
  23866. function ShadowsOptimization() {
  23867. _super.apply(this, arguments);
  23868. this.apply = function (scene) {
  23869. scene.shadowsEnabled = false;
  23870. return true;
  23871. };
  23872. }
  23873. return ShadowsOptimization;
  23874. })(SceneOptimization);
  23875. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23876. var PostProcessesOptimization = (function (_super) {
  23877. __extends(PostProcessesOptimization, _super);
  23878. function PostProcessesOptimization() {
  23879. _super.apply(this, arguments);
  23880. this.apply = function (scene) {
  23881. scene.postProcessesEnabled = false;
  23882. return true;
  23883. };
  23884. }
  23885. return PostProcessesOptimization;
  23886. })(SceneOptimization);
  23887. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23888. var LensFlaresOptimization = (function (_super) {
  23889. __extends(LensFlaresOptimization, _super);
  23890. function LensFlaresOptimization() {
  23891. _super.apply(this, arguments);
  23892. this.apply = function (scene) {
  23893. scene.lensFlaresEnabled = false;
  23894. return true;
  23895. };
  23896. }
  23897. return LensFlaresOptimization;
  23898. })(SceneOptimization);
  23899. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23900. var ParticlesOptimization = (function (_super) {
  23901. __extends(ParticlesOptimization, _super);
  23902. function ParticlesOptimization() {
  23903. _super.apply(this, arguments);
  23904. this.apply = function (scene) {
  23905. scene.particlesEnabled = false;
  23906. return true;
  23907. };
  23908. }
  23909. return ParticlesOptimization;
  23910. })(SceneOptimization);
  23911. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23912. var RenderTargetsOptimization = (function (_super) {
  23913. __extends(RenderTargetsOptimization, _super);
  23914. function RenderTargetsOptimization() {
  23915. _super.apply(this, arguments);
  23916. this.apply = function (scene) {
  23917. scene.renderTargetsEnabled = false;
  23918. return true;
  23919. };
  23920. }
  23921. return RenderTargetsOptimization;
  23922. })(SceneOptimization);
  23923. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23924. var MergeMeshesOptimization = (function (_super) {
  23925. __extends(MergeMeshesOptimization, _super);
  23926. function MergeMeshesOptimization() {
  23927. _super.apply(this, arguments);
  23928. var _this = this;
  23929. this._canBeMerged = function (abstractMesh) {
  23930. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23931. return false;
  23932. }
  23933. var mesh = abstractMesh;
  23934. if (!mesh.isVisible || !mesh.isEnabled()) {
  23935. return false;
  23936. }
  23937. if (mesh.instances.length > 0) {
  23938. return false;
  23939. }
  23940. if (mesh.skeleton || mesh.hasLODLevels) {
  23941. return false;
  23942. }
  23943. return true;
  23944. };
  23945. this.apply = function (scene) {
  23946. var globalPool = scene.meshes.slice(0);
  23947. var globalLength = globalPool.length;
  23948. for (var index = 0; index < globalLength; index++) {
  23949. var currentPool = new Array();
  23950. var current = globalPool[index];
  23951. // Checks
  23952. if (!_this._canBeMerged(current)) {
  23953. continue;
  23954. }
  23955. currentPool.push(current);
  23956. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  23957. var otherMesh = globalPool[subIndex];
  23958. if (!_this._canBeMerged(otherMesh)) {
  23959. continue;
  23960. }
  23961. if (otherMesh.material !== current.material) {
  23962. continue;
  23963. }
  23964. if (otherMesh.checkCollisions !== current.checkCollisions) {
  23965. continue;
  23966. }
  23967. currentPool.push(otherMesh);
  23968. globalLength--;
  23969. globalPool.splice(subIndex, 1);
  23970. subIndex--;
  23971. }
  23972. if (currentPool.length < 2) {
  23973. continue;
  23974. }
  23975. // Merge meshes
  23976. BABYLON.Mesh.MergeMeshes(currentPool);
  23977. }
  23978. return true;
  23979. };
  23980. }
  23981. return MergeMeshesOptimization;
  23982. })(SceneOptimization);
  23983. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  23984. // Options
  23985. var SceneOptimizerOptions = (function () {
  23986. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  23987. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  23988. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  23989. this.targetFrameRate = targetFrameRate;
  23990. this.trackerDuration = trackerDuration;
  23991. this.optimizations = new Array();
  23992. }
  23993. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  23994. var result = new SceneOptimizerOptions(targetFrameRate);
  23995. var priority = 0;
  23996. result.optimizations.push(new MergeMeshesOptimization(priority));
  23997. result.optimizations.push(new ShadowsOptimization(priority));
  23998. result.optimizations.push(new LensFlaresOptimization(priority));
  23999. // Next priority
  24000. priority++;
  24001. result.optimizations.push(new PostProcessesOptimization(priority));
  24002. result.optimizations.push(new ParticlesOptimization(priority));
  24003. // Next priority
  24004. priority++;
  24005. result.optimizations.push(new TextureOptimization(priority, 1024));
  24006. return result;
  24007. };
  24008. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24009. var result = new SceneOptimizerOptions(targetFrameRate);
  24010. var priority = 0;
  24011. result.optimizations.push(new MergeMeshesOptimization(priority));
  24012. result.optimizations.push(new ShadowsOptimization(priority));
  24013. result.optimizations.push(new LensFlaresOptimization(priority));
  24014. // Next priority
  24015. priority++;
  24016. result.optimizations.push(new PostProcessesOptimization(priority));
  24017. result.optimizations.push(new ParticlesOptimization(priority));
  24018. // Next priority
  24019. priority++;
  24020. result.optimizations.push(new TextureOptimization(priority, 512));
  24021. // Next priority
  24022. priority++;
  24023. result.optimizations.push(new RenderTargetsOptimization(priority));
  24024. // Next priority
  24025. priority++;
  24026. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24027. return result;
  24028. };
  24029. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24030. var result = new SceneOptimizerOptions(targetFrameRate);
  24031. var priority = 0;
  24032. result.optimizations.push(new MergeMeshesOptimization(priority));
  24033. result.optimizations.push(new ShadowsOptimization(priority));
  24034. result.optimizations.push(new LensFlaresOptimization(priority));
  24035. // Next priority
  24036. priority++;
  24037. result.optimizations.push(new PostProcessesOptimization(priority));
  24038. result.optimizations.push(new ParticlesOptimization(priority));
  24039. // Next priority
  24040. priority++;
  24041. result.optimizations.push(new TextureOptimization(priority, 256));
  24042. // Next priority
  24043. priority++;
  24044. result.optimizations.push(new RenderTargetsOptimization(priority));
  24045. // Next priority
  24046. priority++;
  24047. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24048. return result;
  24049. };
  24050. return SceneOptimizerOptions;
  24051. })();
  24052. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24053. // Scene optimizer tool
  24054. var SceneOptimizer = (function () {
  24055. function SceneOptimizer() {
  24056. }
  24057. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24058. // TODO: add an epsilon
  24059. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24060. if (onSuccess) {
  24061. onSuccess();
  24062. }
  24063. return;
  24064. }
  24065. // Apply current level of optimizations
  24066. var allDone = true;
  24067. var noOptimizationApplied = true;
  24068. for (var index = 0; index < options.optimizations.length; index++) {
  24069. var optimization = options.optimizations[index];
  24070. if (optimization.priority === currentPriorityLevel) {
  24071. noOptimizationApplied = false;
  24072. allDone = allDone && optimization.apply(scene);
  24073. }
  24074. }
  24075. // If no optimization was applied, this is a failure :(
  24076. if (noOptimizationApplied) {
  24077. if (onFailure) {
  24078. onFailure();
  24079. }
  24080. return;
  24081. }
  24082. // If all optimizations were done, move to next level
  24083. if (allDone) {
  24084. currentPriorityLevel++;
  24085. }
  24086. // Let's the system running for a specific amount of time before checking FPS
  24087. scene.executeWhenReady(function () {
  24088. setTimeout(function () {
  24089. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24090. }, options.trackerDuration);
  24091. });
  24092. };
  24093. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24094. if (!options) {
  24095. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24096. }
  24097. // Let's the system running for a specific amount of time before checking FPS
  24098. scene.executeWhenReady(function () {
  24099. setTimeout(function () {
  24100. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24101. }, options.trackerDuration);
  24102. });
  24103. };
  24104. return SceneOptimizer;
  24105. })();
  24106. BABYLON.SceneOptimizer = SceneOptimizer;
  24107. })(BABYLON || (BABYLON = {}));
  24108. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24109. var BABYLON;
  24110. (function (BABYLON) {
  24111. (function (Internals) {
  24112. var MeshLODLevel = (function () {
  24113. function MeshLODLevel(distance, mesh) {
  24114. this.distance = distance;
  24115. this.mesh = mesh;
  24116. }
  24117. return MeshLODLevel;
  24118. })();
  24119. Internals.MeshLODLevel = MeshLODLevel;
  24120. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24121. var Internals = BABYLON.Internals;
  24122. })(BABYLON || (BABYLON = {}));
  24123. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24124. var BABYLON;
  24125. (function (BABYLON) {
  24126. var AudioEngine = (function () {
  24127. function AudioEngine() {
  24128. this.audioContext = null;
  24129. this.canUseWebAudio = false;
  24130. try {
  24131. if (typeof AudioContext !== 'undefined') {
  24132. this.audioContext = new AudioContext();
  24133. this.canUseWebAudio = true;
  24134. } else if (typeof webkitAudioContext !== 'undefined') {
  24135. this.audioContext = new webkitAudioContext();
  24136. this.canUseWebAudio = true;
  24137. }
  24138. } catch (e) {
  24139. this.canUseWebAudio = false;
  24140. }
  24141. // create a global volume gain node
  24142. if (this.canUseWebAudio) {
  24143. this.masterGain = this.audioContext.createGain();
  24144. this.masterGain.gain.value = 1;
  24145. this.masterGain.connect(this.audioContext.destination);
  24146. }
  24147. }
  24148. AudioEngine.prototype.getGlobalVolume = function () {
  24149. if (this.canUseWebAudio) {
  24150. return this.masterGain.gain.value;
  24151. } else {
  24152. return -1;
  24153. }
  24154. };
  24155. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24156. if (this.canUseWebAudio) {
  24157. this.masterGain.gain.value = newVolume;
  24158. }
  24159. };
  24160. return AudioEngine;
  24161. })();
  24162. BABYLON.AudioEngine = AudioEngine;
  24163. })(BABYLON || (BABYLON = {}));
  24164. //# sourceMappingURL=babylon.audioengine.js.map
  24165. var BABYLON;
  24166. (function (BABYLON) {
  24167. var Sound = (function () {
  24168. /**
  24169. * Create a sound and attach it to a scene
  24170. * @param name Name of your sound
  24171. * @param url Url to the sound to load async
  24172. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24173. * @param options Objects to provide with the current available options: autoplay, loop, distanceMax
  24174. */
  24175. function Sound(name, url, scene, readyToPlayCallback, options) {
  24176. var _this = this;
  24177. this.autoplay = false;
  24178. this.loop = false;
  24179. this.useCustomAttenuation = false;
  24180. this.spatialSound = false;
  24181. this.refDistance = 1;
  24182. this.rolloffFactor = 1;
  24183. this.maxDistance = 100;
  24184. this._position = BABYLON.Vector3.Zero();
  24185. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24186. this._volume = 1;
  24187. this._isLoaded = false;
  24188. this._isReadyToPlay = false;
  24189. this._isPlaying = false;
  24190. this._isDirectional = false;
  24191. // Used if you'd like to create a directional sound.
  24192. // If not set, the sound will be omnidirectional
  24193. this._coneInnerAngle = null;
  24194. this._coneOuterAngle = null;
  24195. this._coneOuterGain = null;
  24196. this._name = name;
  24197. this._scene = scene;
  24198. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24199. this._readyToPlayCallback = readyToPlayCallback;
  24200. // Default custom attenuation function is a linear attenuation
  24201. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance) {
  24202. if (currentDistance < maxDistance) {
  24203. return currentVolume * (1 - currentDistance / maxDistance);
  24204. } else {
  24205. return 0;
  24206. }
  24207. };
  24208. if (options) {
  24209. if (options.maxDistance) {
  24210. this.maxDistance = options.maxDistance;
  24211. }
  24212. if (options.autoplay) {
  24213. this.autoplay = options.autoplay;
  24214. }
  24215. if (options.loop) {
  24216. this.loop = options.loop;
  24217. }
  24218. if (options.volume) {
  24219. this._volume = options.volume;
  24220. }
  24221. if (options.useCustomAttenuation) {
  24222. this.maxDistance = Number.MAX_VALUE;
  24223. this.useCustomAttenuation = options.useCustomAttenuation;
  24224. }
  24225. if (options.spatialSound) {
  24226. this.spatialSound = options.spatialSound;
  24227. }
  24228. }
  24229. if (this._audioEngine.canUseWebAudio) {
  24230. this._soundGain = this._audioEngine.audioContext.createGain();
  24231. this._soundGain.gain.value = this._volume;
  24232. if (this.spatialSound) {
  24233. this._createSpatialParameters();
  24234. } else {
  24235. this._audioNode = this._soundGain;
  24236. }
  24237. this._scene.mainSoundTrack.AddSound(this);
  24238. BABYLON.Tools.LoadFile(url, function (data) {
  24239. _this._soundLoaded(data);
  24240. }, null, null, true);
  24241. }
  24242. }
  24243. Sound.prototype._createSpatialParameters = function () {
  24244. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24245. this._soundPanner.distanceModel = "linear";
  24246. this._soundPanner.maxDistance = this.maxDistance;
  24247. this._soundGain.connect(this._soundPanner);
  24248. this._audioNode = this._soundPanner;
  24249. };
  24250. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24251. if (this._audioEngine.canUseWebAudio) {
  24252. this._audioNode.disconnect();
  24253. this._audioNode.connect(soundTrackAudioNode);
  24254. }
  24255. };
  24256. /**
  24257. * Transform this sound into a directional source
  24258. * @param coneInnerAngle Size of the inner cone in degree
  24259. * @param coneOuterAngle Size of the outer cone in degree
  24260. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24261. */
  24262. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24263. if (coneOuterAngle < coneInnerAngle) {
  24264. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24265. return;
  24266. }
  24267. this._coneInnerAngle = coneInnerAngle;
  24268. this._coneOuterAngle = coneOuterAngle;
  24269. this._coneOuterGain = coneOuterGain;
  24270. this._isDirectional = true;
  24271. if (this._isPlaying && this.loop) {
  24272. this.stop();
  24273. this.play();
  24274. }
  24275. };
  24276. Sound.prototype.setPosition = function (newPosition) {
  24277. this._position = newPosition;
  24278. if (this._isPlaying && this.spatialSound) {
  24279. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24280. }
  24281. };
  24282. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24283. this._localDirection = newLocalDirection;
  24284. if (this._connectedMesh && this._isPlaying) {
  24285. this._updateDirection();
  24286. }
  24287. };
  24288. Sound.prototype._updateDirection = function () {
  24289. var mat = this._connectedMesh.getWorldMatrix();
  24290. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24291. direction.normalize();
  24292. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24293. };
  24294. Sound.prototype.updateDistanceFromListener = function () {
  24295. if (this._connectedMesh && this.useCustomAttenuation) {
  24296. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24297. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance);
  24298. }
  24299. };
  24300. Sound.prototype.setAttenuationFunction = function (callback) {
  24301. this._customAttenuationFunction = callback;
  24302. };
  24303. /**
  24304. * Play the sound
  24305. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24306. */
  24307. Sound.prototype.play = function (time) {
  24308. if (this._isReadyToPlay) {
  24309. try {
  24310. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24311. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24312. this._soundSource.buffer = this._audioBuffer;
  24313. if (this.spatialSound) {
  24314. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24315. if (this._isDirectional) {
  24316. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24317. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24318. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24319. if (this._connectedMesh) {
  24320. this._updateDirection();
  24321. } else {
  24322. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24323. }
  24324. }
  24325. }
  24326. this._soundSource.connect(this._audioNode);
  24327. this._soundSource.loop = this.loop;
  24328. this._soundSource.start(startTime);
  24329. this._isPlaying = true;
  24330. } catch (ex) {
  24331. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24332. }
  24333. }
  24334. };
  24335. /**
  24336. * Stop the sound
  24337. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24338. */
  24339. Sound.prototype.stop = function (time) {
  24340. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24341. this._soundSource.stop(stopTime);
  24342. this._isPlaying = false;
  24343. };
  24344. Sound.prototype.pause = function () {
  24345. // TODO
  24346. };
  24347. Sound.prototype.setVolume = function (newVolume) {
  24348. this._volume = newVolume;
  24349. this._soundGain.gain.value = newVolume;
  24350. };
  24351. Sound.prototype.getVolume = function () {
  24352. return this._volume;
  24353. };
  24354. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24355. var _this = this;
  24356. this._connectedMesh = meshToConnectTo;
  24357. if (!this.spatialSound) {
  24358. this._createSpatialParameters();
  24359. this.spatialSound = true;
  24360. }
  24361. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24362. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24363. });
  24364. };
  24365. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24366. this.setPosition(connectedMesh.position);
  24367. if (this._isDirectional && this._isPlaying) {
  24368. this._updateDirection();
  24369. }
  24370. };
  24371. Sound.prototype._soundLoaded = function (audioData) {
  24372. var _this = this;
  24373. this._isLoaded = true;
  24374. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24375. _this._audioBuffer = buffer;
  24376. _this._isReadyToPlay = true;
  24377. if (_this.autoplay) {
  24378. _this.play();
  24379. }
  24380. if (_this._readyToPlayCallback) {
  24381. _this._readyToPlayCallback();
  24382. }
  24383. }, function (error) {
  24384. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24385. });
  24386. };
  24387. return Sound;
  24388. })();
  24389. BABYLON.Sound = Sound;
  24390. })(BABYLON || (BABYLON = {}));
  24391. //# sourceMappingURL=babylon.sound.js.map
  24392. var BABYLON;
  24393. (function (BABYLON) {
  24394. var SoundTrack = (function () {
  24395. function SoundTrack(scene, options) {
  24396. this.id = -1;
  24397. this._isMainTrack = false;
  24398. this._scene = scene;
  24399. this._audioEngine = scene.getEngine().getAudioEngine();
  24400. this.soundCollection = new Array();
  24401. if (this._audioEngine.canUseWebAudio) {
  24402. this._trackGain = this._audioEngine.audioContext.createGain();
  24403. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24404. //this._trackConvolver.connect(this._trackGain);
  24405. this._trackGain.connect(this._audioEngine.masterGain);
  24406. if (options) {
  24407. if (options.volume) {
  24408. this._trackGain.gain.value = options.volume;
  24409. }
  24410. if (options.mainTrack) {
  24411. this._isMainTrack = options.mainTrack;
  24412. }
  24413. }
  24414. }
  24415. if (!this._isMainTrack) {
  24416. this._scene.soundTracks.push(this);
  24417. this.id = this._scene.soundTracks.length - 1;
  24418. }
  24419. }
  24420. SoundTrack.prototype.AddSound = function (sound) {
  24421. sound.connectToSoundTrackAudioNode(this._trackGain);
  24422. if (sound.soundTrackId) {
  24423. if (sound.soundTrackId === -1) {
  24424. this._scene.mainSoundTrack.RemoveSound(sound);
  24425. } else {
  24426. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24427. }
  24428. }
  24429. this.soundCollection.push(sound);
  24430. sound.soundTrackId = this.id;
  24431. };
  24432. SoundTrack.prototype.RemoveSound = function (sound) {
  24433. var index = this.soundCollection.indexOf(sound);
  24434. if (index !== -1) {
  24435. this.soundCollection.splice(index, 1);
  24436. }
  24437. };
  24438. SoundTrack.prototype.setVolume = function (newVolume) {
  24439. if (this._audioEngine.canUseWebAudio) {
  24440. this._trackGain.gain.value = newVolume;
  24441. }
  24442. };
  24443. return SoundTrack;
  24444. })();
  24445. BABYLON.SoundTrack = SoundTrack;
  24446. })(BABYLON || (BABYLON = {}));
  24447. //# sourceMappingURL=babylon.soundtrack.js.map
  24448. var BABYLON;
  24449. (function (BABYLON) {
  24450. var DebugLayer = (function () {
  24451. function DebugLayer(scene) {
  24452. var _this = this;
  24453. this._enabled = false;
  24454. this._labelsEnabled = false;
  24455. this._displayStatistics = true;
  24456. this._displayTree = false;
  24457. this._displayLogs = false;
  24458. this._identityMatrix = BABYLON.Matrix.Identity();
  24459. this.axisRatio = 0.02;
  24460. this.accentColor = "orange";
  24461. this._scene = scene;
  24462. this._syncPositions = function () {
  24463. var engine = _this._scene.getEngine();
  24464. var canvasRect = engine.getRenderingCanvasClientRect();
  24465. if (_this._showUI) {
  24466. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24467. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24468. _this._statsDiv.style.width = "300px";
  24469. _this._statsDiv.style.height = "360px";
  24470. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24471. _this._optionsDiv.style.left = "0px";
  24472. _this._optionsDiv.style.top = "10px";
  24473. _this._optionsDiv.style.width = "200px";
  24474. _this._optionsDiv.style.height = "auto";
  24475. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24476. _this._logDiv.style.left = "0px";
  24477. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24478. _this._logDiv.style.width = "600px";
  24479. _this._logDiv.style.height = "160px";
  24480. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24481. _this._treeDiv.style.top = "10px";
  24482. _this._treeDiv.style.width = "300px";
  24483. _this._treeDiv.style.height = "auto";
  24484. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24485. }
  24486. _this._globalDiv.style.left = canvasRect.left + "px";
  24487. _this._globalDiv.style.top = canvasRect.top + "px";
  24488. _this._drawingCanvas.style.left = "0px";
  24489. _this._drawingCanvas.style.top = "0px";
  24490. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24491. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24492. var devicePixelRatio = window.devicePixelRatio || 1;
  24493. var context = _this._drawingContext;
  24494. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24495. _this._ratio = devicePixelRatio / backingStoreRatio;
  24496. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24497. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24498. };
  24499. this._onCanvasClick = function (evt) {
  24500. _this._clickPosition = {
  24501. x: evt.clientX * _this._ratio,
  24502. y: evt.clientY * _this._ratio
  24503. };
  24504. };
  24505. this._syncData = function () {
  24506. if (_this._showUI) {
  24507. if (_this._displayStatistics) {
  24508. _this._displayStats();
  24509. _this._statsDiv.style.display = "";
  24510. } else {
  24511. _this._statsDiv.style.display = "none";
  24512. }
  24513. if (_this._displayLogs) {
  24514. _this._logDiv.style.display = "";
  24515. } else {
  24516. _this._logDiv.style.display = "none";
  24517. }
  24518. if (_this._displayTree) {
  24519. _this._treeDiv.style.display = "";
  24520. if (_this._needToRefreshMeshesTree) {
  24521. _this._needToRefreshMeshesTree = false;
  24522. _this._refreshMeshesTreeContent();
  24523. }
  24524. } else {
  24525. _this._treeDiv.style.display = "none";
  24526. }
  24527. }
  24528. if (_this._labelsEnabled || !_this._showUI) {
  24529. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24530. var engine = _this._scene.getEngine();
  24531. var viewport = _this._scene.activeCamera.viewport;
  24532. var globalViewport = viewport.toGlobal(engine);
  24533. // Meshes
  24534. var meshes = _this._scene.getActiveMeshes();
  24535. for (var index = 0; index < meshes.length; index++) {
  24536. var mesh = meshes.data[index];
  24537. var position = mesh.getBoundingInfo().boundingSphere.center;
  24538. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24539. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24540. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24541. }
  24542. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24543. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24544. mesh.renderOverlay = !mesh.renderOverlay;
  24545. }, function () {
  24546. return mesh.renderOverlay ? 'red' : 'black';
  24547. });
  24548. }
  24549. }
  24550. // Cameras
  24551. var cameras = _this._scene.cameras;
  24552. for (index = 0; index < cameras.length; index++) {
  24553. var camera = cameras[index];
  24554. if (camera === _this._scene.activeCamera) {
  24555. continue;
  24556. }
  24557. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24558. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24559. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24560. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24561. _this._scene.activeCamera = camera;
  24562. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24563. }, function () {
  24564. return "purple";
  24565. });
  24566. }
  24567. }
  24568. // Lights
  24569. var lights = _this._scene.lights;
  24570. for (index = 0; index < lights.length; index++) {
  24571. var light = lights[index];
  24572. if (light.position) {
  24573. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24574. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24575. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24576. light.setEnabled(!light.isEnabled());
  24577. }, function () {
  24578. return light.isEnabled() ? "orange" : "gray";
  24579. });
  24580. }
  24581. }
  24582. }
  24583. }
  24584. _this._clickPosition = undefined;
  24585. };
  24586. }
  24587. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24588. while (this._treeSubsetDiv.hasChildNodes()) {
  24589. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24590. }
  24591. // Add meshes
  24592. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24593. sortedArray.sort(function (a, b) {
  24594. if (a.name === b.name) {
  24595. return 0;
  24596. }
  24597. return (a.name > b.name) ? 1 : -1;
  24598. });
  24599. for (var index = 0; index < sortedArray.length; index++) {
  24600. var mesh = sortedArray[index];
  24601. if (!mesh.isEnabled()) {
  24602. continue;
  24603. }
  24604. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24605. m.isVisible = element.checked;
  24606. }, mesh);
  24607. }
  24608. };
  24609. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24610. this._drawingContext.beginPath();
  24611. this._drawingContext.moveTo(zero.x, zero.y);
  24612. this._drawingContext.lineTo(unit.x, unit.y);
  24613. this._drawingContext.strokeStyle = color;
  24614. this._drawingContext.lineWidth = 4;
  24615. this._drawingContext.stroke();
  24616. this._drawingContext.font = "normal 14px Segoe UI";
  24617. this._drawingContext.fillStyle = color;
  24618. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24619. };
  24620. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24621. var position = mesh.getBoundingInfo().boundingSphere.center;
  24622. var worldMatrix = mesh.getWorldMatrix();
  24623. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  24624. var unit = (unprojectedVector.subtract(position)).length();
  24625. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24626. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24627. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24628. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24629. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24630. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24631. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24632. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24633. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24634. };
  24635. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24636. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24637. this._drawingContext.font = "normal 12px Segoe UI";
  24638. var textMetrics = this._drawingContext.measureText(text);
  24639. var centerX = projectedPosition.x - textMetrics.width / 2;
  24640. var centerY = projectedPosition.y;
  24641. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24642. onClick();
  24643. }
  24644. this._drawingContext.beginPath();
  24645. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24646. this._drawingContext.fillStyle = getFillStyle();
  24647. this._drawingContext.globalAlpha = 0.5;
  24648. this._drawingContext.fill();
  24649. this._drawingContext.globalAlpha = 1.0;
  24650. this._drawingContext.strokeStyle = '#FFFFFF';
  24651. this._drawingContext.lineWidth = 1;
  24652. this._drawingContext.stroke();
  24653. this._drawingContext.fillStyle = "#FFFFFF";
  24654. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24655. this._drawingContext.beginPath();
  24656. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24657. this._drawingContext.fill();
  24658. }
  24659. };
  24660. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24661. if (!this._clickPosition) {
  24662. return false;
  24663. }
  24664. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24665. return false;
  24666. }
  24667. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24668. return false;
  24669. }
  24670. return true;
  24671. };
  24672. DebugLayer.prototype.isVisible = function () {
  24673. return this._enabled;
  24674. };
  24675. DebugLayer.prototype.hide = function () {
  24676. if (!this._enabled) {
  24677. return;
  24678. }
  24679. this._enabled = false;
  24680. var engine = this._scene.getEngine();
  24681. this._scene.unregisterAfterRender(this._syncData);
  24682. document.body.removeChild(this._globalDiv);
  24683. window.removeEventListener("resize", this._syncPositions);
  24684. this._scene.forceShowBoundingBoxes = false;
  24685. this._scene.forceWireframe = false;
  24686. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24687. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24688. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24689. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24690. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24691. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24692. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24693. this._scene.shadowsEnabled = true;
  24694. this._scene.particlesEnabled = true;
  24695. this._scene.postProcessesEnabled = true;
  24696. this._scene.collisionsEnabled = true;
  24697. this._scene.lightsEnabled = true;
  24698. this._scene.texturesEnabled = true;
  24699. this._scene.lensFlaresEnabled = true;
  24700. this._scene.proceduralTexturesEnabled = true;
  24701. this._scene.renderTargetsEnabled = true;
  24702. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24703. };
  24704. DebugLayer.prototype.show = function (showUI) {
  24705. if (typeof showUI === "undefined") { showUI = true; }
  24706. if (this._enabled) {
  24707. return;
  24708. }
  24709. this._enabled = true;
  24710. this._showUI = showUI;
  24711. var engine = this._scene.getEngine();
  24712. this._globalDiv = document.createElement("div");
  24713. document.body.appendChild(this._globalDiv);
  24714. this._generateDOMelements();
  24715. window.addEventListener("resize", this._syncPositions);
  24716. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24717. this._syncPositions();
  24718. this._scene.registerAfterRender(this._syncData);
  24719. };
  24720. DebugLayer.prototype._clearLabels = function () {
  24721. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24722. for (var index = 0; index < this._scene.meshes.length; index++) {
  24723. var mesh = this._scene.meshes[index];
  24724. mesh.renderOverlay = false;
  24725. }
  24726. };
  24727. DebugLayer.prototype._generateheader = function (root, text) {
  24728. var header = document.createElement("div");
  24729. header.innerHTML = text + "&nbsp;";
  24730. header.style.textAlign = "right";
  24731. header.style.width = "100%";
  24732. header.style.color = "white";
  24733. header.style.backgroundColor = "Black";
  24734. header.style.padding = "5px 5px 4px 0px";
  24735. header.style.marginLeft = "-5px";
  24736. header.style.fontWeight = "bold";
  24737. root.appendChild(header);
  24738. };
  24739. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24740. var label = document.createElement("label");
  24741. label.innerHTML = title;
  24742. label.style.color = color;
  24743. root.appendChild(label);
  24744. root.appendChild(document.createElement("br"));
  24745. };
  24746. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24747. if (typeof tag === "undefined") { tag = null; }
  24748. var label = document.createElement("label");
  24749. var boundingBoxesCheckbox = document.createElement("input");
  24750. boundingBoxesCheckbox.type = "checkbox";
  24751. boundingBoxesCheckbox.checked = initialState;
  24752. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24753. task(evt.target, tag);
  24754. });
  24755. label.appendChild(boundingBoxesCheckbox);
  24756. var container = document.createElement("span");
  24757. var leftPart = document.createElement("span");
  24758. var rightPart = document.createElement("span");
  24759. rightPart.style.cssFloat = "right";
  24760. leftPart.innerHTML = leftTitle;
  24761. rightPart.innerHTML = rightTitle;
  24762. rightPart.style.fontSize = "12px";
  24763. rightPart.style.maxWidth = "200px";
  24764. container.appendChild(leftPart);
  24765. container.appendChild(rightPart);
  24766. label.appendChild(container);
  24767. root.appendChild(label);
  24768. root.appendChild(document.createElement("br"));
  24769. };
  24770. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24771. if (typeof tag === "undefined") { tag = null; }
  24772. var label = document.createElement("label");
  24773. var boundingBoxesCheckbox = document.createElement("input");
  24774. boundingBoxesCheckbox.type = "checkbox";
  24775. boundingBoxesCheckbox.checked = initialState;
  24776. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24777. task(evt.target, tag);
  24778. });
  24779. label.appendChild(boundingBoxesCheckbox);
  24780. label.appendChild(document.createTextNode(title));
  24781. root.appendChild(label);
  24782. root.appendChild(document.createElement("br"));
  24783. };
  24784. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24785. if (typeof tag === "undefined") { tag = null; }
  24786. var label = document.createElement("label");
  24787. var boundingBoxesRadio = document.createElement("input");
  24788. boundingBoxesRadio.type = "radio";
  24789. boundingBoxesRadio.name = name;
  24790. boundingBoxesRadio.checked = initialState;
  24791. boundingBoxesRadio.addEventListener("change", function (evt) {
  24792. task(evt.target, tag);
  24793. });
  24794. label.appendChild(boundingBoxesRadio);
  24795. label.appendChild(document.createTextNode(title));
  24796. root.appendChild(label);
  24797. root.appendChild(document.createElement("br"));
  24798. };
  24799. DebugLayer.prototype._generateDOMelements = function () {
  24800. var _this = this;
  24801. this._globalDiv.id = "DebugLayer";
  24802. this._globalDiv.style.position = "absolute";
  24803. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24804. this._globalDiv.style.fontSize = "14px";
  24805. this._globalDiv.style.color = "white";
  24806. // Drawing canvas
  24807. this._drawingCanvas = document.createElement("canvas");
  24808. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24809. this._drawingCanvas.style.position = "absolute";
  24810. this._drawingCanvas.style.pointerEvents = "none";
  24811. this._drawingContext = this._drawingCanvas.getContext("2d");
  24812. this._globalDiv.appendChild(this._drawingCanvas);
  24813. if (this._showUI) {
  24814. var background = "rgba(128, 128, 128, 0.4)";
  24815. var border = "rgb(180, 180, 180) solid 1px";
  24816. // Stats
  24817. this._statsDiv = document.createElement("div");
  24818. this._statsDiv.id = "DebugLayerStats";
  24819. this._statsDiv.style.border = border;
  24820. this._statsDiv.style.position = "absolute";
  24821. this._statsDiv.style.background = background;
  24822. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24823. this._statsDiv.style.pointerEvents = "none";
  24824. this._statsDiv.style.overflowY = "auto";
  24825. this._generateheader(this._statsDiv, "STATISTICS");
  24826. this._statsSubsetDiv = document.createElement("div");
  24827. this._statsSubsetDiv.style.paddingTop = "5px";
  24828. this._statsSubsetDiv.style.paddingBottom = "5px";
  24829. this._statsDiv.appendChild(this._statsSubsetDiv);
  24830. // Tree
  24831. this._treeDiv = document.createElement("div");
  24832. this._treeDiv.id = "DebugLayerTree";
  24833. this._treeDiv.style.border = border;
  24834. this._treeDiv.style.position = "absolute";
  24835. this._treeDiv.style.background = background;
  24836. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24837. this._treeDiv.style.display = "none";
  24838. this._generateheader(this._treeDiv, "MESHES TREE");
  24839. this._treeSubsetDiv = document.createElement("div");
  24840. this._treeSubsetDiv.style.paddingTop = "5px";
  24841. this._treeSubsetDiv.style.paddingRight = "5px";
  24842. this._treeSubsetDiv.style.overflowY = "auto";
  24843. this._treeSubsetDiv.style.maxHeight = "300px";
  24844. this._treeDiv.appendChild(this._treeSubsetDiv);
  24845. this._needToRefreshMeshesTree = true;
  24846. // Logs
  24847. this._logDiv = document.createElement("div");
  24848. this._logDiv.style.border = border;
  24849. this._logDiv.id = "DebugLayerLogs";
  24850. this._logDiv.style.position = "absolute";
  24851. this._logDiv.style.background = background;
  24852. this._logDiv.style.padding = "0px 0px 0px 5px";
  24853. this._logDiv.style.display = "none";
  24854. this._generateheader(this._logDiv, "LOGS");
  24855. this._logSubsetDiv = document.createElement("div");
  24856. this._logSubsetDiv.style.height = "127px";
  24857. this._logSubsetDiv.style.paddingTop = "5px";
  24858. this._logSubsetDiv.style.overflowY = "auto";
  24859. this._logSubsetDiv.style.fontSize = "12px";
  24860. this._logSubsetDiv.style.fontFamily = "consolas";
  24861. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24862. this._logDiv.appendChild(this._logSubsetDiv);
  24863. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24864. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24865. };
  24866. // Options
  24867. this._optionsDiv = document.createElement("div");
  24868. this._optionsDiv.id = "DebugLayerOptions";
  24869. this._optionsDiv.style.border = border;
  24870. this._optionsDiv.style.position = "absolute";
  24871. this._optionsDiv.style.background = background;
  24872. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24873. this._optionsDiv.style.overflowY = "auto";
  24874. this._generateheader(this._optionsDiv, "OPTIONS");
  24875. this._optionsSubsetDiv = document.createElement("div");
  24876. this._optionsSubsetDiv.style.paddingTop = "5px";
  24877. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24878. this._optionsSubsetDiv.style.overflowY = "auto";
  24879. this._optionsSubsetDiv.style.maxHeight = "200px";
  24880. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24881. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24882. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24883. _this._displayStatistics = element.checked;
  24884. });
  24885. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24886. _this._displayLogs = element.checked;
  24887. });
  24888. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24889. _this._displayTree = element.checked;
  24890. _this._needToRefreshMeshesTree = true;
  24891. });
  24892. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24893. _this._scene.forceShowBoundingBoxes = element.checked;
  24894. });
  24895. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24896. _this._labelsEnabled = element.checked;
  24897. if (!_this._labelsEnabled) {
  24898. _this._clearLabels();
  24899. }
  24900. });
  24901. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24902. if (element.checked) {
  24903. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24904. } else {
  24905. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24906. }
  24907. });
  24908. ;
  24909. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24910. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24911. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24912. if (element.checked) {
  24913. _this._scene.forceWireframe = false;
  24914. _this._scene.forcePointsCloud = false;
  24915. }
  24916. });
  24917. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  24918. if (element.checked) {
  24919. _this._scene.forceWireframe = true;
  24920. _this._scene.forcePointsCloud = false;
  24921. }
  24922. });
  24923. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  24924. if (element.checked) {
  24925. _this._scene.forceWireframe = false;
  24926. _this._scene.forcePointsCloud = true;
  24927. }
  24928. });
  24929. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24930. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  24931. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  24932. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  24933. });
  24934. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  24935. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  24936. });
  24937. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  24938. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  24939. });
  24940. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  24941. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  24942. });
  24943. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  24944. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  24945. });
  24946. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  24947. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  24948. });
  24949. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  24950. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  24951. });
  24952. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  24953. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  24954. });
  24955. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24956. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  24957. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  24958. _this._scene.animationsEnabled = element.checked;
  24959. });
  24960. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  24961. _this._scene.collisionsEnabled = element.checked;
  24962. });
  24963. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  24964. _this._scene.fogEnabled = element.checked;
  24965. });
  24966. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  24967. _this._scene.lensFlaresEnabled = element.checked;
  24968. });
  24969. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  24970. _this._scene.lightsEnabled = element.checked;
  24971. });
  24972. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  24973. _this._scene.particlesEnabled = element.checked;
  24974. });
  24975. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  24976. _this._scene.postProcessesEnabled = element.checked;
  24977. });
  24978. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  24979. _this._scene.proceduralTexturesEnabled = element.checked;
  24980. });
  24981. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  24982. _this._scene.renderTargetsEnabled = element.checked;
  24983. });
  24984. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  24985. _this._scene.shadowsEnabled = element.checked;
  24986. });
  24987. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  24988. _this._scene.skeletonsEnabled = element.checked;
  24989. });
  24990. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  24991. _this._scene.texturesEnabled = element.checked;
  24992. });
  24993. this._globalDiv.appendChild(this._statsDiv);
  24994. this._globalDiv.appendChild(this._logDiv);
  24995. this._globalDiv.appendChild(this._optionsDiv);
  24996. this._globalDiv.appendChild(this._treeDiv);
  24997. }
  24998. };
  24999. DebugLayer.prototype._displayStats = function () {
  25000. var scene = this._scene;
  25001. var engine = scene.getEngine();
  25002. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br><br>" + "Frame duration: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<i>Evaluate Active Meshes duration:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "<i>Render Targets duration:</i> " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "<i>Particles duration:</i> " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "<i>Sprites duration:</i> " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br>" + "<i>Render duration:</i> <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b>";
  25003. };
  25004. return DebugLayer;
  25005. })();
  25006. BABYLON.DebugLayer = DebugLayer;
  25007. })(BABYLON || (BABYLON = {}));
  25008. //# sourceMappingURL=babylon.debugLayer.js.map
  25009. var BABYLON;
  25010. (function (BABYLON) {
  25011. var RawTexture = (function (_super) {
  25012. __extends(RawTexture, _super);
  25013. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25014. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25015. if (typeof invertY === "undefined") { invertY = false; }
  25016. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25017. _super.call(this, null, scene, !generateMipMaps, invertY);
  25018. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25019. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25020. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25021. }
  25022. // Statics
  25023. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25024. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25025. if (typeof invertY === "undefined") { invertY = false; }
  25026. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25027. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25028. };
  25029. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25030. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25031. if (typeof invertY === "undefined") { invertY = false; }
  25032. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25033. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25034. };
  25035. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25036. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25037. if (typeof invertY === "undefined") { invertY = false; }
  25038. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25039. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25040. };
  25041. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25042. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25043. if (typeof invertY === "undefined") { invertY = false; }
  25044. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25045. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25046. };
  25047. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25048. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25049. if (typeof invertY === "undefined") { invertY = false; }
  25050. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25051. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25052. };
  25053. return RawTexture;
  25054. })(BABYLON.Texture);
  25055. BABYLON.RawTexture = RawTexture;
  25056. })(BABYLON || (BABYLON = {}));
  25057. //# sourceMappingURL=babylon.rawTexture.js.map
  25058. var BABYLON;
  25059. (function (BABYLON) {
  25060. var IndexedVector2 = (function (_super) {
  25061. __extends(IndexedVector2, _super);
  25062. function IndexedVector2(original, index) {
  25063. _super.call(this, original.x, original.y);
  25064. this.index = index;
  25065. }
  25066. return IndexedVector2;
  25067. })(BABYLON.Vector2);
  25068. var PolygonPoints = (function () {
  25069. function PolygonPoints() {
  25070. this.elements = new Array();
  25071. }
  25072. PolygonPoints.prototype.add = function (originalPoints) {
  25073. var _this = this;
  25074. var result = new Array();
  25075. originalPoints.forEach(function (point) {
  25076. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y))) {
  25077. var newPoint = new IndexedVector2(point, _this.elements.length);
  25078. result.push(newPoint);
  25079. _this.elements.push(newPoint);
  25080. }
  25081. });
  25082. return result;
  25083. };
  25084. PolygonPoints.prototype.computeBounds = function () {
  25085. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25086. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25087. this.elements.forEach(function (point) {
  25088. // x
  25089. if (point.x < lmin.x) {
  25090. lmin.x = point.x;
  25091. } else if (point.x > lmax.x) {
  25092. lmax.x = point.x;
  25093. }
  25094. // y
  25095. if (point.y < lmin.y) {
  25096. lmin.y = point.y;
  25097. } else if (point.y > lmax.y) {
  25098. lmax.y = point.y;
  25099. }
  25100. });
  25101. return {
  25102. min: lmin,
  25103. max: lmax,
  25104. width: lmax.x - lmin.x,
  25105. height: lmax.y - lmin.y
  25106. };
  25107. };
  25108. return PolygonPoints;
  25109. })();
  25110. var Polygon = (function () {
  25111. function Polygon() {
  25112. }
  25113. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25114. return [
  25115. new BABYLON.Vector2(xmin, ymin),
  25116. new BABYLON.Vector2(xmax, ymin),
  25117. new BABYLON.Vector2(xmax, ymax),
  25118. new BABYLON.Vector2(xmin, ymax)
  25119. ];
  25120. };
  25121. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25122. if (typeof cx === "undefined") { cx = 0; }
  25123. if (typeof cy === "undefined") { cy = 0; }
  25124. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25125. var result = new Array();
  25126. var angle = 0;
  25127. var increment = (Math.PI * 2) / numberOfSides;
  25128. for (var i = 0; i < numberOfSides; i++) {
  25129. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25130. angle -= increment;
  25131. }
  25132. return result;
  25133. };
  25134. Polygon.Parse = function (input) {
  25135. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25136. return (!isNaN(val));
  25137. });
  25138. var i, result = [];
  25139. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25140. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25141. }
  25142. return result;
  25143. };
  25144. Polygon.StartingAt = function (x, y) {
  25145. return BABYLON.Path2.StartingAt(x, y);
  25146. };
  25147. return Polygon;
  25148. })();
  25149. BABYLON.Polygon = Polygon;
  25150. var PolygonMeshBuilder = (function () {
  25151. function PolygonMeshBuilder(name, contours, scene) {
  25152. this._points = new PolygonPoints();
  25153. if (!("poly2tri" in window)) {
  25154. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25155. }
  25156. this._name = name;
  25157. this._scene = scene;
  25158. var points;
  25159. if (contours instanceof BABYLON.Path2) {
  25160. points = contours.getPoints();
  25161. } else {
  25162. points = contours;
  25163. }
  25164. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25165. }
  25166. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25167. this._swctx.addHole(this._points.add(hole));
  25168. return this;
  25169. };
  25170. PolygonMeshBuilder.prototype.build = function (updatable) {
  25171. if (typeof updatable === "undefined") { updatable = false; }
  25172. var result = new BABYLON.Mesh(this._name, this._scene);
  25173. var normals = [];
  25174. var positions = [];
  25175. var uvs = [];
  25176. var bounds = this._points.computeBounds();
  25177. this._points.elements.forEach(function (p) {
  25178. normals.push(0, 1.0, 0);
  25179. positions.push(p.x, 0, p.y);
  25180. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25181. });
  25182. var indices = [];
  25183. this._swctx.triangulate();
  25184. this._swctx.getTriangles().forEach(function (triangle) {
  25185. triangle.getPoints().forEach(function (point) {
  25186. indices.push(point.index);
  25187. });
  25188. });
  25189. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25190. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25191. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25192. result.setIndices(indices);
  25193. return result;
  25194. };
  25195. return PolygonMeshBuilder;
  25196. })();
  25197. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25198. })(BABYLON || (BABYLON = {}));
  25199. //# sourceMappingURL=babylon.polygonMesh.js.map