babylon.2.0-alpha.debug.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465
  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. BABYLON.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 = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  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 = BABYLON.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 = BABYLON.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.000) {
  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 = BABYLON.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 BABYLON.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 BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1773. };
  1774. Plane.FromPoints = function (point1, point2, point3) {
  1775. var result = new BABYLON.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 BABYLON.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 = BABYLON.Vector3.Zero();
  1961. this._edge2 = BABYLON.Vector3.Zero();
  1962. this._pvec = BABYLON.Vector3.Zero();
  1963. this._tvec = BABYLON.Vector3.Zero();
  1964. this._qvec = BABYLON.Vector3.Zero();
  1965. }
  1966. vertex1.subtractToRef(vertex0, this._edge1);
  1967. vertex2.subtractToRef(vertex0, this._edge2);
  1968. BABYLON.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 = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1994. var end = BABYLON.Vector3.Unproject(new BABYLON.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 = BABYLON.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 = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  2015. var newDirection = BABYLON.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 BABYLON.Vector3(1, 0, 0);
  2030. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  2031. Axis.Z = new BABYLON.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 Arc = (function () {
  2092. function Arc(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 Arc;
  2119. })();
  2120. BABYLON.Arc = Arc;
  2121. var Path = (function () {
  2122. function Path(x, y) {
  2123. this._points = [];
  2124. this._points.push(new Vector2(x, y));
  2125. }
  2126. Path.prototype.addLineTo = function (x, y) {
  2127. this._points.push(new Vector2(x, y));
  2128. return this;
  2129. };
  2130. Path.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2131. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2132. var startPoint = this._points[this._points.length - 1];
  2133. var midPoint = new Vector2(midX, midY);
  2134. var endPoint = new Vector2(endX, endY);
  2135. var arc = new Arc(startPoint, midPoint, endPoint);
  2136. var increment = arc.angle.radians() / numberOfSegments;
  2137. if (arc.orientation === 0 /* CW */)
  2138. increment *= -1;
  2139. var currentAngle = arc.startAngle.radians() + increment;
  2140. for (var i = 0; i < numberOfSegments; i++) {
  2141. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2142. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2143. this.addLineTo(x, y);
  2144. currentAngle += increment;
  2145. }
  2146. return this;
  2147. };
  2148. Path.prototype.close = function () {
  2149. return this._points;
  2150. };
  2151. Path.StartingAt = function (x, y) {
  2152. return new Path(x, y);
  2153. };
  2154. return Path;
  2155. })();
  2156. BABYLON.Path = Path;
  2157. })(BABYLON || (BABYLON = {}));
  2158. //# sourceMappingURL=babylon.math.js.map
  2159. var BABYLON;
  2160. (function (BABYLON) {
  2161. // Screenshots
  2162. var screenshotCanvas;
  2163. var cloneValue = function (source, destinationObject) {
  2164. if (!source)
  2165. return null;
  2166. if (source instanceof BABYLON.Mesh) {
  2167. return null;
  2168. }
  2169. if (source instanceof BABYLON.SubMesh) {
  2170. return source.clone(destinationObject);
  2171. } else if (source.clone) {
  2172. return source.clone();
  2173. }
  2174. return null;
  2175. };
  2176. var Tools = (function () {
  2177. function Tools() {
  2178. }
  2179. Tools.GetFilename = function (path) {
  2180. var index = path.lastIndexOf("/");
  2181. if (index < 0)
  2182. return path;
  2183. return path.substring(index + 1);
  2184. };
  2185. Tools.GetDOMTextContent = function (element) {
  2186. var result = "";
  2187. var child = element.firstChild;
  2188. while (child) {
  2189. if (child.nodeType == 3) {
  2190. result += child.textContent;
  2191. }
  2192. child = child.nextSibling;
  2193. }
  2194. return result;
  2195. };
  2196. Tools.ToDegrees = function (angle) {
  2197. return angle * 180 / Math.PI;
  2198. };
  2199. Tools.ToRadians = function (angle) {
  2200. return angle * Math.PI / 180;
  2201. };
  2202. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2203. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2204. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2205. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2206. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2207. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2208. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2209. }
  2210. return {
  2211. minimum: minimum,
  2212. maximum: maximum
  2213. };
  2214. };
  2215. Tools.ExtractMinAndMax = function (positions, start, count) {
  2216. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2217. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2218. for (var index = start; index < start + count; index++) {
  2219. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2220. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2221. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2222. }
  2223. return {
  2224. minimum: minimum,
  2225. maximum: maximum
  2226. };
  2227. };
  2228. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2229. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2230. return undefined;
  2231. return Array.isArray(obj) ? obj : [obj];
  2232. };
  2233. // Misc.
  2234. Tools.GetPointerPrefix = function () {
  2235. var eventPrefix = "pointer";
  2236. // Check if hand.js is referenced or if the browser natively supports pointer events
  2237. if (!navigator.pointerEnabled) {
  2238. eventPrefix = "mouse";
  2239. }
  2240. return eventPrefix;
  2241. };
  2242. Tools.QueueNewFrame = function (func) {
  2243. if (window.requestAnimationFrame)
  2244. window.requestAnimationFrame(func);
  2245. else if (window.msRequestAnimationFrame)
  2246. window.msRequestAnimationFrame(func);
  2247. else if (window.webkitRequestAnimationFrame)
  2248. window.webkitRequestAnimationFrame(func);
  2249. else if (window.mozRequestAnimationFrame)
  2250. window.mozRequestAnimationFrame(func);
  2251. else if (window.oRequestAnimationFrame)
  2252. window.oRequestAnimationFrame(func);
  2253. else {
  2254. window.setTimeout(func, 16);
  2255. }
  2256. };
  2257. Tools.RequestFullscreen = function (element) {
  2258. if (element.requestFullscreen)
  2259. element.requestFullscreen();
  2260. else if (element.msRequestFullscreen)
  2261. element.msRequestFullscreen();
  2262. else if (element.webkitRequestFullscreen)
  2263. element.webkitRequestFullscreen();
  2264. else if (element.mozRequestFullScreen)
  2265. element.mozRequestFullScreen();
  2266. };
  2267. Tools.ExitFullscreen = function () {
  2268. if (document.exitFullscreen) {
  2269. document.exitFullscreen();
  2270. } else if (document.mozCancelFullScreen) {
  2271. document.mozCancelFullScreen();
  2272. } else if (document.webkitCancelFullScreen) {
  2273. document.webkitCancelFullScreen();
  2274. } else if (document.msCancelFullScreen) {
  2275. document.msCancelFullScreen();
  2276. }
  2277. };
  2278. // External files
  2279. Tools.CleanUrl = function (url) {
  2280. url = url.replace(/#/mg, "%23");
  2281. return url;
  2282. };
  2283. Tools.LoadImage = function (url, onload, onerror, database) {
  2284. url = Tools.CleanUrl(url);
  2285. var img = new Image();
  2286. if (url.substr(0, 5) != "data:")
  2287. img.crossOrigin = 'anonymous';
  2288. img.onload = function () {
  2289. onload(img);
  2290. };
  2291. img.onerror = function (err) {
  2292. onerror(img, err);
  2293. };
  2294. var noIndexedDB = function () {
  2295. img.src = url;
  2296. };
  2297. var loadFromIndexedDB = function () {
  2298. database.loadImageFromDB(url, img);
  2299. };
  2300. //ANY database to do!
  2301. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2302. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2303. } else {
  2304. if (url.indexOf("file:") === -1) {
  2305. noIndexedDB();
  2306. } else {
  2307. try {
  2308. var textureName = url.substring(5);
  2309. var blobURL;
  2310. try {
  2311. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2312. } catch (ex) {
  2313. // Chrome doesn't support oneTimeOnly parameter
  2314. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2315. }
  2316. img.src = blobURL;
  2317. } catch (e) {
  2318. Tools.Log("Error while trying to load texture: " + textureName);
  2319. img.src = null;
  2320. }
  2321. }
  2322. }
  2323. return img;
  2324. };
  2325. //ANY
  2326. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2327. url = Tools.CleanUrl(url);
  2328. var noIndexedDB = function () {
  2329. var request = new XMLHttpRequest();
  2330. var loadUrl = Tools.BaseUrl + url;
  2331. request.open('GET', loadUrl, true);
  2332. if (useArrayBuffer) {
  2333. request.responseType = "arraybuffer";
  2334. }
  2335. request.onprogress = progressCallBack;
  2336. request.onreadystatechange = function () {
  2337. if (request.readyState == 4) {
  2338. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2339. callback(!useArrayBuffer ? request.responseText : request.response);
  2340. } else {
  2341. if (onError) {
  2342. onError();
  2343. } else {
  2344. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2345. }
  2346. }
  2347. }
  2348. };
  2349. request.send(null);
  2350. };
  2351. var loadFromIndexedDB = function () {
  2352. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2353. };
  2354. if (url.indexOf("file:") !== -1) {
  2355. var fileName = url.substring(5);
  2356. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2357. } else {
  2358. // Caching all files
  2359. if (database && database.enableSceneOffline) {
  2360. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2361. } else {
  2362. noIndexedDB();
  2363. }
  2364. }
  2365. };
  2366. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2367. var reader = new FileReader();
  2368. reader.onload = function (e) {
  2369. callback(e.target.result);
  2370. };
  2371. reader.onprogress = progressCallback;
  2372. reader.readAsDataURL(fileToLoad);
  2373. };
  2374. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2375. var reader = new FileReader();
  2376. reader.onload = function (e) {
  2377. callback(e.target.result);
  2378. };
  2379. reader.onprogress = progressCallBack;
  2380. if (!useArrayBuffer) {
  2381. // Asynchronous read
  2382. reader.readAsText(fileToLoad);
  2383. } else {
  2384. reader.readAsArrayBuffer(fileToLoad);
  2385. }
  2386. };
  2387. // Misc.
  2388. Tools.Clamp = function (value, min, max) {
  2389. if (typeof min === "undefined") { min = 0; }
  2390. if (typeof max === "undefined") { max = 1; }
  2391. return Math.min(max, Math.max(min, value));
  2392. };
  2393. Tools.Format = function (value, decimals) {
  2394. if (typeof decimals === "undefined") { decimals = 2; }
  2395. return value.toFixed(decimals);
  2396. };
  2397. Tools.CheckExtends = function (v, min, max) {
  2398. if (v.x < min.x)
  2399. min.x = v.x;
  2400. if (v.y < min.y)
  2401. min.y = v.y;
  2402. if (v.z < min.z)
  2403. min.z = v.z;
  2404. if (v.x > max.x)
  2405. max.x = v.x;
  2406. if (v.y > max.y)
  2407. max.y = v.y;
  2408. if (v.z > max.z)
  2409. max.z = v.z;
  2410. };
  2411. Tools.WithinEpsilon = function (a, b) {
  2412. var num = a - b;
  2413. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2414. };
  2415. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2416. for (var prop in source) {
  2417. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2418. continue;
  2419. }
  2420. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2421. continue;
  2422. }
  2423. var sourceValue = source[prop];
  2424. var typeOfSourceValue = typeof sourceValue;
  2425. if (typeOfSourceValue == "function") {
  2426. continue;
  2427. }
  2428. if (typeOfSourceValue == "object") {
  2429. if (sourceValue instanceof Array) {
  2430. destination[prop] = [];
  2431. if (sourceValue.length > 0) {
  2432. if (typeof sourceValue[0] == "object") {
  2433. for (var index = 0; index < sourceValue.length; index++) {
  2434. var clonedValue = cloneValue(sourceValue[index], destination);
  2435. if (destination[prop].indexOf(clonedValue) === -1) {
  2436. destination[prop].push(clonedValue);
  2437. }
  2438. }
  2439. } else {
  2440. destination[prop] = sourceValue.slice(0);
  2441. }
  2442. }
  2443. } else {
  2444. destination[prop] = cloneValue(sourceValue, destination);
  2445. }
  2446. } else {
  2447. destination[prop] = sourceValue;
  2448. }
  2449. }
  2450. };
  2451. Tools.IsEmpty = function (obj) {
  2452. for (var i in obj) {
  2453. return false;
  2454. }
  2455. return true;
  2456. };
  2457. Tools.RegisterTopRootEvents = function (events) {
  2458. for (var index = 0; index < events.length; index++) {
  2459. var event = events[index];
  2460. window.addEventListener(event.name, event.handler, false);
  2461. try {
  2462. if (window.parent) {
  2463. window.parent.addEventListener(event.name, event.handler, false);
  2464. }
  2465. } catch (e) {
  2466. // Silently fails...
  2467. }
  2468. }
  2469. };
  2470. Tools.UnregisterTopRootEvents = function (events) {
  2471. for (var index = 0; index < events.length; index++) {
  2472. var event = events[index];
  2473. window.removeEventListener(event.name, event.handler);
  2474. try {
  2475. if (window.parent) {
  2476. window.parent.removeEventListener(event.name, event.handler);
  2477. }
  2478. } catch (e) {
  2479. // Silently fails...
  2480. }
  2481. }
  2482. };
  2483. Tools.CreateScreenshot = function (engine, camera, size) {
  2484. var width;
  2485. var height;
  2486. var scene = camera.getScene();
  2487. var previousCamera = null;
  2488. if (scene.activeCamera !== camera) {
  2489. previousCamera = scene.activeCamera;
  2490. scene.activeCamera = camera;
  2491. }
  2492. //If a precision value is specified
  2493. if (size.precision) {
  2494. width = Math.round(engine.getRenderWidth() * size.precision);
  2495. height = Math.round(width / engine.getAspectRatio(camera));
  2496. size = { width: width, height: height };
  2497. } else if (size.width && size.height) {
  2498. width = size.width;
  2499. height = size.height;
  2500. } else if (size.width && !size.height) {
  2501. width = size.width;
  2502. height = Math.round(width / engine.getAspectRatio(camera));
  2503. size = { width: width, height: height };
  2504. } else if (size.height && !size.width) {
  2505. height = size.height;
  2506. width = Math.round(height * engine.getAspectRatio(camera));
  2507. size = { width: width, height: height };
  2508. } else if (!isNaN(size)) {
  2509. height = size;
  2510. width = size;
  2511. } else {
  2512. Tools.Error("Invalid 'size' parameter !");
  2513. return;
  2514. }
  2515. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2516. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2517. texture.renderList = engine.scenes[0].meshes;
  2518. texture.onAfterRender = function () {
  2519. // Read the contents of the framebuffer
  2520. var numberOfChannelsByLine = width * 4;
  2521. var halfHeight = height / 2;
  2522. //Reading datas from WebGL
  2523. var data = engine.readPixels(0, 0, width, height);
  2524. for (var i = 0; i < halfHeight; i++) {
  2525. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2526. var currentCell = j + i * numberOfChannelsByLine;
  2527. var targetLine = height - i - 1;
  2528. var targetCell = j + targetLine * numberOfChannelsByLine;
  2529. var temp = data[currentCell];
  2530. data[currentCell] = data[targetCell];
  2531. data[targetCell] = temp;
  2532. }
  2533. }
  2534. // Create a 2D canvas to store the result
  2535. if (!screenshotCanvas) {
  2536. screenshotCanvas = document.createElement('canvas');
  2537. }
  2538. screenshotCanvas.width = width;
  2539. screenshotCanvas.height = height;
  2540. var context = screenshotCanvas.getContext('2d');
  2541. // Copy the pixels to a 2D canvas
  2542. var imageData = context.createImageData(width, height);
  2543. imageData.data.set(data);
  2544. context.putImageData(imageData, 0, 0);
  2545. var base64Image = screenshotCanvas.toDataURL();
  2546. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2547. if (("download" in document.createElement("a"))) {
  2548. var a = window.document.createElement("a");
  2549. a.href = base64Image;
  2550. var date = new Date();
  2551. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2552. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2553. window.document.body.appendChild(a);
  2554. a.addEventListener("click", function () {
  2555. a.parentElement.removeChild(a);
  2556. });
  2557. a.click();
  2558. //Or opening a new tab with the image if it is not possible to automatically start download.
  2559. } else {
  2560. var newWindow = window.open("");
  2561. var img = newWindow.document.createElement("img");
  2562. img.src = base64Image;
  2563. newWindow.document.body.appendChild(img);
  2564. }
  2565. };
  2566. texture.render(true);
  2567. texture.dispose();
  2568. if (previousCamera) {
  2569. scene.activeCamera = previousCamera;
  2570. }
  2571. };
  2572. // XHR response validator for local file scenario
  2573. Tools.ValidateXHRData = function (xhr, dataType) {
  2574. if (typeof dataType === "undefined") { dataType = 7; }
  2575. try {
  2576. if (dataType & 1) {
  2577. if (xhr.responseText && xhr.responseText.length > 0) {
  2578. return true;
  2579. } else if (dataType === 1) {
  2580. return false;
  2581. }
  2582. }
  2583. if (dataType & 2) {
  2584. // Check header width and height since there is no "TGA" magic number
  2585. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2586. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2587. return true;
  2588. } else if (dataType === 2) {
  2589. return false;
  2590. }
  2591. }
  2592. if (dataType & 4) {
  2593. // Check for the "DDS" magic number
  2594. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2595. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2596. return true;
  2597. } else {
  2598. return false;
  2599. }
  2600. }
  2601. } catch (e) {
  2602. // Global protection
  2603. }
  2604. return false;
  2605. };
  2606. Object.defineProperty(Tools, "NoneLogLevel", {
  2607. get: function () {
  2608. return Tools._NoneLogLevel;
  2609. },
  2610. enumerable: true,
  2611. configurable: true
  2612. });
  2613. Object.defineProperty(Tools, "MessageLogLevel", {
  2614. get: function () {
  2615. return Tools._MessageLogLevel;
  2616. },
  2617. enumerable: true,
  2618. configurable: true
  2619. });
  2620. Object.defineProperty(Tools, "WarningLogLevel", {
  2621. get: function () {
  2622. return Tools._WarningLogLevel;
  2623. },
  2624. enumerable: true,
  2625. configurable: true
  2626. });
  2627. Object.defineProperty(Tools, "ErrorLogLevel", {
  2628. get: function () {
  2629. return Tools._ErrorLogLevel;
  2630. },
  2631. enumerable: true,
  2632. configurable: true
  2633. });
  2634. Object.defineProperty(Tools, "AllLogLevel", {
  2635. get: function () {
  2636. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2637. },
  2638. enumerable: true,
  2639. configurable: true
  2640. });
  2641. Tools._AddLogEntry = function (entry) {
  2642. Tools._LogCache = entry + Tools._LogCache;
  2643. if (Tools.OnNewCacheEntry) {
  2644. Tools.OnNewCacheEntry(entry);
  2645. }
  2646. };
  2647. Tools._FormatMessage = function (message) {
  2648. var padStr = function (i) {
  2649. return (i < 10) ? "0" + i : "" + i;
  2650. };
  2651. var date = new Date();
  2652. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2653. };
  2654. Tools._LogDisabled = function (message) {
  2655. // nothing to do
  2656. };
  2657. Tools._LogEnabled = function (message) {
  2658. var formattedMessage = Tools._FormatMessage(message);
  2659. console.log("BJS - " + formattedMessage);
  2660. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2661. Tools._AddLogEntry(entry);
  2662. };
  2663. Tools._WarnDisabled = function (message) {
  2664. // nothing to do
  2665. };
  2666. Tools._WarnEnabled = function (message) {
  2667. var formattedMessage = Tools._FormatMessage(message);
  2668. console.warn("BJS - " + formattedMessage);
  2669. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2670. Tools._AddLogEntry(entry);
  2671. };
  2672. Tools._ErrorDisabled = function (message) {
  2673. // nothing to do
  2674. };
  2675. Tools._ErrorEnabled = function (message) {
  2676. var formattedMessage = Tools._FormatMessage(message);
  2677. console.error("BJS - " + formattedMessage);
  2678. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2679. Tools._AddLogEntry(entry);
  2680. };
  2681. Object.defineProperty(Tools, "LogCache", {
  2682. get: function () {
  2683. return Tools._LogCache;
  2684. },
  2685. enumerable: true,
  2686. configurable: true
  2687. });
  2688. Object.defineProperty(Tools, "LogLevels", {
  2689. set: function (level) {
  2690. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2691. Tools.Log = Tools._LogEnabled;
  2692. } else {
  2693. Tools.Log = Tools._LogDisabled;
  2694. }
  2695. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2696. Tools.Warn = Tools._WarnEnabled;
  2697. } else {
  2698. Tools.Warn = Tools._WarnDisabled;
  2699. }
  2700. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2701. Tools.Error = Tools._ErrorEnabled;
  2702. } else {
  2703. Tools.Error = Tools._ErrorDisabled;
  2704. }
  2705. },
  2706. enumerable: true,
  2707. configurable: true
  2708. });
  2709. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2710. get: function () {
  2711. return Tools._PerformanceNoneLogLevel;
  2712. },
  2713. enumerable: true,
  2714. configurable: true
  2715. });
  2716. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2717. get: function () {
  2718. return Tools._PerformanceUserMarkLogLevel;
  2719. },
  2720. enumerable: true,
  2721. configurable: true
  2722. });
  2723. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2724. get: function () {
  2725. return Tools._PerformanceConsoleLogLevel;
  2726. },
  2727. enumerable: true,
  2728. configurable: true
  2729. });
  2730. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2731. set: function (level) {
  2732. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2733. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2734. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2735. return;
  2736. }
  2737. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2738. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2739. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2740. return;
  2741. }
  2742. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2743. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2744. },
  2745. enumerable: true,
  2746. configurable: true
  2747. });
  2748. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2749. };
  2750. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2751. };
  2752. Tools._StartUserMark = function (counterName, condition) {
  2753. if (typeof condition === "undefined") { condition = true; }
  2754. if (!condition || !Tools._performance.mark) {
  2755. return;
  2756. }
  2757. Tools._performance.mark(counterName + "-Begin");
  2758. };
  2759. Tools._EndUserMark = function (counterName, condition) {
  2760. if (typeof condition === "undefined") { condition = true; }
  2761. if (!condition || !Tools._performance.mark) {
  2762. return;
  2763. }
  2764. Tools._performance.mark(counterName + "-End");
  2765. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2766. };
  2767. Tools._StartPerformanceConsole = function (counterName, condition) {
  2768. if (typeof condition === "undefined") { condition = true; }
  2769. if (!condition) {
  2770. return;
  2771. }
  2772. Tools._StartUserMark(counterName, condition);
  2773. if (console.time) {
  2774. console.time(counterName);
  2775. }
  2776. };
  2777. Tools._EndPerformanceConsole = function (counterName, condition) {
  2778. if (typeof condition === "undefined") { condition = true; }
  2779. if (!condition) {
  2780. return;
  2781. }
  2782. Tools._EndUserMark(counterName, condition);
  2783. if (console.time) {
  2784. console.timeEnd(counterName);
  2785. }
  2786. };
  2787. Object.defineProperty(Tools, "Now", {
  2788. get: function () {
  2789. if (window.performance && window.performance.now) {
  2790. return window.performance.now();
  2791. }
  2792. return new Date().getTime();
  2793. },
  2794. enumerable: true,
  2795. configurable: true
  2796. });
  2797. // Deprecated
  2798. Tools.GetFps = function () {
  2799. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2800. return 0;
  2801. };
  2802. Tools.BaseUrl = "";
  2803. Tools.GetExponantOfTwo = function (value, max) {
  2804. var count = 1;
  2805. do {
  2806. count *= 2;
  2807. } while(count < value);
  2808. if (count > max)
  2809. count = max;
  2810. return count;
  2811. };
  2812. Tools._NoneLogLevel = 0;
  2813. Tools._MessageLogLevel = 1;
  2814. Tools._WarningLogLevel = 2;
  2815. Tools._ErrorLogLevel = 4;
  2816. Tools._LogCache = "";
  2817. Tools.Log = Tools._LogEnabled;
  2818. Tools.Warn = Tools._WarnEnabled;
  2819. Tools.Error = Tools._ErrorEnabled;
  2820. Tools._PerformanceNoneLogLevel = 0;
  2821. Tools._PerformanceUserMarkLogLevel = 1;
  2822. Tools._PerformanceConsoleLogLevel = 2;
  2823. Tools._performance = window.performance;
  2824. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2825. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2826. return Tools;
  2827. })();
  2828. BABYLON.Tools = Tools;
  2829. })(BABYLON || (BABYLON = {}));
  2830. //# sourceMappingURL=babylon.tools.js.map
  2831. var BABYLON;
  2832. (function (BABYLON) {
  2833. var _DepthCullingState = (function () {
  2834. function _DepthCullingState() {
  2835. this._isDepthTestDirty = false;
  2836. this._isDepthMaskDirty = false;
  2837. this._isDepthFuncDirty = false;
  2838. this._isCullFaceDirty = false;
  2839. this._isCullDirty = false;
  2840. }
  2841. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2842. get: function () {
  2843. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2844. },
  2845. enumerable: true,
  2846. configurable: true
  2847. });
  2848. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2849. get: function () {
  2850. return this._cullFace;
  2851. },
  2852. set: function (value) {
  2853. if (this._cullFace === value) {
  2854. return;
  2855. }
  2856. this._cullFace = value;
  2857. this._isCullFaceDirty = true;
  2858. },
  2859. enumerable: true,
  2860. configurable: true
  2861. });
  2862. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2863. get: function () {
  2864. return this._cull;
  2865. },
  2866. set: function (value) {
  2867. if (this._cull === value) {
  2868. return;
  2869. }
  2870. this._cull = value;
  2871. this._isCullDirty = true;
  2872. },
  2873. enumerable: true,
  2874. configurable: true
  2875. });
  2876. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2877. get: function () {
  2878. return this._depthFunc;
  2879. },
  2880. set: function (value) {
  2881. if (this._depthFunc === value) {
  2882. return;
  2883. }
  2884. this._depthFunc = value;
  2885. this._isDepthFuncDirty = true;
  2886. },
  2887. enumerable: true,
  2888. configurable: true
  2889. });
  2890. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2891. get: function () {
  2892. return this._depthMask;
  2893. },
  2894. set: function (value) {
  2895. if (this._depthMask === value) {
  2896. return;
  2897. }
  2898. this._depthMask = value;
  2899. this._isDepthMaskDirty = true;
  2900. },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2905. get: function () {
  2906. return this._depthTest;
  2907. },
  2908. set: function (value) {
  2909. if (this._depthTest === value) {
  2910. return;
  2911. }
  2912. this._depthTest = value;
  2913. this._isDepthTestDirty = true;
  2914. },
  2915. enumerable: true,
  2916. configurable: true
  2917. });
  2918. _DepthCullingState.prototype.reset = function () {
  2919. this._depthMask = true;
  2920. this._depthTest = true;
  2921. this._depthFunc = null;
  2922. this._cull = null;
  2923. this._cullFace = null;
  2924. this._isDepthTestDirty = true;
  2925. this._isDepthMaskDirty = true;
  2926. this._isDepthFuncDirty = false;
  2927. this._isCullFaceDirty = false;
  2928. this._isCullDirty = false;
  2929. };
  2930. _DepthCullingState.prototype.apply = function (gl) {
  2931. if (!this.isDirty) {
  2932. return;
  2933. }
  2934. // Cull
  2935. if (this._isCullDirty) {
  2936. if (this.cull === true) {
  2937. gl.enable(gl.CULL_FACE);
  2938. } else if (this.cull === false) {
  2939. gl.disable(gl.CULL_FACE);
  2940. }
  2941. this._isCullDirty = false;
  2942. }
  2943. // Cull face
  2944. if (this._isCullFaceDirty) {
  2945. gl.cullFace(this.cullFace);
  2946. this._isCullFaceDirty = false;
  2947. }
  2948. // Depth mask
  2949. if (this._isDepthMaskDirty) {
  2950. gl.depthMask(this.depthMask);
  2951. this._isDepthMaskDirty = false;
  2952. }
  2953. // Depth test
  2954. if (this._isDepthTestDirty) {
  2955. if (this.depthTest === true) {
  2956. gl.enable(gl.DEPTH_TEST);
  2957. } else if (this.depthTest === false) {
  2958. gl.disable(gl.DEPTH_TEST);
  2959. }
  2960. this._isDepthTestDirty = false;
  2961. }
  2962. // Depth func
  2963. if (this._isDepthFuncDirty) {
  2964. gl.depthFunc(this.depthFunc);
  2965. this._isDepthFuncDirty = false;
  2966. }
  2967. };
  2968. return _DepthCullingState;
  2969. })();
  2970. BABYLON._DepthCullingState = _DepthCullingState;
  2971. var _AlphaState = (function () {
  2972. function _AlphaState() {
  2973. this._isAlphaBlendDirty = false;
  2974. this._isBlendFunctionParametersDirty = false;
  2975. this._alphaBlend = false;
  2976. this._blendFunctionParameters = new Array(4);
  2977. }
  2978. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2979. get: function () {
  2980. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2981. },
  2982. enumerable: true,
  2983. configurable: true
  2984. });
  2985. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2986. get: function () {
  2987. return this._alphaBlend;
  2988. },
  2989. set: function (value) {
  2990. if (this._alphaBlend === value) {
  2991. return;
  2992. }
  2993. this._alphaBlend = value;
  2994. this._isAlphaBlendDirty = true;
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3000. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3001. return;
  3002. }
  3003. this._blendFunctionParameters[0] = value0;
  3004. this._blendFunctionParameters[1] = value1;
  3005. this._blendFunctionParameters[2] = value2;
  3006. this._blendFunctionParameters[3] = value3;
  3007. this._isBlendFunctionParametersDirty = true;
  3008. };
  3009. _AlphaState.prototype.reset = function () {
  3010. this._alphaBlend = false;
  3011. this._blendFunctionParameters[0] = null;
  3012. this._blendFunctionParameters[1] = null;
  3013. this._blendFunctionParameters[2] = null;
  3014. this._blendFunctionParameters[3] = null;
  3015. this._isAlphaBlendDirty = true;
  3016. this._isBlendFunctionParametersDirty = false;
  3017. };
  3018. _AlphaState.prototype.apply = function (gl) {
  3019. if (!this.isDirty) {
  3020. return;
  3021. }
  3022. // Alpha blend
  3023. if (this._isAlphaBlendDirty) {
  3024. if (this._alphaBlend === true) {
  3025. gl.enable(gl.BLEND);
  3026. } else if (this._alphaBlend === false) {
  3027. gl.disable(gl.BLEND);
  3028. }
  3029. this._isAlphaBlendDirty = false;
  3030. }
  3031. // Alpha function
  3032. if (this._isBlendFunctionParametersDirty) {
  3033. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3034. this._isBlendFunctionParametersDirty = false;
  3035. }
  3036. };
  3037. return _AlphaState;
  3038. })();
  3039. BABYLON._AlphaState = _AlphaState;
  3040. var compileShader = function (gl, source, type, defines) {
  3041. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3042. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3043. gl.compileShader(shader);
  3044. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3045. throw new Error(gl.getShaderInfoLog(shader));
  3046. }
  3047. return shader;
  3048. };
  3049. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3050. var magFilter = gl.NEAREST;
  3051. var minFilter = gl.NEAREST;
  3052. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3053. magFilter = gl.LINEAR;
  3054. if (generateMipMaps) {
  3055. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3056. } else {
  3057. minFilter = gl.LINEAR;
  3058. }
  3059. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3060. magFilter = gl.LINEAR;
  3061. if (generateMipMaps) {
  3062. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3063. } else {
  3064. minFilter = gl.LINEAR;
  3065. }
  3066. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3067. magFilter = gl.NEAREST;
  3068. if (generateMipMaps) {
  3069. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3070. } else {
  3071. minFilter = gl.NEAREST;
  3072. }
  3073. }
  3074. return {
  3075. min: minFilter,
  3076. mag: magFilter
  3077. };
  3078. };
  3079. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3080. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3081. var engine = scene.getEngine();
  3082. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3083. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3084. gl.bindTexture(gl.TEXTURE_2D, texture);
  3085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3086. processFunction(potWidth, potHeight);
  3087. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3090. if (!noMipmap && !isCompressed) {
  3091. gl.generateMipmap(gl.TEXTURE_2D);
  3092. }
  3093. gl.bindTexture(gl.TEXTURE_2D, null);
  3094. engine._activeTexturesCache = [];
  3095. texture._baseWidth = width;
  3096. texture._baseHeight = height;
  3097. texture._width = potWidth;
  3098. texture._height = potHeight;
  3099. texture.isReady = true;
  3100. scene._removePendingData(texture);
  3101. };
  3102. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3103. var img;
  3104. var onload = function () {
  3105. loadedImages[index] = img;
  3106. loadedImages._internalCount++;
  3107. scene._removePendingData(img);
  3108. if (loadedImages._internalCount == 6) {
  3109. onfinish(loadedImages);
  3110. }
  3111. };
  3112. var onerror = function () {
  3113. scene._removePendingData(img);
  3114. };
  3115. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3116. scene._addPendingData(img);
  3117. };
  3118. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3119. var loadedImages = [];
  3120. loadedImages._internalCount = 0;
  3121. for (var index = 0; index < 6; index++) {
  3122. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3123. }
  3124. };
  3125. var EngineCapabilities = (function () {
  3126. function EngineCapabilities() {
  3127. }
  3128. return EngineCapabilities;
  3129. })();
  3130. BABYLON.EngineCapabilities = EngineCapabilities;
  3131. var Engine = (function () {
  3132. function Engine(canvas, antialias, options) {
  3133. var _this = this;
  3134. // Public members
  3135. this.isFullscreen = false;
  3136. this.isPointerLock = false;
  3137. this.cullBackFaces = true;
  3138. this.renderEvenInBackground = true;
  3139. this.scenes = new Array();
  3140. this._windowIsBackground = false;
  3141. this._loadingDivBackgroundColor = "black";
  3142. this._drawCalls = 0;
  3143. this._renderingQueueLaunched = false;
  3144. this._activeRenderLoops = [];
  3145. // FPS
  3146. this.fpsRange = 60;
  3147. this.previousFramesDuration = [];
  3148. this.fps = 60;
  3149. this.deltaTime = 0;
  3150. // States
  3151. this._depthCullingState = new _DepthCullingState();
  3152. this._alphaState = new _AlphaState();
  3153. this._alphaMode = Engine.ALPHA_DISABLE;
  3154. // Cache
  3155. this._loadedTexturesCache = new Array();
  3156. this._activeTexturesCache = new Array();
  3157. this._compiledEffects = {};
  3158. this._uintIndicesCurrentlySet = false;
  3159. this._renderingCanvas = canvas;
  3160. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3161. options = options || {};
  3162. options.antialias = antialias;
  3163. try {
  3164. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3165. } catch (e) {
  3166. throw new Error("WebGL not supported");
  3167. }
  3168. if (!this._gl) {
  3169. throw new Error("WebGL not supported");
  3170. }
  3171. this._onBlur = function () {
  3172. _this._windowIsBackground = true;
  3173. };
  3174. this._onFocus = function () {
  3175. _this._windowIsBackground = false;
  3176. };
  3177. window.addEventListener("blur", this._onBlur);
  3178. window.addEventListener("focus", this._onFocus);
  3179. // Textures
  3180. this._workingCanvas = document.createElement("canvas");
  3181. this._workingContext = this._workingCanvas.getContext("2d");
  3182. // Viewport
  3183. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3184. this.resize();
  3185. // Caps
  3186. this._caps = new EngineCapabilities();
  3187. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3188. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3189. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3190. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3191. // Extensions
  3192. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3193. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3194. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3195. 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');
  3196. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3197. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3198. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3199. // Depth buffer
  3200. this.setDepthBuffer(true);
  3201. this.setDepthFunctionToLessOrEqual();
  3202. this.setDepthWrite(true);
  3203. // Fullscreen
  3204. this._onFullscreenChange = function () {
  3205. if (document.fullscreen !== undefined) {
  3206. _this.isFullscreen = document.fullscreen;
  3207. } else if (document.mozFullScreen !== undefined) {
  3208. _this.isFullscreen = document.mozFullScreen;
  3209. } else if (document.webkitIsFullScreen !== undefined) {
  3210. _this.isFullscreen = document.webkitIsFullScreen;
  3211. } else if (document.msIsFullScreen !== undefined) {
  3212. _this.isFullscreen = document.msIsFullScreen;
  3213. }
  3214. // Pointer lock
  3215. if (_this.isFullscreen && _this._pointerLockRequested) {
  3216. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3217. if (canvas.requestPointerLock) {
  3218. canvas.requestPointerLock();
  3219. }
  3220. }
  3221. };
  3222. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3223. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3224. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3225. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3226. // Pointer lock
  3227. this._onPointerLockChange = function () {
  3228. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3229. };
  3230. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3231. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3232. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3233. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3234. this._audioEngine = new BABYLON.AudioEngine();
  3235. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3236. }
  3237. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3238. get: function () {
  3239. return Engine._ALPHA_DISABLE;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. Object.defineProperty(Engine, "ALPHA_ADD", {
  3245. get: function () {
  3246. return Engine._ALPHA_ADD;
  3247. },
  3248. enumerable: true,
  3249. configurable: true
  3250. });
  3251. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3252. get: function () {
  3253. return Engine._ALPHA_COMBINE;
  3254. },
  3255. enumerable: true,
  3256. configurable: true
  3257. });
  3258. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3259. get: function () {
  3260. return Engine._DELAYLOADSTATE_NONE;
  3261. },
  3262. enumerable: true,
  3263. configurable: true
  3264. });
  3265. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3266. get: function () {
  3267. return Engine._DELAYLOADSTATE_LOADED;
  3268. },
  3269. enumerable: true,
  3270. configurable: true
  3271. });
  3272. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3273. get: function () {
  3274. return Engine._DELAYLOADSTATE_LOADING;
  3275. },
  3276. enumerable: true,
  3277. configurable: true
  3278. });
  3279. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3280. get: function () {
  3281. return Engine._DELAYLOADSTATE_NOTLOADED;
  3282. },
  3283. enumerable: true,
  3284. configurable: true
  3285. });
  3286. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3287. get: function () {
  3288. return Engine._TEXTUREFORMAT_ALPHA;
  3289. },
  3290. enumerable: true,
  3291. configurable: true
  3292. });
  3293. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3294. get: function () {
  3295. return Engine._TEXTUREFORMAT_LUMINANCE;
  3296. },
  3297. enumerable: true,
  3298. configurable: true
  3299. });
  3300. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3301. get: function () {
  3302. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3303. },
  3304. enumerable: true,
  3305. configurable: true
  3306. });
  3307. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3308. get: function () {
  3309. return Engine._TEXTUREFORMAT_RGB;
  3310. },
  3311. enumerable: true,
  3312. configurable: true
  3313. });
  3314. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3315. get: function () {
  3316. return Engine._TEXTUREFORMAT_RGBA;
  3317. },
  3318. enumerable: true,
  3319. configurable: true
  3320. });
  3321. Object.defineProperty(Engine, "Version", {
  3322. get: function () {
  3323. return "2.0.0";
  3324. },
  3325. enumerable: true,
  3326. configurable: true
  3327. });
  3328. Engine.prototype.getAudioEngine = function () {
  3329. return this._audioEngine;
  3330. };
  3331. Engine.prototype.getAspectRatio = function (camera) {
  3332. var viewport = camera.viewport;
  3333. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3334. };
  3335. Engine.prototype.getRenderWidth = function () {
  3336. if (this._currentRenderTarget) {
  3337. return this._currentRenderTarget._width;
  3338. }
  3339. return this._renderingCanvas.width;
  3340. };
  3341. Engine.prototype.getRenderHeight = function () {
  3342. if (this._currentRenderTarget) {
  3343. return this._currentRenderTarget._height;
  3344. }
  3345. return this._renderingCanvas.height;
  3346. };
  3347. Engine.prototype.getRenderingCanvas = function () {
  3348. return this._renderingCanvas;
  3349. };
  3350. Engine.prototype.getRenderingCanvasClientRect = function () {
  3351. return this._renderingCanvas.getBoundingClientRect();
  3352. };
  3353. Engine.prototype.setHardwareScalingLevel = function (level) {
  3354. this._hardwareScalingLevel = level;
  3355. this.resize();
  3356. };
  3357. Engine.prototype.getHardwareScalingLevel = function () {
  3358. return this._hardwareScalingLevel;
  3359. };
  3360. Engine.prototype.getLoadedTexturesCache = function () {
  3361. return this._loadedTexturesCache;
  3362. };
  3363. Engine.prototype.getCaps = function () {
  3364. return this._caps;
  3365. };
  3366. Object.defineProperty(Engine.prototype, "drawCalls", {
  3367. get: function () {
  3368. return this._drawCalls;
  3369. },
  3370. enumerable: true,
  3371. configurable: true
  3372. });
  3373. // Methods
  3374. Engine.prototype.resetDrawCalls = function () {
  3375. this._drawCalls = 0;
  3376. };
  3377. Engine.prototype.setDepthFunctionToGreater = function () {
  3378. this._depthCullingState.depthFunc = this._gl.GREATER;
  3379. };
  3380. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3381. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3382. };
  3383. Engine.prototype.setDepthFunctionToLess = function () {
  3384. this._depthCullingState.depthFunc = this._gl.LESS;
  3385. };
  3386. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3387. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3388. };
  3389. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3390. if (!renderFunction) {
  3391. this._activeRenderLoops = [];
  3392. return;
  3393. }
  3394. var index = this._activeRenderLoops.indexOf(renderFunction);
  3395. if (index >= 0) {
  3396. this._activeRenderLoops.splice(index, 1);
  3397. }
  3398. };
  3399. Engine.prototype._renderLoop = function () {
  3400. var _this = this;
  3401. var shouldRender = true;
  3402. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3403. shouldRender = false;
  3404. }
  3405. if (shouldRender) {
  3406. // Start new frame
  3407. this.beginFrame();
  3408. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3409. var renderFunction = this._activeRenderLoops[index];
  3410. renderFunction();
  3411. }
  3412. // Present
  3413. this.endFrame();
  3414. }
  3415. if (this._activeRenderLoops.length > 0) {
  3416. // Register new frame
  3417. BABYLON.Tools.QueueNewFrame(function () {
  3418. _this._renderLoop();
  3419. });
  3420. } else {
  3421. this._renderingQueueLaunched = false;
  3422. }
  3423. };
  3424. Engine.prototype.runRenderLoop = function (renderFunction) {
  3425. var _this = this;
  3426. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3427. return;
  3428. }
  3429. this._activeRenderLoops.push(renderFunction);
  3430. if (!this._renderingQueueLaunched) {
  3431. this._renderingQueueLaunched = true;
  3432. BABYLON.Tools.QueueNewFrame(function () {
  3433. _this._renderLoop();
  3434. });
  3435. }
  3436. };
  3437. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3438. if (this.isFullscreen) {
  3439. BABYLON.Tools.ExitFullscreen();
  3440. } else {
  3441. this._pointerLockRequested = requestPointerLock;
  3442. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3443. }
  3444. };
  3445. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3446. this.applyStates();
  3447. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3448. if (this._depthCullingState.depthMask) {
  3449. this._gl.clearDepth(1.0);
  3450. }
  3451. var mode = 0;
  3452. if (backBuffer)
  3453. mode |= this._gl.COLOR_BUFFER_BIT;
  3454. if (depthStencil && this._depthCullingState.depthMask)
  3455. mode |= this._gl.DEPTH_BUFFER_BIT;
  3456. this._gl.clear(mode);
  3457. };
  3458. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3459. var width = requiredWidth || this._renderingCanvas.width;
  3460. var height = requiredHeight || this._renderingCanvas.height;
  3461. var x = viewport.x || 0;
  3462. var y = viewport.y || 0;
  3463. this._cachedViewport = viewport;
  3464. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3465. };
  3466. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3467. this._cachedViewport = null;
  3468. this._gl.viewport(x, y, width, height);
  3469. };
  3470. Engine.prototype.beginFrame = function () {
  3471. this._measureFps();
  3472. };
  3473. Engine.prototype.endFrame = function () {
  3474. this.flushFramebuffer();
  3475. };
  3476. Engine.prototype.resize = function () {
  3477. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3478. };
  3479. Engine.prototype.setSize = function (width, height) {
  3480. this._renderingCanvas.width = width;
  3481. this._renderingCanvas.height = height;
  3482. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3483. };
  3484. Engine.prototype.bindFramebuffer = function (texture) {
  3485. this._currentRenderTarget = texture;
  3486. var gl = this._gl;
  3487. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3488. this._gl.viewport(0, 0, texture._width, texture._height);
  3489. this.wipeCaches();
  3490. };
  3491. Engine.prototype.unBindFramebuffer = function (texture) {
  3492. this._currentRenderTarget = null;
  3493. if (texture.generateMipMaps) {
  3494. var gl = this._gl;
  3495. gl.bindTexture(gl.TEXTURE_2D, texture);
  3496. gl.generateMipmap(gl.TEXTURE_2D);
  3497. gl.bindTexture(gl.TEXTURE_2D, null);
  3498. }
  3499. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3500. };
  3501. Engine.prototype.flushFramebuffer = function () {
  3502. // this._gl.flush();
  3503. };
  3504. Engine.prototype.restoreDefaultFramebuffer = function () {
  3505. this._currentRenderTarget = null;
  3506. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3507. this.setViewport(this._cachedViewport);
  3508. this.wipeCaches();
  3509. };
  3510. // VBOs
  3511. Engine.prototype._resetVertexBufferBinding = function () {
  3512. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3513. this._cachedVertexBuffers = null;
  3514. };
  3515. Engine.prototype.createVertexBuffer = function (vertices) {
  3516. var vbo = this._gl.createBuffer();
  3517. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3518. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3519. this._resetVertexBufferBinding();
  3520. vbo.references = 1;
  3521. return vbo;
  3522. };
  3523. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3524. var vbo = this._gl.createBuffer();
  3525. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3526. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3527. this._resetVertexBufferBinding();
  3528. vbo.references = 1;
  3529. return vbo;
  3530. };
  3531. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3532. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3533. if (offset === undefined) {
  3534. offset = 0;
  3535. }
  3536. if (vertices instanceof Float32Array) {
  3537. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3538. } else {
  3539. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3540. }
  3541. this._resetVertexBufferBinding();
  3542. };
  3543. Engine.prototype._resetIndexBufferBinding = function () {
  3544. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3545. this._cachedIndexBuffer = null;
  3546. };
  3547. Engine.prototype.createIndexBuffer = function (indices) {
  3548. var vbo = this._gl.createBuffer();
  3549. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3550. // Check for 32 bits indices
  3551. var arrayBuffer;
  3552. var need32Bits = false;
  3553. if (this._caps.uintIndices) {
  3554. for (var index = 0; index < indices.length; index++) {
  3555. if (indices[index] > 65535) {
  3556. need32Bits = true;
  3557. break;
  3558. }
  3559. }
  3560. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3561. } else {
  3562. arrayBuffer = new Uint16Array(indices);
  3563. }
  3564. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3565. this._resetIndexBufferBinding();
  3566. vbo.references = 1;
  3567. vbo.is32Bits = need32Bits;
  3568. return vbo;
  3569. };
  3570. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3571. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3572. this._cachedVertexBuffers = vertexBuffer;
  3573. this._cachedEffectForVertexBuffers = effect;
  3574. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3575. var offset = 0;
  3576. for (var index = 0; index < vertexDeclaration.length; index++) {
  3577. var order = effect.getAttributeLocation(index);
  3578. if (order >= 0) {
  3579. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3580. }
  3581. offset += vertexDeclaration[index] * 4;
  3582. }
  3583. }
  3584. if (this._cachedIndexBuffer !== indexBuffer) {
  3585. this._cachedIndexBuffer = indexBuffer;
  3586. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3587. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3588. }
  3589. };
  3590. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3591. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3592. this._cachedVertexBuffers = vertexBuffers;
  3593. this._cachedEffectForVertexBuffers = effect;
  3594. var attributes = effect.getAttributesNames();
  3595. for (var index = 0; index < attributes.length; index++) {
  3596. var order = effect.getAttributeLocation(index);
  3597. if (order >= 0) {
  3598. var vertexBuffer = vertexBuffers[attributes[index]];
  3599. if (!vertexBuffer) {
  3600. continue;
  3601. }
  3602. var stride = vertexBuffer.getStrideSize();
  3603. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3604. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3605. }
  3606. }
  3607. }
  3608. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3609. this._cachedIndexBuffer = indexBuffer;
  3610. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3611. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3612. }
  3613. };
  3614. Engine.prototype._releaseBuffer = function (buffer) {
  3615. buffer.references--;
  3616. if (buffer.references === 0) {
  3617. this._gl.deleteBuffer(buffer);
  3618. return true;
  3619. }
  3620. return false;
  3621. };
  3622. Engine.prototype.createInstancesBuffer = function (capacity) {
  3623. var buffer = this._gl.createBuffer();
  3624. buffer.capacity = capacity;
  3625. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3626. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3627. return buffer;
  3628. };
  3629. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3630. this._gl.deleteBuffer(buffer);
  3631. };
  3632. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3633. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3634. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3635. for (var index = 0; index < 4; index++) {
  3636. var offsetLocation = offsetLocations[index];
  3637. this._gl.enableVertexAttribArray(offsetLocation);
  3638. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3639. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3640. }
  3641. };
  3642. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3643. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3644. for (var index = 0; index < 4; index++) {
  3645. var offsetLocation = offsetLocations[index];
  3646. this._gl.disableVertexAttribArray(offsetLocation);
  3647. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3648. }
  3649. };
  3650. Engine.prototype.applyStates = function () {
  3651. this._depthCullingState.apply(this._gl);
  3652. this._alphaState.apply(this._gl);
  3653. };
  3654. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3655. // Apply states
  3656. this.applyStates();
  3657. this._drawCalls++;
  3658. // Render
  3659. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3660. if (instancesCount) {
  3661. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3662. return;
  3663. }
  3664. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3665. };
  3666. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3667. // Apply states
  3668. this.applyStates();
  3669. this._drawCalls++;
  3670. if (instancesCount) {
  3671. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3672. return;
  3673. }
  3674. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3675. };
  3676. // Shaders
  3677. Engine.prototype._releaseEffect = function (effect) {
  3678. if (this._compiledEffects[effect._key]) {
  3679. delete this._compiledEffects[effect._key];
  3680. if (effect.getProgram()) {
  3681. this._gl.deleteProgram(effect.getProgram());
  3682. }
  3683. }
  3684. };
  3685. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3686. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3687. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3688. var name = vertex + "+" + fragment + "@" + defines;
  3689. if (this._compiledEffects[name]) {
  3690. return this._compiledEffects[name];
  3691. }
  3692. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3693. effect._key = name;
  3694. this._compiledEffects[name] = effect;
  3695. return effect;
  3696. };
  3697. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3698. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3699. if (typeof samplers === "undefined") { samplers = []; }
  3700. if (typeof defines === "undefined") { defines = ""; }
  3701. return this.createEffect({
  3702. vertex: "particles",
  3703. fragmentElement: fragmentName
  3704. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3705. };
  3706. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3707. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3708. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3709. var shaderProgram = this._gl.createProgram();
  3710. this._gl.attachShader(shaderProgram, vertexShader);
  3711. this._gl.attachShader(shaderProgram, fragmentShader);
  3712. this._gl.linkProgram(shaderProgram);
  3713. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3714. if (!linked) {
  3715. var error = this._gl.getProgramInfoLog(shaderProgram);
  3716. if (error) {
  3717. throw new Error(error);
  3718. }
  3719. }
  3720. this._gl.deleteShader(vertexShader);
  3721. this._gl.deleteShader(fragmentShader);
  3722. return shaderProgram;
  3723. };
  3724. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3725. var results = [];
  3726. for (var index = 0; index < uniformsNames.length; index++) {
  3727. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3728. }
  3729. return results;
  3730. };
  3731. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3732. var results = [];
  3733. for (var index = 0; index < attributesNames.length; index++) {
  3734. try {
  3735. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3736. } catch (e) {
  3737. results.push(-1);
  3738. }
  3739. }
  3740. return results;
  3741. };
  3742. Engine.prototype.enableEffect = function (effect) {
  3743. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3744. if (effect && effect.onBind) {
  3745. effect.onBind(effect);
  3746. }
  3747. return;
  3748. }
  3749. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3750. // Use program
  3751. this._gl.useProgram(effect.getProgram());
  3752. for (var i in this._vertexAttribArrays) {
  3753. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3754. continue;
  3755. }
  3756. this._vertexAttribArrays[i] = false;
  3757. this._gl.disableVertexAttribArray(i);
  3758. }
  3759. var attributesCount = effect.getAttributesCount();
  3760. for (var index = 0; index < attributesCount; index++) {
  3761. // Attributes
  3762. var order = effect.getAttributeLocation(index);
  3763. if (order >= 0) {
  3764. this._vertexAttribArrays[order] = true;
  3765. this._gl.enableVertexAttribArray(order);
  3766. }
  3767. }
  3768. this._currentEffect = effect;
  3769. if (effect.onBind) {
  3770. effect.onBind(effect);
  3771. }
  3772. };
  3773. Engine.prototype.setArray = function (uniform, array) {
  3774. if (!uniform)
  3775. return;
  3776. this._gl.uniform1fv(uniform, array);
  3777. };
  3778. Engine.prototype.setMatrices = function (uniform, matrices) {
  3779. if (!uniform)
  3780. return;
  3781. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3782. };
  3783. Engine.prototype.setMatrix = function (uniform, matrix) {
  3784. if (!uniform)
  3785. return;
  3786. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3787. };
  3788. Engine.prototype.setFloat = function (uniform, value) {
  3789. if (!uniform)
  3790. return;
  3791. this._gl.uniform1f(uniform, value);
  3792. };
  3793. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3794. if (!uniform)
  3795. return;
  3796. this._gl.uniform2f(uniform, x, y);
  3797. };
  3798. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3799. if (!uniform)
  3800. return;
  3801. this._gl.uniform3f(uniform, x, y, z);
  3802. };
  3803. Engine.prototype.setBool = function (uniform, bool) {
  3804. if (!uniform)
  3805. return;
  3806. this._gl.uniform1i(uniform, bool);
  3807. };
  3808. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3809. if (!uniform)
  3810. return;
  3811. this._gl.uniform4f(uniform, x, y, z, w);
  3812. };
  3813. Engine.prototype.setColor3 = function (uniform, color3) {
  3814. if (!uniform)
  3815. return;
  3816. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3817. };
  3818. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3819. if (!uniform)
  3820. return;
  3821. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3822. };
  3823. // States
  3824. Engine.prototype.setState = function (culling, force) {
  3825. // Culling
  3826. if (this._depthCullingState.cull !== culling || force) {
  3827. if (culling) {
  3828. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3829. this._depthCullingState.cull = true;
  3830. } else {
  3831. this._depthCullingState.cull = false;
  3832. }
  3833. }
  3834. };
  3835. Engine.prototype.setDepthBuffer = function (enable) {
  3836. this._depthCullingState.depthTest = enable;
  3837. };
  3838. Engine.prototype.getDepthWrite = function () {
  3839. return this._depthCullingState.depthMask;
  3840. };
  3841. Engine.prototype.setDepthWrite = function (enable) {
  3842. this._depthCullingState.depthMask = enable;
  3843. };
  3844. Engine.prototype.setColorWrite = function (enable) {
  3845. this._gl.colorMask(enable, enable, enable, enable);
  3846. };
  3847. Engine.prototype.setAlphaMode = function (mode) {
  3848. switch (mode) {
  3849. case BABYLON.Engine.ALPHA_DISABLE:
  3850. this.setDepthWrite(true);
  3851. this._alphaState.alphaBlend = false;
  3852. break;
  3853. case BABYLON.Engine.ALPHA_COMBINE:
  3854. this.setDepthWrite(false);
  3855. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3856. this._alphaState.alphaBlend = true;
  3857. break;
  3858. case BABYLON.Engine.ALPHA_ADD:
  3859. this.setDepthWrite(false);
  3860. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3861. this._alphaState.alphaBlend = true;
  3862. break;
  3863. }
  3864. this._alphaMode = mode;
  3865. };
  3866. Engine.prototype.getAlphaMode = function () {
  3867. return this._alphaMode;
  3868. };
  3869. Engine.prototype.setAlphaTesting = function (enable) {
  3870. this._alphaTest = enable;
  3871. };
  3872. Engine.prototype.getAlphaTesting = function () {
  3873. return this._alphaTest;
  3874. };
  3875. // Textures
  3876. Engine.prototype.wipeCaches = function () {
  3877. this._activeTexturesCache = [];
  3878. this._currentEffect = null;
  3879. this._depthCullingState.reset();
  3880. this._alphaState.reset();
  3881. this._cachedVertexBuffers = null;
  3882. this._cachedIndexBuffer = null;
  3883. this._cachedEffectForVertexBuffers = null;
  3884. };
  3885. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3886. var gl = this._gl;
  3887. gl.bindTexture(gl.TEXTURE_2D, texture);
  3888. var magFilter = gl.NEAREST;
  3889. var minFilter = gl.NEAREST;
  3890. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3891. magFilter = gl.LINEAR;
  3892. minFilter = gl.LINEAR;
  3893. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3894. magFilter = gl.LINEAR;
  3895. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3896. }
  3897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3899. gl.bindTexture(gl.TEXTURE_2D, null);
  3900. };
  3901. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3902. var _this = this;
  3903. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3904. if (typeof onLoad === "undefined") { onLoad = null; }
  3905. if (typeof onError === "undefined") { onError = null; }
  3906. if (typeof buffer === "undefined") { buffer = null; }
  3907. var texture = this._gl.createTexture();
  3908. var extension;
  3909. var fromData = false;
  3910. if (url.substr(0, 5) === "data:") {
  3911. fromData = true;
  3912. }
  3913. if (!fromData)
  3914. extension = url.substr(url.length - 4, 4).toLowerCase();
  3915. else {
  3916. var oldUrl = url;
  3917. fromData = oldUrl.split(':');
  3918. url = oldUrl;
  3919. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3920. }
  3921. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3922. var isTGA = (extension === ".tga");
  3923. scene._addPendingData(texture);
  3924. texture.url = url;
  3925. texture.noMipmap = noMipmap;
  3926. texture.references = 1;
  3927. this._loadedTexturesCache.push(texture);
  3928. var onerror = function () {
  3929. scene._removePendingData(texture);
  3930. if (onError) {
  3931. onError();
  3932. }
  3933. };
  3934. if (isTGA) {
  3935. var callback = function (arrayBuffer) {
  3936. var data = new Uint8Array(arrayBuffer);
  3937. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3938. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3939. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3940. if (onLoad) {
  3941. onLoad();
  3942. }
  3943. }, samplingMode);
  3944. };
  3945. if (!(fromData instanceof Array))
  3946. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3947. callback(arrayBuffer);
  3948. }, onerror, scene.database, true);
  3949. else
  3950. callback(buffer);
  3951. } else if (isDDS) {
  3952. callback = function (data) {
  3953. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3954. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3955. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3956. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3957. if (onLoad) {
  3958. onLoad();
  3959. }
  3960. }, samplingMode);
  3961. };
  3962. if (!(fromData instanceof Array))
  3963. BABYLON.Tools.LoadFile(url, function (data) {
  3964. callback(data);
  3965. }, onerror, scene.database, true);
  3966. else
  3967. callback(buffer);
  3968. } else {
  3969. var onload = function (img) {
  3970. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3971. var isPot = (img.width == potWidth && img.height == potHeight);
  3972. if (!isPot) {
  3973. _this._workingCanvas.width = potWidth;
  3974. _this._workingCanvas.height = potHeight;
  3975. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3976. }
  3977. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3978. if (onLoad) {
  3979. onLoad();
  3980. }
  3981. }, samplingMode);
  3982. };
  3983. if (!(fromData instanceof Array))
  3984. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3985. else
  3986. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3987. }
  3988. return texture;
  3989. };
  3990. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  3991. var texture = this._gl.createTexture();
  3992. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3993. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3994. // Format
  3995. var internalFormat = this._gl.RGBA;
  3996. switch (format) {
  3997. case Engine.TEXTUREFORMAT_ALPHA:
  3998. internalFormat = this._gl.ALPHA;
  3999. break;
  4000. case Engine.TEXTUREFORMAT_LUMINANCE:
  4001. internalFormat = this._gl.LUMINANCE;
  4002. break;
  4003. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4004. internalFormat = this._gl.LUMINANCE_ALPHA;
  4005. break;
  4006. case Engine.TEXTUREFORMAT_RGB:
  4007. internalFormat = this._gl.RGB;
  4008. break;
  4009. case Engine.TEXTUREFORMAT_RGBA:
  4010. internalFormat = this._gl.RGBA;
  4011. break;
  4012. }
  4013. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4014. if (generateMipMaps) {
  4015. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4016. }
  4017. // Filters
  4018. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4019. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4020. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4021. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4022. this._activeTexturesCache = [];
  4023. texture._baseWidth = width;
  4024. texture._baseHeight = height;
  4025. texture._width = width;
  4026. texture._height = height;
  4027. texture.isReady = true;
  4028. texture.references = 1;
  4029. this._loadedTexturesCache.push(texture);
  4030. return texture;
  4031. };
  4032. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4033. var texture = this._gl.createTexture();
  4034. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4035. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4036. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4037. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4038. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4039. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4040. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4041. this._activeTexturesCache = [];
  4042. texture._baseWidth = width;
  4043. texture._baseHeight = height;
  4044. texture._width = width;
  4045. texture._height = height;
  4046. texture.isReady = false;
  4047. texture.generateMipMaps = generateMipMaps;
  4048. texture.references = 1;
  4049. this._loadedTexturesCache.push(texture);
  4050. return texture;
  4051. };
  4052. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4053. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4054. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4055. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4056. if (texture.generateMipMaps) {
  4057. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4058. }
  4059. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4060. this._activeTexturesCache = [];
  4061. texture.isReady = true;
  4062. };
  4063. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4064. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4065. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4066. // Scale the video if it is a NPOT using the current working canvas
  4067. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4068. if (!texture._workingCanvas) {
  4069. texture._workingCanvas = document.createElement("canvas");
  4070. texture._workingContext = texture._workingCanvas.getContext("2d");
  4071. texture._workingCanvas.width = texture._width;
  4072. texture._workingCanvas.height = texture._height;
  4073. }
  4074. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4075. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4076. } else {
  4077. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4078. }
  4079. if (texture.generateMipMaps) {
  4080. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4081. }
  4082. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4083. this._activeTexturesCache = [];
  4084. texture.isReady = true;
  4085. };
  4086. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4087. // old version had a "generateMipMaps" arg instead of options.
  4088. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4089. // in the same way, generateDepthBuffer is defaulted to true
  4090. var generateMipMaps = false;
  4091. var generateDepthBuffer = true;
  4092. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4093. if (options !== undefined) {
  4094. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4095. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4096. if (options.samplingMode !== undefined) {
  4097. samplingMode = options.samplingMode;
  4098. }
  4099. }
  4100. var gl = this._gl;
  4101. var texture = gl.createTexture();
  4102. gl.bindTexture(gl.TEXTURE_2D, texture);
  4103. var width = size.width || size;
  4104. var height = size.height || size;
  4105. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4110. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4111. var depthBuffer;
  4112. // Create the depth buffer
  4113. if (generateDepthBuffer) {
  4114. depthBuffer = gl.createRenderbuffer();
  4115. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4116. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4117. }
  4118. // Create the framebuffer
  4119. var framebuffer = gl.createFramebuffer();
  4120. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4122. if (generateDepthBuffer) {
  4123. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4124. }
  4125. // Unbind
  4126. gl.bindTexture(gl.TEXTURE_2D, null);
  4127. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4128. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4129. texture._framebuffer = framebuffer;
  4130. if (generateDepthBuffer) {
  4131. texture._depthBuffer = depthBuffer;
  4132. }
  4133. texture._width = width;
  4134. texture._height = height;
  4135. texture.isReady = true;
  4136. texture.generateMipMaps = generateMipMaps;
  4137. texture.references = 1;
  4138. this._activeTexturesCache = [];
  4139. this._loadedTexturesCache.push(texture);
  4140. return texture;
  4141. };
  4142. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4143. var _this = this;
  4144. var gl = this._gl;
  4145. var texture = gl.createTexture();
  4146. texture.isCube = true;
  4147. texture.url = rootUrl;
  4148. texture.references = 1;
  4149. this._loadedTexturesCache.push(texture);
  4150. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4151. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4152. if (isDDS) {
  4153. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4154. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4155. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4156. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4157. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4158. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4159. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4160. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4161. }
  4162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4166. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4167. _this._activeTexturesCache = [];
  4168. texture._width = info.width;
  4169. texture._height = info.height;
  4170. texture.isReady = true;
  4171. }, null, null, true);
  4172. } else {
  4173. cascadeLoad(rootUrl, scene, function (imgs) {
  4174. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4175. var height = width;
  4176. _this._workingCanvas.width = width;
  4177. _this._workingCanvas.height = height;
  4178. var faces = [
  4179. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4180. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4181. ];
  4182. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4183. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4184. for (var index = 0; index < faces.length; index++) {
  4185. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4186. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4187. }
  4188. if (!noMipmap) {
  4189. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4190. }
  4191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4193. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4195. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4196. _this._activeTexturesCache = [];
  4197. texture._width = width;
  4198. texture._height = height;
  4199. texture.isReady = true;
  4200. }, extensions);
  4201. }
  4202. return texture;
  4203. };
  4204. Engine.prototype._releaseTexture = function (texture) {
  4205. var gl = this._gl;
  4206. if (texture._framebuffer) {
  4207. gl.deleteFramebuffer(texture._framebuffer);
  4208. }
  4209. if (texture._depthBuffer) {
  4210. gl.deleteRenderbuffer(texture._depthBuffer);
  4211. }
  4212. gl.deleteTexture(texture);
  4213. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4214. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4215. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4216. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4217. this._activeTexturesCache[channel] = null;
  4218. }
  4219. var index = this._loadedTexturesCache.indexOf(texture);
  4220. if (index !== -1) {
  4221. this._loadedTexturesCache.splice(index, 1);
  4222. }
  4223. };
  4224. Engine.prototype.bindSamplers = function (effect) {
  4225. this._gl.useProgram(effect.getProgram());
  4226. var samplers = effect.getSamplers();
  4227. for (var index = 0; index < samplers.length; index++) {
  4228. var uniform = effect.getUniform(samplers[index]);
  4229. this._gl.uniform1i(uniform, index);
  4230. }
  4231. this._currentEffect = null;
  4232. };
  4233. Engine.prototype._bindTexture = function (channel, texture) {
  4234. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4235. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4236. this._activeTexturesCache[channel] = null;
  4237. };
  4238. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4239. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4240. };
  4241. Engine.prototype.setTexture = function (channel, texture) {
  4242. if (channel < 0) {
  4243. return;
  4244. }
  4245. // Not ready?
  4246. if (!texture || !texture.isReady()) {
  4247. if (this._activeTexturesCache[channel] != null) {
  4248. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4249. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4250. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4251. this._activeTexturesCache[channel] = null;
  4252. }
  4253. return;
  4254. }
  4255. // Video
  4256. if (texture instanceof BABYLON.VideoTexture) {
  4257. if (texture.update()) {
  4258. this._activeTexturesCache[channel] = null;
  4259. }
  4260. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4261. texture.delayLoad();
  4262. return;
  4263. }
  4264. if (this._activeTexturesCache[channel] == texture) {
  4265. return;
  4266. }
  4267. this._activeTexturesCache[channel] = texture;
  4268. var internalTexture = texture.getInternalTexture();
  4269. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4270. if (internalTexture.isCube) {
  4271. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4272. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4273. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4274. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4275. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4276. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4277. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4278. }
  4279. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4280. } else {
  4281. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4282. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4283. internalTexture._cachedWrapU = texture.wrapU;
  4284. switch (texture.wrapU) {
  4285. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4287. break;
  4288. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4290. break;
  4291. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4292. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4293. break;
  4294. }
  4295. }
  4296. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4297. internalTexture._cachedWrapV = texture.wrapV;
  4298. switch (texture.wrapV) {
  4299. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4301. break;
  4302. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4304. break;
  4305. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4307. break;
  4308. }
  4309. }
  4310. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4311. }
  4312. };
  4313. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4314. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4315. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4316. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4317. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4318. }
  4319. };
  4320. Engine.prototype.readPixels = function (x, y, width, height) {
  4321. var data = new Uint8Array(height * width * 4);
  4322. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4323. return data;
  4324. };
  4325. // Dispose
  4326. Engine.prototype.dispose = function () {
  4327. this.hideLoadingUI();
  4328. this.stopRenderLoop();
  4329. while (this.scenes.length) {
  4330. this.scenes[0].dispose();
  4331. }
  4332. for (var name in this._compiledEffects) {
  4333. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4334. }
  4335. for (var i in this._vertexAttribArrays) {
  4336. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4337. continue;
  4338. }
  4339. this._gl.disableVertexAttribArray(i);
  4340. }
  4341. // Events
  4342. window.removeEventListener("blur", this._onBlur);
  4343. window.removeEventListener("focus", this._onFocus);
  4344. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4345. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4346. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4347. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4348. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4349. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4350. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4351. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4352. };
  4353. // Loading screen
  4354. Engine.prototype.displayLoadingUI = function () {
  4355. var _this = this;
  4356. this._loadingDiv = document.createElement("div");
  4357. this._loadingDiv.style.opacity = "0";
  4358. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4359. // Loading text
  4360. this._loadingTextDiv = document.createElement("div");
  4361. this._loadingTextDiv.style.position = "absolute";
  4362. this._loadingTextDiv.style.left = "0";
  4363. this._loadingTextDiv.style.top = "50%";
  4364. this._loadingTextDiv.style.marginTop = "80px";
  4365. this._loadingTextDiv.style.width = "100%";
  4366. this._loadingTextDiv.style.height = "20px";
  4367. this._loadingTextDiv.style.fontFamily = "Arial";
  4368. this._loadingTextDiv.style.fontSize = "14px";
  4369. this._loadingTextDiv.style.color = "white";
  4370. this._loadingTextDiv.style.textAlign = "center";
  4371. this._loadingTextDiv.innerHTML = "Loading";
  4372. this._loadingDiv.appendChild(this._loadingTextDiv);
  4373. // Loading img
  4374. var imgBack = new Image();
  4375. 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==";
  4376. imgBack.style.position = "absolute";
  4377. imgBack.style.left = "50%";
  4378. imgBack.style.top = "50%";
  4379. imgBack.style.marginLeft = "-50px";
  4380. imgBack.style.marginTop = "-50px";
  4381. imgBack.style.transition = "transform 1.0s ease";
  4382. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4383. var deg = 360;
  4384. var onTransitionEnd = function () {
  4385. deg += 360;
  4386. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4387. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4388. };
  4389. imgBack.addEventListener("transitionend", onTransitionEnd);
  4390. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4391. this._loadingDiv.appendChild(imgBack);
  4392. // front image
  4393. var imgFront = new Image();
  4394. 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=";
  4395. imgFront.style.position = "absolute";
  4396. imgFront.style.left = "50%";
  4397. imgFront.style.top = "50%";
  4398. imgFront.style.marginLeft = "-50px";
  4399. imgFront.style.marginTop = "-50px";
  4400. this._loadingDiv.appendChild(imgFront);
  4401. // Resize
  4402. this._resizeLoadingUI = function () {
  4403. var canvasRect = _this.getRenderingCanvasClientRect();
  4404. _this._loadingDiv.style.position = "absolute";
  4405. _this._loadingDiv.style.left = canvasRect.left + "px";
  4406. _this._loadingDiv.style.top = canvasRect.top + "px";
  4407. _this._loadingDiv.style.width = canvasRect.width + "px";
  4408. _this._loadingDiv.style.height = canvasRect.height + "px";
  4409. };
  4410. this._resizeLoadingUI();
  4411. window.addEventListener("resize", this._resizeLoadingUI);
  4412. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4413. document.body.appendChild(this._loadingDiv);
  4414. setTimeout(function () {
  4415. _this._loadingDiv.style.opacity = "1";
  4416. imgBack.style.transform = "rotateZ(360deg)";
  4417. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4418. }, 0);
  4419. };
  4420. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4421. set: function (text) {
  4422. if (!this._loadingDiv) {
  4423. return;
  4424. }
  4425. this._loadingTextDiv.innerHTML = text;
  4426. },
  4427. enumerable: true,
  4428. configurable: true
  4429. });
  4430. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4431. get: function () {
  4432. return this._loadingDivBackgroundColor;
  4433. },
  4434. set: function (color) {
  4435. this._loadingDivBackgroundColor = color;
  4436. if (!this._loadingDiv) {
  4437. return;
  4438. }
  4439. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4440. },
  4441. enumerable: true,
  4442. configurable: true
  4443. });
  4444. Engine.prototype.hideLoadingUI = function () {
  4445. var _this = this;
  4446. if (!this._loadingDiv) {
  4447. return;
  4448. }
  4449. var onTransitionEnd = function () {
  4450. if (!_this._loadingDiv) {
  4451. return;
  4452. }
  4453. document.body.removeChild(_this._loadingDiv);
  4454. window.removeEventListener("resize", _this._resizeLoadingUI);
  4455. _this._loadingDiv = null;
  4456. };
  4457. this._loadingDiv.style.opacity = "0";
  4458. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4459. };
  4460. // FPS
  4461. Engine.prototype.getFps = function () {
  4462. return this.fps;
  4463. };
  4464. Engine.prototype.getDeltaTime = function () {
  4465. return this.deltaTime;
  4466. };
  4467. Engine.prototype._measureFps = function () {
  4468. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4469. var length = this.previousFramesDuration.length;
  4470. if (length >= 2) {
  4471. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4472. }
  4473. if (length >= this.fpsRange) {
  4474. if (length > this.fpsRange) {
  4475. this.previousFramesDuration.splice(0, 1);
  4476. length = this.previousFramesDuration.length;
  4477. }
  4478. var sum = 0;
  4479. for (var id = 0; id < length - 1; id++) {
  4480. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4481. }
  4482. this.fps = 1000.0 / (sum / (length - 1));
  4483. }
  4484. };
  4485. // Statics
  4486. Engine.isSupported = function () {
  4487. try {
  4488. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4489. if (navigator.isCocoonJS) {
  4490. return true;
  4491. }
  4492. var tempcanvas = document.createElement("canvas");
  4493. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4494. return gl != null && !!window.WebGLRenderingContext;
  4495. } catch (e) {
  4496. return false;
  4497. }
  4498. };
  4499. Engine._ALPHA_DISABLE = 0;
  4500. Engine._ALPHA_ADD = 1;
  4501. Engine._ALPHA_COMBINE = 2;
  4502. Engine._DELAYLOADSTATE_NONE = 0;
  4503. Engine._DELAYLOADSTATE_LOADED = 1;
  4504. Engine._DELAYLOADSTATE_LOADING = 2;
  4505. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4506. Engine._TEXTUREFORMAT_ALPHA = 0;
  4507. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4508. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4509. Engine._TEXTUREFORMAT_RGB = 4;
  4510. Engine._TEXTUREFORMAT_RGBA = 4;
  4511. Engine.Epsilon = 0.001;
  4512. Engine.CollisionsEpsilon = 0.001;
  4513. Engine.ShadersRepository = "Babylon/Shaders/";
  4514. return Engine;
  4515. })();
  4516. BABYLON.Engine = Engine;
  4517. })(BABYLON || (BABYLON = {}));
  4518. //# sourceMappingURL=babylon.engine.js.map
  4519. var BABYLON;
  4520. (function (BABYLON) {
  4521. var Node = (function () {
  4522. function Node(name, scene) {
  4523. this.state = "";
  4524. this.animations = new Array();
  4525. this._childrenFlag = -1;
  4526. this._isEnabled = true;
  4527. this._isReady = true;
  4528. this._currentRenderId = -1;
  4529. this.name = name;
  4530. this.id = name;
  4531. this._scene = scene;
  4532. this._initCache();
  4533. }
  4534. Node.prototype.getScene = function () {
  4535. return this._scene;
  4536. };
  4537. Node.prototype.getEngine = function () {
  4538. return this._scene.getEngine();
  4539. };
  4540. // override it in derived class
  4541. Node.prototype.getWorldMatrix = function () {
  4542. return BABYLON.Matrix.Identity();
  4543. };
  4544. // override it in derived class if you add new variables to the cache
  4545. // and call the parent class method
  4546. Node.prototype._initCache = function () {
  4547. this._cache = {};
  4548. this._cache.parent = undefined;
  4549. };
  4550. Node.prototype.updateCache = function (force) {
  4551. if (!force && this.isSynchronized())
  4552. return;
  4553. this._cache.parent = this.parent;
  4554. this._updateCache();
  4555. };
  4556. // override it in derived class if you add new variables to the cache
  4557. // and call the parent class method if !ignoreParentClass
  4558. Node.prototype._updateCache = function (ignoreParentClass) {
  4559. };
  4560. // override it in derived class if you add new variables to the cache
  4561. Node.prototype._isSynchronized = function () {
  4562. return true;
  4563. };
  4564. Node.prototype.isSynchronizedWithParent = function () {
  4565. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4566. };
  4567. Node.prototype.isSynchronized = function (updateCache) {
  4568. var check = this.hasNewParent();
  4569. check = check || !this.isSynchronizedWithParent();
  4570. check = check || !this._isSynchronized();
  4571. if (updateCache)
  4572. this.updateCache(true);
  4573. return !check;
  4574. };
  4575. Node.prototype.hasNewParent = function (update) {
  4576. if (this._cache.parent === this.parent)
  4577. return false;
  4578. if (update)
  4579. this._cache.parent = this.parent;
  4580. return true;
  4581. };
  4582. Node.prototype.isReady = function () {
  4583. return this._isReady;
  4584. };
  4585. Node.prototype.isEnabled = function () {
  4586. if (!this._isEnabled) {
  4587. return false;
  4588. }
  4589. if (this.parent) {
  4590. return this.parent.isEnabled();
  4591. }
  4592. return true;
  4593. };
  4594. Node.prototype.setEnabled = function (value) {
  4595. this._isEnabled = value;
  4596. };
  4597. Node.prototype.isDescendantOf = function (ancestor) {
  4598. if (this.parent) {
  4599. if (this.parent === ancestor) {
  4600. return true;
  4601. }
  4602. return this.parent.isDescendantOf(ancestor);
  4603. }
  4604. return false;
  4605. };
  4606. Node.prototype._getDescendants = function (list, results) {
  4607. for (var index = 0; index < list.length; index++) {
  4608. var item = list[index];
  4609. if (item.isDescendantOf(this)) {
  4610. results.push(item);
  4611. }
  4612. }
  4613. };
  4614. Node.prototype.getDescendants = function () {
  4615. var results = [];
  4616. this._getDescendants(this._scene.meshes, results);
  4617. this._getDescendants(this._scene.lights, results);
  4618. this._getDescendants(this._scene.cameras, results);
  4619. return results;
  4620. };
  4621. Node.prototype._setReady = function (state) {
  4622. if (state == this._isReady) {
  4623. return;
  4624. }
  4625. if (!state) {
  4626. this._isReady = false;
  4627. return;
  4628. }
  4629. this._isReady = true;
  4630. if (this.onReady) {
  4631. this.onReady(this);
  4632. }
  4633. };
  4634. return Node;
  4635. })();
  4636. BABYLON.Node = Node;
  4637. })(BABYLON || (BABYLON = {}));
  4638. //# sourceMappingURL=babylon.node.js.map
  4639. var BABYLON;
  4640. (function (BABYLON) {
  4641. var BoundingSphere = (function () {
  4642. function BoundingSphere(minimum, maximum) {
  4643. this.minimum = minimum;
  4644. this.maximum = maximum;
  4645. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4646. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4647. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4648. this.radius = distance * 0.5;
  4649. this.centerWorld = BABYLON.Vector3.Zero();
  4650. this._update(BABYLON.Matrix.Identity());
  4651. }
  4652. // Methods
  4653. BoundingSphere.prototype._update = function (world) {
  4654. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4655. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4656. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4657. };
  4658. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4659. for (var i = 0; i < 6; i++) {
  4660. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4661. return false;
  4662. }
  4663. return true;
  4664. };
  4665. BoundingSphere.prototype.intersectsPoint = function (point) {
  4666. var x = this.centerWorld.x - point.x;
  4667. var y = this.centerWorld.y - point.y;
  4668. var z = this.centerWorld.z - point.z;
  4669. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4670. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4671. return false;
  4672. return true;
  4673. };
  4674. // Statics
  4675. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4676. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4677. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4678. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4679. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4680. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4681. return false;
  4682. return true;
  4683. };
  4684. return BoundingSphere;
  4685. })();
  4686. BABYLON.BoundingSphere = BoundingSphere;
  4687. })(BABYLON || (BABYLON = {}));
  4688. //# sourceMappingURL=babylon.boundingSphere.js.map
  4689. var BABYLON;
  4690. (function (BABYLON) {
  4691. var BoundingBox = (function () {
  4692. function BoundingBox(minimum, maximum) {
  4693. this.minimum = minimum;
  4694. this.maximum = maximum;
  4695. this.vectors = new Array();
  4696. this.vectorsWorld = new Array();
  4697. // Bounding vectors
  4698. this.vectors.push(this.minimum.clone());
  4699. this.vectors.push(this.maximum.clone());
  4700. this.vectors.push(this.minimum.clone());
  4701. this.vectors[2].x = this.maximum.x;
  4702. this.vectors.push(this.minimum.clone());
  4703. this.vectors[3].y = this.maximum.y;
  4704. this.vectors.push(this.minimum.clone());
  4705. this.vectors[4].z = this.maximum.z;
  4706. this.vectors.push(this.maximum.clone());
  4707. this.vectors[5].z = this.minimum.z;
  4708. this.vectors.push(this.maximum.clone());
  4709. this.vectors[6].x = this.minimum.x;
  4710. this.vectors.push(this.maximum.clone());
  4711. this.vectors[7].y = this.minimum.y;
  4712. // OBB
  4713. this.center = this.maximum.add(this.minimum).scale(0.5);
  4714. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4715. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4716. for (var index = 0; index < this.vectors.length; index++) {
  4717. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4718. }
  4719. this.minimumWorld = BABYLON.Vector3.Zero();
  4720. this.maximumWorld = BABYLON.Vector3.Zero();
  4721. this._update(BABYLON.Matrix.Identity());
  4722. }
  4723. // Methods
  4724. BoundingBox.prototype.getWorldMatrix = function () {
  4725. return this._worldMatrix;
  4726. };
  4727. BoundingBox.prototype._update = function (world) {
  4728. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4729. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4730. for (var index = 0; index < this.vectors.length; index++) {
  4731. var v = this.vectorsWorld[index];
  4732. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4733. if (v.x < this.minimumWorld.x)
  4734. this.minimumWorld.x = v.x;
  4735. if (v.y < this.minimumWorld.y)
  4736. this.minimumWorld.y = v.y;
  4737. if (v.z < this.minimumWorld.z)
  4738. this.minimumWorld.z = v.z;
  4739. if (v.x > this.maximumWorld.x)
  4740. this.maximumWorld.x = v.x;
  4741. if (v.y > this.maximumWorld.y)
  4742. this.maximumWorld.y = v.y;
  4743. if (v.z > this.maximumWorld.z)
  4744. this.maximumWorld.z = v.z;
  4745. }
  4746. // OBB
  4747. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4748. this.center.scaleInPlace(0.5);
  4749. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4750. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4751. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4752. this._worldMatrix = world;
  4753. };
  4754. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4755. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4756. };
  4757. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4758. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4759. };
  4760. BoundingBox.prototype.intersectsPoint = function (point) {
  4761. var delta = BABYLON.Engine.Epsilon;
  4762. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4763. return false;
  4764. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4765. return false;
  4766. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4767. return false;
  4768. return true;
  4769. };
  4770. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4771. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4772. };
  4773. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4774. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4775. return false;
  4776. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4777. return false;
  4778. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4779. return false;
  4780. return true;
  4781. };
  4782. // Statics
  4783. BoundingBox.Intersects = function (box0, box1) {
  4784. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4785. return false;
  4786. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4787. return false;
  4788. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4789. return false;
  4790. return true;
  4791. };
  4792. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4793. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4794. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4795. return (num <= (sphereRadius * sphereRadius));
  4796. };
  4797. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4798. for (var p = 0; p < 6; p++) {
  4799. for (var i = 0; i < 8; i++) {
  4800. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4801. return false;
  4802. }
  4803. }
  4804. }
  4805. return true;
  4806. };
  4807. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4808. for (var p = 0; p < 6; p++) {
  4809. var inCount = 8;
  4810. for (var i = 0; i < 8; i++) {
  4811. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4812. --inCount;
  4813. } else {
  4814. break;
  4815. }
  4816. }
  4817. if (inCount == 0)
  4818. return false;
  4819. }
  4820. return true;
  4821. };
  4822. return BoundingBox;
  4823. })();
  4824. BABYLON.BoundingBox = BoundingBox;
  4825. })(BABYLON || (BABYLON = {}));
  4826. //# sourceMappingURL=babylon.boundingBox.js.map
  4827. var BABYLON;
  4828. (function (BABYLON) {
  4829. var computeBoxExtents = function (axis, box) {
  4830. var p = BABYLON.Vector3.Dot(box.center, axis);
  4831. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4832. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4833. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4834. var r = r0 + r1 + r2;
  4835. return {
  4836. min: p - r,
  4837. max: p + r
  4838. };
  4839. };
  4840. var extentsOverlap = function (min0, max0, min1, max1) {
  4841. return !(min0 > max1 || min1 > max0);
  4842. };
  4843. var axisOverlap = function (axis, box0, box1) {
  4844. var result0 = computeBoxExtents(axis, box0);
  4845. var result1 = computeBoxExtents(axis, box1);
  4846. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4847. };
  4848. var BoundingInfo = (function () {
  4849. function BoundingInfo(minimum, maximum) {
  4850. this.minimum = minimum;
  4851. this.maximum = maximum;
  4852. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4853. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4854. }
  4855. // Methods
  4856. BoundingInfo.prototype._update = function (world) {
  4857. this.boundingBox._update(world);
  4858. this.boundingSphere._update(world);
  4859. };
  4860. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4861. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4862. return false;
  4863. return this.boundingBox.isInFrustum(frustumPlanes);
  4864. };
  4865. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4866. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4867. };
  4868. BoundingInfo.prototype._checkCollision = function (collider) {
  4869. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4870. };
  4871. BoundingInfo.prototype.intersectsPoint = function (point) {
  4872. if (!this.boundingSphere.centerWorld) {
  4873. return false;
  4874. }
  4875. if (!this.boundingSphere.intersectsPoint(point)) {
  4876. return false;
  4877. }
  4878. if (!this.boundingBox.intersectsPoint(point)) {
  4879. return false;
  4880. }
  4881. return true;
  4882. };
  4883. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4884. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4885. return false;
  4886. }
  4887. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4888. return false;
  4889. }
  4890. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4891. return false;
  4892. }
  4893. if (!precise) {
  4894. return true;
  4895. }
  4896. var box0 = this.boundingBox;
  4897. var box1 = boundingInfo.boundingBox;
  4898. if (!axisOverlap(box0.directions[0], box0, box1))
  4899. return false;
  4900. if (!axisOverlap(box0.directions[1], box0, box1))
  4901. return false;
  4902. if (!axisOverlap(box0.directions[2], box0, box1))
  4903. return false;
  4904. if (!axisOverlap(box1.directions[0], box0, box1))
  4905. return false;
  4906. if (!axisOverlap(box1.directions[1], box0, box1))
  4907. return false;
  4908. if (!axisOverlap(box1.directions[2], box0, box1))
  4909. return false;
  4910. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4911. return false;
  4912. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4913. return false;
  4914. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4915. return false;
  4916. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4917. return false;
  4918. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4919. return false;
  4920. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4921. return false;
  4922. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4923. return false;
  4924. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4925. return false;
  4926. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4927. return false;
  4928. return true;
  4929. };
  4930. return BoundingInfo;
  4931. })();
  4932. BABYLON.BoundingInfo = BoundingInfo;
  4933. })(BABYLON || (BABYLON = {}));
  4934. //# sourceMappingURL=babylon.boundingInfo.js.map
  4935. var BABYLON;
  4936. (function (BABYLON) {
  4937. var Light = (function (_super) {
  4938. __extends(Light, _super);
  4939. function Light(name, scene) {
  4940. _super.call(this, name, scene);
  4941. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4942. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4943. this.intensity = 1.0;
  4944. this.range = Number.MAX_VALUE;
  4945. this.includedOnlyMeshes = new Array();
  4946. this.excludedMeshes = new Array();
  4947. this._excludedMeshesIds = new Array();
  4948. this._includedOnlyMeshesIds = new Array();
  4949. scene.lights.push(this);
  4950. }
  4951. Light.prototype.getShadowGenerator = function () {
  4952. return this._shadowGenerator;
  4953. };
  4954. Light.prototype.getAbsolutePosition = function () {
  4955. return BABYLON.Vector3.Zero();
  4956. };
  4957. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4958. };
  4959. Light.prototype._getWorldMatrix = function () {
  4960. return BABYLON.Matrix.Identity();
  4961. };
  4962. Light.prototype.canAffectMesh = function (mesh) {
  4963. if (!mesh) {
  4964. return true;
  4965. }
  4966. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4967. return false;
  4968. }
  4969. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4970. return false;
  4971. }
  4972. return true;
  4973. };
  4974. Light.prototype.getWorldMatrix = function () {
  4975. this._currentRenderId = this.getScene().getRenderId();
  4976. var worldMatrix = this._getWorldMatrix();
  4977. if (this.parent && this.parent.getWorldMatrix) {
  4978. if (!this._parentedWorldMatrix) {
  4979. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4980. }
  4981. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4982. return this._parentedWorldMatrix;
  4983. }
  4984. return worldMatrix;
  4985. };
  4986. Light.prototype.dispose = function () {
  4987. if (this._shadowGenerator) {
  4988. this._shadowGenerator.dispose();
  4989. this._shadowGenerator = null;
  4990. }
  4991. // Remove from scene
  4992. var index = this.getScene().lights.indexOf(this);
  4993. this.getScene().lights.splice(index, 1);
  4994. };
  4995. return Light;
  4996. })(BABYLON.Node);
  4997. BABYLON.Light = Light;
  4998. })(BABYLON || (BABYLON = {}));
  4999. //# sourceMappingURL=babylon.light.js.map
  5000. var BABYLON;
  5001. (function (BABYLON) {
  5002. var PointLight = (function (_super) {
  5003. __extends(PointLight, _super);
  5004. function PointLight(name, position, scene) {
  5005. _super.call(this, name, scene);
  5006. this.position = position;
  5007. }
  5008. PointLight.prototype.getAbsolutePosition = function () {
  5009. return this._transformedPosition ? this._transformedPosition : this.position;
  5010. };
  5011. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5012. if (this.parent && this.parent.getWorldMatrix) {
  5013. if (!this._transformedPosition) {
  5014. this._transformedPosition = BABYLON.Vector3.Zero();
  5015. }
  5016. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5017. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5018. return;
  5019. }
  5020. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5021. };
  5022. PointLight.prototype.getShadowGenerator = function () {
  5023. return null;
  5024. };
  5025. PointLight.prototype._getWorldMatrix = function () {
  5026. if (!this._worldMatrix) {
  5027. this._worldMatrix = BABYLON.Matrix.Identity();
  5028. }
  5029. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5030. return this._worldMatrix;
  5031. };
  5032. return PointLight;
  5033. })(BABYLON.Light);
  5034. BABYLON.PointLight = PointLight;
  5035. })(BABYLON || (BABYLON = {}));
  5036. //# sourceMappingURL=babylon.pointLight.js.map
  5037. var BABYLON;
  5038. (function (BABYLON) {
  5039. var SpotLight = (function (_super) {
  5040. __extends(SpotLight, _super);
  5041. function SpotLight(name, position, direction, angle, exponent, scene) {
  5042. _super.call(this, name, scene);
  5043. this.position = position;
  5044. this.direction = direction;
  5045. this.angle = angle;
  5046. this.exponent = exponent;
  5047. }
  5048. SpotLight.prototype.getAbsolutePosition = function () {
  5049. return this._transformedPosition ? this._transformedPosition : this.position;
  5050. };
  5051. SpotLight.prototype.setDirectionToTarget = function (target) {
  5052. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5053. return this.direction;
  5054. };
  5055. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5056. var normalizeDirection;
  5057. if (this.parent && this.parent.getWorldMatrix) {
  5058. if (!this._transformedDirection) {
  5059. this._transformedDirection = BABYLON.Vector3.Zero();
  5060. }
  5061. if (!this._transformedPosition) {
  5062. this._transformedPosition = BABYLON.Vector3.Zero();
  5063. }
  5064. var parentWorldMatrix = this.parent.getWorldMatrix();
  5065. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5066. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5067. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5068. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5069. } else {
  5070. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5071. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5072. }
  5073. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5074. };
  5075. SpotLight.prototype._getWorldMatrix = function () {
  5076. if (!this._worldMatrix) {
  5077. this._worldMatrix = BABYLON.Matrix.Identity();
  5078. }
  5079. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5080. return this._worldMatrix;
  5081. };
  5082. return SpotLight;
  5083. })(BABYLON.Light);
  5084. BABYLON.SpotLight = SpotLight;
  5085. })(BABYLON || (BABYLON = {}));
  5086. //# sourceMappingURL=babylon.spotLight.js.map
  5087. var BABYLON;
  5088. (function (BABYLON) {
  5089. var DirectionalLight = (function (_super) {
  5090. __extends(DirectionalLight, _super);
  5091. function DirectionalLight(name, direction, scene) {
  5092. _super.call(this, name, scene);
  5093. this.direction = direction;
  5094. this.position = direction.scale(-1);
  5095. }
  5096. DirectionalLight.prototype.getAbsolutePosition = function () {
  5097. return this._transformedPosition ? this._transformedPosition : this.position;
  5098. };
  5099. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5100. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5101. return this.direction;
  5102. };
  5103. DirectionalLight.prototype._computeTransformedPosition = function () {
  5104. if (this.parent && this.parent.getWorldMatrix) {
  5105. if (!this._transformedPosition) {
  5106. this._transformedPosition = BABYLON.Vector3.Zero();
  5107. }
  5108. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5109. return true;
  5110. }
  5111. return false;
  5112. };
  5113. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5114. if (this.parent && this.parent.getWorldMatrix) {
  5115. if (!this._transformedDirection) {
  5116. this._transformedDirection = BABYLON.Vector3.Zero();
  5117. }
  5118. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5119. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5120. return;
  5121. }
  5122. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5123. };
  5124. DirectionalLight.prototype._getWorldMatrix = function () {
  5125. if (!this._worldMatrix) {
  5126. this._worldMatrix = BABYLON.Matrix.Identity();
  5127. }
  5128. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5129. return this._worldMatrix;
  5130. };
  5131. return DirectionalLight;
  5132. })(BABYLON.Light);
  5133. BABYLON.DirectionalLight = DirectionalLight;
  5134. })(BABYLON || (BABYLON = {}));
  5135. //# sourceMappingURL=babylon.directionalLight.js.map
  5136. var BABYLON;
  5137. (function (BABYLON) {
  5138. var ShadowGenerator = (function () {
  5139. function ShadowGenerator(mapSize, light) {
  5140. var _this = this;
  5141. // Members
  5142. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5143. this._darkness = 0;
  5144. this._transparencyShadow = false;
  5145. this._viewMatrix = BABYLON.Matrix.Zero();
  5146. this._projectionMatrix = BABYLON.Matrix.Zero();
  5147. this._transformMatrix = BABYLON.Matrix.Zero();
  5148. this._worldViewProjection = BABYLON.Matrix.Zero();
  5149. this._light = light;
  5150. this._scene = light.getScene();
  5151. light._shadowGenerator = this;
  5152. // Render target
  5153. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5154. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5155. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5156. this._shadowMap.renderParticles = false;
  5157. // Custom render function
  5158. var renderSubMesh = function (subMesh) {
  5159. var mesh = subMesh.getRenderingMesh();
  5160. var scene = _this._scene;
  5161. var engine = scene.getEngine();
  5162. // Culling
  5163. engine.setState(subMesh.getMaterial().backFaceCulling);
  5164. // Managing instances
  5165. var batch = mesh._getInstancesRenderList(subMesh._id);
  5166. if (batch.mustReturn) {
  5167. return;
  5168. }
  5169. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5170. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5171. engine.enableEffect(_this._effect);
  5172. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5173. var material = subMesh.getMaterial();
  5174. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5175. // Alpha test
  5176. if (material && material.needAlphaTesting()) {
  5177. var alphaTexture = material.getAlphaTestTexture();
  5178. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5179. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5180. }
  5181. // Bones
  5182. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5183. if (useBones) {
  5184. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5185. }
  5186. if (hardwareInstancedRendering) {
  5187. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5188. } else {
  5189. if (batch.renderSelf[subMesh._id]) {
  5190. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5191. // Draw
  5192. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5193. }
  5194. if (batch.visibleInstances[subMesh._id]) {
  5195. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5196. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5197. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5198. // Draw
  5199. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5200. }
  5201. }
  5202. }
  5203. } else {
  5204. // Need to reset refresh rate of the shadowMap
  5205. _this._shadowMap.resetRefreshCounter();
  5206. }
  5207. };
  5208. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5209. var index;
  5210. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5211. renderSubMesh(opaqueSubMeshes.data[index]);
  5212. }
  5213. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5214. renderSubMesh(alphaTestSubMeshes.data[index]);
  5215. }
  5216. if (_this._transparencyShadow) {
  5217. for (index = 0; index < transparentSubMeshes.length; index++) {
  5218. renderSubMesh(transparentSubMeshes.data[index]);
  5219. }
  5220. }
  5221. };
  5222. }
  5223. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5224. // Static
  5225. get: function () {
  5226. return ShadowGenerator._FILTER_NONE;
  5227. },
  5228. enumerable: true,
  5229. configurable: true
  5230. });
  5231. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5232. get: function () {
  5233. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5234. },
  5235. enumerable: true,
  5236. configurable: true
  5237. });
  5238. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5239. get: function () {
  5240. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5241. },
  5242. enumerable: true,
  5243. configurable: true
  5244. });
  5245. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5246. get: function () {
  5247. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5248. },
  5249. set: function (value) {
  5250. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5251. },
  5252. enumerable: true,
  5253. configurable: true
  5254. });
  5255. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5256. get: function () {
  5257. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5258. },
  5259. set: function (value) {
  5260. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5261. },
  5262. enumerable: true,
  5263. configurable: true
  5264. });
  5265. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5266. var defines = [];
  5267. if (this.useVarianceShadowMap) {
  5268. defines.push("#define VSM");
  5269. }
  5270. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5271. var mesh = subMesh.getMesh();
  5272. var scene = mesh.getScene();
  5273. var material = subMesh.getMaterial();
  5274. // Alpha test
  5275. if (material && material.needAlphaTesting()) {
  5276. defines.push("#define ALPHATEST");
  5277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5278. attribs.push(BABYLON.VertexBuffer.UVKind);
  5279. defines.push("#define UV1");
  5280. }
  5281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5282. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5283. defines.push("#define UV2");
  5284. }
  5285. }
  5286. // Bones
  5287. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5290. defines.push("#define BONES");
  5291. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5292. }
  5293. // Instances
  5294. if (useInstances) {
  5295. defines.push("#define INSTANCES");
  5296. attribs.push("world0");
  5297. attribs.push("world1");
  5298. attribs.push("world2");
  5299. attribs.push("world3");
  5300. }
  5301. // Get correct effect
  5302. var join = defines.join("\n");
  5303. if (this._cachedDefines != join) {
  5304. this._cachedDefines = join;
  5305. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5306. }
  5307. return this._effect.isReady();
  5308. };
  5309. ShadowGenerator.prototype.getShadowMap = function () {
  5310. return this._shadowMap;
  5311. };
  5312. ShadowGenerator.prototype.getLight = function () {
  5313. return this._light;
  5314. };
  5315. // Methods
  5316. ShadowGenerator.prototype.getTransformMatrix = function () {
  5317. var lightPosition = this._light.position;
  5318. var lightDirection = this._light.direction;
  5319. if (this._light._computeTransformedPosition()) {
  5320. lightPosition = this._light._transformedPosition;
  5321. }
  5322. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5323. this._cachedPosition = lightPosition.clone();
  5324. this._cachedDirection = lightDirection.clone();
  5325. var activeCamera = this._scene.activeCamera;
  5326. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5327. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5328. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5329. }
  5330. return this._transformMatrix;
  5331. };
  5332. ShadowGenerator.prototype.getDarkness = function () {
  5333. return this._darkness;
  5334. };
  5335. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5336. if (darkness >= 1.0)
  5337. this._darkness = 1.0;
  5338. else if (darkness <= 0.0)
  5339. this._darkness = 0.0;
  5340. else
  5341. this._darkness = darkness;
  5342. };
  5343. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5344. this._transparencyShadow = hasShadow;
  5345. };
  5346. ShadowGenerator.prototype.dispose = function () {
  5347. this._shadowMap.dispose();
  5348. };
  5349. ShadowGenerator._FILTER_NONE = 0;
  5350. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5351. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5352. return ShadowGenerator;
  5353. })();
  5354. BABYLON.ShadowGenerator = ShadowGenerator;
  5355. })(BABYLON || (BABYLON = {}));
  5356. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5357. var BABYLON;
  5358. (function (BABYLON) {
  5359. var HemisphericLight = (function (_super) {
  5360. __extends(HemisphericLight, _super);
  5361. function HemisphericLight(name, direction, scene) {
  5362. _super.call(this, name, scene);
  5363. this.direction = direction;
  5364. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5365. }
  5366. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5367. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5368. return this.direction;
  5369. };
  5370. HemisphericLight.prototype.getShadowGenerator = function () {
  5371. return null;
  5372. };
  5373. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5374. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5375. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5376. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5377. };
  5378. HemisphericLight.prototype._getWorldMatrix = function () {
  5379. if (!this._worldMatrix) {
  5380. this._worldMatrix = BABYLON.Matrix.Identity();
  5381. }
  5382. return this._worldMatrix;
  5383. };
  5384. return HemisphericLight;
  5385. })(BABYLON.Light);
  5386. BABYLON.HemisphericLight = HemisphericLight;
  5387. })(BABYLON || (BABYLON = {}));
  5388. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5389. var BABYLON;
  5390. (function (BABYLON) {
  5391. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5392. if (boxMin.x > sphereCenter.x + sphereRadius)
  5393. return false;
  5394. if (sphereCenter.x - sphereRadius > boxMax.x)
  5395. return false;
  5396. if (boxMin.y > sphereCenter.y + sphereRadius)
  5397. return false;
  5398. if (sphereCenter.y - sphereRadius > boxMax.y)
  5399. return false;
  5400. if (boxMin.z > sphereCenter.z + sphereRadius)
  5401. return false;
  5402. if (sphereCenter.z - sphereRadius > boxMax.z)
  5403. return false;
  5404. return true;
  5405. };
  5406. var getLowestRoot = function (a, b, c, maxR) {
  5407. var determinant = b * b - 4.0 * a * c;
  5408. var result = { root: 0, found: false };
  5409. if (determinant < 0)
  5410. return result;
  5411. var sqrtD = Math.sqrt(determinant);
  5412. var r1 = (-b - sqrtD) / (2.0 * a);
  5413. var r2 = (-b + sqrtD) / (2.0 * a);
  5414. if (r1 > r2) {
  5415. var temp = r2;
  5416. r2 = r1;
  5417. r1 = temp;
  5418. }
  5419. if (r1 > 0 && r1 < maxR) {
  5420. result.root = r1;
  5421. result.found = true;
  5422. return result;
  5423. }
  5424. if (r2 > 0 && r2 < maxR) {
  5425. result.root = r2;
  5426. result.found = true;
  5427. return result;
  5428. }
  5429. return result;
  5430. };
  5431. var Collider = (function () {
  5432. function Collider() {
  5433. this.radius = new BABYLON.Vector3(1, 1, 1);
  5434. this.retry = 0;
  5435. this.basePointWorld = BABYLON.Vector3.Zero();
  5436. this.velocityWorld = BABYLON.Vector3.Zero();
  5437. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5438. this._collisionPoint = BABYLON.Vector3.Zero();
  5439. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5440. this._tempVector = BABYLON.Vector3.Zero();
  5441. this._tempVector2 = BABYLON.Vector3.Zero();
  5442. this._tempVector3 = BABYLON.Vector3.Zero();
  5443. this._tempVector4 = BABYLON.Vector3.Zero();
  5444. this._edge = BABYLON.Vector3.Zero();
  5445. this._baseToVertex = BABYLON.Vector3.Zero();
  5446. this._destinationPoint = BABYLON.Vector3.Zero();
  5447. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5448. this._displacementVector = BABYLON.Vector3.Zero();
  5449. }
  5450. // Methods
  5451. Collider.prototype._initialize = function (source, dir, e) {
  5452. this.velocity = dir;
  5453. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5454. this.basePoint = source;
  5455. source.multiplyToRef(this.radius, this.basePointWorld);
  5456. dir.multiplyToRef(this.radius, this.velocityWorld);
  5457. this.velocityWorldLength = this.velocityWorld.length();
  5458. this.epsilon = e;
  5459. this.collisionFound = false;
  5460. };
  5461. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5462. pa.subtractToRef(point, this._tempVector);
  5463. pb.subtractToRef(point, this._tempVector2);
  5464. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5465. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5466. if (d < 0)
  5467. return false;
  5468. pc.subtractToRef(point, this._tempVector3);
  5469. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5470. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5471. if (d < 0)
  5472. return false;
  5473. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5474. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5475. return d >= 0;
  5476. };
  5477. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5478. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5479. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5480. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5481. return false;
  5482. }
  5483. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5484. return false;
  5485. return true;
  5486. };
  5487. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5488. var t0;
  5489. var embeddedInPlane = false;
  5490. if (!subMesh._trianglePlanes) {
  5491. subMesh._trianglePlanes = [];
  5492. }
  5493. if (!subMesh._trianglePlanes[faceIndex]) {
  5494. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5495. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5496. }
  5497. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5498. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5499. return;
  5500. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5501. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5502. if (normalDotVelocity == 0) {
  5503. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5504. return;
  5505. embeddedInPlane = true;
  5506. t0 = 0;
  5507. } else {
  5508. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5509. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5510. if (t0 > t1) {
  5511. var temp = t1;
  5512. t1 = t0;
  5513. t0 = temp;
  5514. }
  5515. if (t0 > 1.0 || t1 < 0.0)
  5516. return;
  5517. if (t0 < 0)
  5518. t0 = 0;
  5519. if (t0 > 1.0)
  5520. t0 = 1.0;
  5521. }
  5522. this._collisionPoint.copyFromFloats(0, 0, 0);
  5523. var found = false;
  5524. var t = 1.0;
  5525. if (!embeddedInPlane) {
  5526. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5527. this.velocity.scaleToRef(t0, this._tempVector);
  5528. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5529. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5530. found = true;
  5531. t = t0;
  5532. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5533. }
  5534. }
  5535. if (!found) {
  5536. var velocitySquaredLength = this.velocity.lengthSquared();
  5537. var a = velocitySquaredLength;
  5538. this.basePoint.subtractToRef(p1, this._tempVector);
  5539. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5540. var c = this._tempVector.lengthSquared() - 1.0;
  5541. var lowestRoot = getLowestRoot(a, b, c, t);
  5542. if (lowestRoot.found) {
  5543. t = lowestRoot.root;
  5544. found = true;
  5545. this._collisionPoint.copyFrom(p1);
  5546. }
  5547. this.basePoint.subtractToRef(p2, this._tempVector);
  5548. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5549. c = this._tempVector.lengthSquared() - 1.0;
  5550. lowestRoot = getLowestRoot(a, b, c, t);
  5551. if (lowestRoot.found) {
  5552. t = lowestRoot.root;
  5553. found = true;
  5554. this._collisionPoint.copyFrom(p2);
  5555. }
  5556. this.basePoint.subtractToRef(p3, this._tempVector);
  5557. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5558. c = this._tempVector.lengthSquared() - 1.0;
  5559. lowestRoot = getLowestRoot(a, b, c, t);
  5560. if (lowestRoot.found) {
  5561. t = lowestRoot.root;
  5562. found = true;
  5563. this._collisionPoint.copyFrom(p3);
  5564. }
  5565. p2.subtractToRef(p1, this._edge);
  5566. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5567. var edgeSquaredLength = this._edge.lengthSquared();
  5568. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5569. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5570. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5571. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5572. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5573. lowestRoot = getLowestRoot(a, b, c, t);
  5574. if (lowestRoot.found) {
  5575. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5576. if (f >= 0.0 && f <= 1.0) {
  5577. t = lowestRoot.root;
  5578. found = true;
  5579. this._edge.scaleInPlace(f);
  5580. p1.addToRef(this._edge, this._collisionPoint);
  5581. }
  5582. }
  5583. p3.subtractToRef(p2, this._edge);
  5584. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5585. edgeSquaredLength = this._edge.lengthSquared();
  5586. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5587. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5588. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5589. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5590. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5591. lowestRoot = getLowestRoot(a, b, c, t);
  5592. if (lowestRoot.found) {
  5593. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5594. if (f >= 0.0 && f <= 1.0) {
  5595. t = lowestRoot.root;
  5596. found = true;
  5597. this._edge.scaleInPlace(f);
  5598. p2.addToRef(this._edge, this._collisionPoint);
  5599. }
  5600. }
  5601. p1.subtractToRef(p3, this._edge);
  5602. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5603. edgeSquaredLength = this._edge.lengthSquared();
  5604. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5605. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5606. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5607. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5608. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5609. lowestRoot = getLowestRoot(a, b, c, t);
  5610. if (lowestRoot.found) {
  5611. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5612. if (f >= 0.0 && f <= 1.0) {
  5613. t = lowestRoot.root;
  5614. found = true;
  5615. this._edge.scaleInPlace(f);
  5616. p3.addToRef(this._edge, this._collisionPoint);
  5617. }
  5618. }
  5619. }
  5620. if (found) {
  5621. var distToCollision = t * this.velocity.length();
  5622. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5623. if (!this.intersectionPoint) {
  5624. this.intersectionPoint = this._collisionPoint.clone();
  5625. } else {
  5626. this.intersectionPoint.copyFrom(this._collisionPoint);
  5627. }
  5628. this.nearestDistance = distToCollision;
  5629. this.collisionFound = true;
  5630. this.collidedMesh = subMesh.getMesh();
  5631. }
  5632. }
  5633. };
  5634. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5635. for (var i = indexStart; i < indexEnd; i += 3) {
  5636. var p1 = pts[indices[i] - decal];
  5637. var p2 = pts[indices[i + 1] - decal];
  5638. var p3 = pts[indices[i + 2] - decal];
  5639. this._testTriangle(i, subMesh, p3, p2, p1);
  5640. }
  5641. };
  5642. Collider.prototype._getResponse = function (pos, vel) {
  5643. pos.addToRef(vel, this._destinationPoint);
  5644. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5645. this.basePoint.addToRef(vel, pos);
  5646. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5647. this._slidePlaneNormal.normalize();
  5648. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5649. pos.addInPlace(this._displacementVector);
  5650. this.intersectionPoint.addInPlace(this._displacementVector);
  5651. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5652. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5653. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5654. };
  5655. return Collider;
  5656. })();
  5657. BABYLON.Collider = Collider;
  5658. })(BABYLON || (BABYLON = {}));
  5659. //# sourceMappingURL=babylon.collider.js.map
  5660. var BABYLON;
  5661. (function (BABYLON) {
  5662. var Camera = (function (_super) {
  5663. __extends(Camera, _super);
  5664. function Camera(name, position, scene) {
  5665. _super.call(this, name, scene);
  5666. this.position = position;
  5667. // Members
  5668. this.upVector = BABYLON.Vector3.Up();
  5669. this.orthoLeft = null;
  5670. this.orthoRight = null;
  5671. this.orthoBottom = null;
  5672. this.orthoTop = null;
  5673. this.fov = 0.8;
  5674. this.minZ = 1.0;
  5675. this.maxZ = 10000.0;
  5676. this.inertia = 0.9;
  5677. this.mode = Camera.PERSPECTIVE_CAMERA;
  5678. this.isIntermediate = false;
  5679. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5680. this.subCameras = [];
  5681. this.layerMask = 0xFFFFFFFF;
  5682. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5683. this._projectionMatrix = new BABYLON.Matrix();
  5684. this._postProcesses = new Array();
  5685. this._postProcessesTakenIndices = [];
  5686. scene.cameras.push(this);
  5687. if (!scene.activeCamera) {
  5688. scene.activeCamera = this;
  5689. }
  5690. }
  5691. //Cache
  5692. Camera.prototype._initCache = function () {
  5693. _super.prototype._initCache.call(this);
  5694. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5696. this._cache.mode = undefined;
  5697. this._cache.minZ = undefined;
  5698. this._cache.maxZ = undefined;
  5699. this._cache.fov = undefined;
  5700. this._cache.aspectRatio = undefined;
  5701. this._cache.orthoLeft = undefined;
  5702. this._cache.orthoRight = undefined;
  5703. this._cache.orthoBottom = undefined;
  5704. this._cache.orthoTop = undefined;
  5705. this._cache.renderWidth = undefined;
  5706. this._cache.renderHeight = undefined;
  5707. };
  5708. Camera.prototype._updateCache = function (ignoreParentClass) {
  5709. if (!ignoreParentClass) {
  5710. _super.prototype._updateCache.call(this);
  5711. }
  5712. var engine = this.getEngine();
  5713. this._cache.position.copyFrom(this.position);
  5714. this._cache.upVector.copyFrom(this.upVector);
  5715. this._cache.mode = this.mode;
  5716. this._cache.minZ = this.minZ;
  5717. this._cache.maxZ = this.maxZ;
  5718. this._cache.fov = this.fov;
  5719. this._cache.aspectRatio = engine.getAspectRatio(this);
  5720. this._cache.orthoLeft = this.orthoLeft;
  5721. this._cache.orthoRight = this.orthoRight;
  5722. this._cache.orthoBottom = this.orthoBottom;
  5723. this._cache.orthoTop = this.orthoTop;
  5724. this._cache.renderWidth = engine.getRenderWidth();
  5725. this._cache.renderHeight = engine.getRenderHeight();
  5726. };
  5727. Camera.prototype._updateFromScene = function () {
  5728. this.updateCache();
  5729. this._update();
  5730. };
  5731. // Synchronized
  5732. Camera.prototype._isSynchronized = function () {
  5733. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5734. };
  5735. Camera.prototype._isSynchronizedViewMatrix = function () {
  5736. if (!_super.prototype._isSynchronized.call(this))
  5737. return false;
  5738. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5739. };
  5740. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5741. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5742. if (!check) {
  5743. return false;
  5744. }
  5745. var engine = this.getEngine();
  5746. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5747. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5748. } else {
  5749. 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();
  5750. }
  5751. return check;
  5752. };
  5753. // Controls
  5754. Camera.prototype.attachControl = function (element) {
  5755. };
  5756. Camera.prototype.detachControl = function (element) {
  5757. };
  5758. Camera.prototype._update = function () {
  5759. };
  5760. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5761. if (typeof insertAt === "undefined") { insertAt = null; }
  5762. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5763. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5764. return 0;
  5765. }
  5766. if (insertAt == null || insertAt < 0) {
  5767. this._postProcesses.push(postProcess);
  5768. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5769. return this._postProcesses.length - 1;
  5770. }
  5771. var add = 0;
  5772. if (this._postProcesses[insertAt]) {
  5773. var start = this._postProcesses.length - 1;
  5774. for (var i = start; i >= insertAt + 1; --i) {
  5775. this._postProcesses[i + 1] = this._postProcesses[i];
  5776. }
  5777. add = 1;
  5778. }
  5779. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5780. if (this._postProcessesTakenIndices[i] < insertAt) {
  5781. continue;
  5782. }
  5783. start = this._postProcessesTakenIndices.length - 1;
  5784. for (var j = start; j >= i; --j) {
  5785. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5786. }
  5787. this._postProcessesTakenIndices[i] = insertAt;
  5788. break;
  5789. }
  5790. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5791. this._postProcessesTakenIndices.push(insertAt);
  5792. }
  5793. var result = insertAt + add;
  5794. this._postProcesses[result] = postProcess;
  5795. return result;
  5796. };
  5797. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5798. if (typeof atIndices === "undefined") { atIndices = null; }
  5799. var result = [];
  5800. if (!atIndices) {
  5801. var length = this._postProcesses.length;
  5802. for (var i = 0; i < length; i++) {
  5803. if (this._postProcesses[i] !== postProcess) {
  5804. continue;
  5805. }
  5806. delete this._postProcesses[i];
  5807. var index = this._postProcessesTakenIndices.indexOf(i);
  5808. this._postProcessesTakenIndices.splice(index, 1);
  5809. }
  5810. } else {
  5811. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5812. for (i = 0; i < atIndices.length; i++) {
  5813. var foundPostProcess = this._postProcesses[atIndices[i]];
  5814. if (foundPostProcess !== postProcess) {
  5815. result.push(i);
  5816. continue;
  5817. }
  5818. delete this._postProcesses[atIndices[i]];
  5819. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5820. this._postProcessesTakenIndices.splice(index, 1);
  5821. }
  5822. }
  5823. return result;
  5824. };
  5825. Camera.prototype.getWorldMatrix = function () {
  5826. if (!this._worldMatrix) {
  5827. this._worldMatrix = BABYLON.Matrix.Identity();
  5828. }
  5829. var viewMatrix = this.getViewMatrix();
  5830. viewMatrix.invertToRef(this._worldMatrix);
  5831. return this._worldMatrix;
  5832. };
  5833. Camera.prototype._getViewMatrix = function () {
  5834. return BABYLON.Matrix.Identity();
  5835. };
  5836. Camera.prototype.getViewMatrix = function () {
  5837. this._computedViewMatrix = this._computeViewMatrix();
  5838. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5839. return this._computedViewMatrix;
  5840. }
  5841. if (!this._worldMatrix) {
  5842. this._worldMatrix = BABYLON.Matrix.Identity();
  5843. }
  5844. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5845. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5846. this._computedViewMatrix.invert();
  5847. this._currentRenderId = this.getScene().getRenderId();
  5848. return this._computedViewMatrix;
  5849. };
  5850. Camera.prototype._computeViewMatrix = function (force) {
  5851. if (!force && this._isSynchronizedViewMatrix()) {
  5852. return this._computedViewMatrix;
  5853. }
  5854. this._computedViewMatrix = this._getViewMatrix();
  5855. if (!this.parent || !this.parent.getWorldMatrix) {
  5856. this._currentRenderId = this.getScene().getRenderId();
  5857. }
  5858. return this._computedViewMatrix;
  5859. };
  5860. Camera.prototype.getProjectionMatrix = function (force) {
  5861. if (!force && this._isSynchronizedProjectionMatrix()) {
  5862. return this._projectionMatrix;
  5863. }
  5864. var engine = this.getEngine();
  5865. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5866. if (this.minZ <= 0) {
  5867. this.minZ = 0.1;
  5868. }
  5869. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5870. return this._projectionMatrix;
  5871. }
  5872. var halfWidth = engine.getRenderWidth() / 2.0;
  5873. var halfHeight = engine.getRenderHeight() / 2.0;
  5874. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5875. return this._projectionMatrix;
  5876. };
  5877. Camera.prototype.dispose = function () {
  5878. // Remove from scene
  5879. var index = this.getScene().cameras.indexOf(this);
  5880. this.getScene().cameras.splice(index, 1);
  5881. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5882. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5883. }
  5884. };
  5885. Camera.PERSPECTIVE_CAMERA = 0;
  5886. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5887. return Camera;
  5888. })(BABYLON.Node);
  5889. BABYLON.Camera = Camera;
  5890. })(BABYLON || (BABYLON = {}));
  5891. //# sourceMappingURL=babylon.camera.js.map
  5892. var BABYLON;
  5893. (function (BABYLON) {
  5894. var TargetCamera = (function (_super) {
  5895. __extends(TargetCamera, _super);
  5896. function TargetCamera(name, position, scene) {
  5897. _super.call(this, name, position, scene);
  5898. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5899. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5900. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5901. this.speed = 2.0;
  5902. this.noRotationConstraint = false;
  5903. this.lockedTarget = null;
  5904. this._currentTarget = BABYLON.Vector3.Zero();
  5905. this._viewMatrix = BABYLON.Matrix.Zero();
  5906. this._camMatrix = BABYLON.Matrix.Zero();
  5907. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5908. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5909. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5910. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5911. this._lookAtTemp = BABYLON.Matrix.Zero();
  5912. this._tempMatrix = BABYLON.Matrix.Zero();
  5913. }
  5914. TargetCamera.prototype._getLockedTargetPosition = function () {
  5915. if (!this.lockedTarget) {
  5916. return null;
  5917. }
  5918. return this.lockedTarget.position || this.lockedTarget;
  5919. };
  5920. // Cache
  5921. TargetCamera.prototype._initCache = function () {
  5922. _super.prototype._initCache.call(this);
  5923. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5924. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5925. };
  5926. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5927. if (!ignoreParentClass) {
  5928. _super.prototype._updateCache.call(this);
  5929. }
  5930. var lockedTargetPosition = this._getLockedTargetPosition();
  5931. if (!lockedTargetPosition) {
  5932. this._cache.lockedTarget = null;
  5933. } else {
  5934. if (!this._cache.lockedTarget) {
  5935. this._cache.lockedTarget = lockedTargetPosition.clone();
  5936. } else {
  5937. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5938. }
  5939. }
  5940. this._cache.rotation.copyFrom(this.rotation);
  5941. };
  5942. // Synchronized
  5943. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5944. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5945. return false;
  5946. }
  5947. var lockedTargetPosition = this._getLockedTargetPosition();
  5948. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5949. };
  5950. // Methods
  5951. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5952. var engine = this.getEngine();
  5953. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  5954. };
  5955. // Target
  5956. TargetCamera.prototype.setTarget = function (target) {
  5957. this.upVector.normalize();
  5958. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5959. this._camMatrix.invert();
  5960. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5961. var vDir = target.subtract(this.position);
  5962. if (vDir.x >= 0.0) {
  5963. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5964. } else {
  5965. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5966. }
  5967. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5968. if (isNaN(this.rotation.x)) {
  5969. this.rotation.x = 0;
  5970. }
  5971. if (isNaN(this.rotation.y)) {
  5972. this.rotation.y = 0;
  5973. }
  5974. if (isNaN(this.rotation.z)) {
  5975. this.rotation.z = 0;
  5976. }
  5977. };
  5978. TargetCamera.prototype.getTarget = function () {
  5979. return this._currentTarget;
  5980. };
  5981. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5982. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5983. };
  5984. TargetCamera.prototype._updatePosition = function () {
  5985. this.position.addInPlace(this.cameraDirection);
  5986. };
  5987. TargetCamera.prototype._update = function () {
  5988. var needToMove = this._decideIfNeedsToMove();
  5989. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5990. // Move
  5991. if (needToMove) {
  5992. this._updatePosition();
  5993. }
  5994. // Rotate
  5995. if (needToRotate) {
  5996. this.rotation.x += this.cameraRotation.x;
  5997. this.rotation.y += this.cameraRotation.y;
  5998. if (!this.noRotationConstraint) {
  5999. var limit = (Math.PI / 2) * 0.95;
  6000. if (this.rotation.x > limit)
  6001. this.rotation.x = limit;
  6002. if (this.rotation.x < -limit)
  6003. this.rotation.x = -limit;
  6004. }
  6005. }
  6006. // Inertia
  6007. if (needToMove) {
  6008. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6009. this.cameraDirection.x = 0;
  6010. }
  6011. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6012. this.cameraDirection.y = 0;
  6013. }
  6014. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6015. this.cameraDirection.z = 0;
  6016. }
  6017. this.cameraDirection.scaleInPlace(this.inertia);
  6018. }
  6019. if (needToRotate) {
  6020. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6021. this.cameraRotation.x = 0;
  6022. }
  6023. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6024. this.cameraRotation.y = 0;
  6025. }
  6026. this.cameraRotation.scaleInPlace(this.inertia);
  6027. }
  6028. };
  6029. TargetCamera.prototype._getViewMatrix = function () {
  6030. if (!this.lockedTarget) {
  6031. // Compute
  6032. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6033. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6034. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6035. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6036. this._lookAtTemp.invert();
  6037. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6038. } else {
  6039. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6040. }
  6041. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6042. // Computing target and final matrix
  6043. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6044. } else {
  6045. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6046. }
  6047. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6048. return this._viewMatrix;
  6049. };
  6050. return TargetCamera;
  6051. })(BABYLON.Camera);
  6052. BABYLON.TargetCamera = TargetCamera;
  6053. })(BABYLON || (BABYLON = {}));
  6054. //# sourceMappingURL=babylon.targetCamera.js.map
  6055. var BABYLON;
  6056. (function (BABYLON) {
  6057. var FollowCamera = (function (_super) {
  6058. __extends(FollowCamera, _super);
  6059. function FollowCamera(name, position, scene) {
  6060. _super.call(this, name, position, scene);
  6061. this.radius = 12;
  6062. this.rotationOffset = 0;
  6063. this.heightOffset = 4;
  6064. this.cameraAcceleration = 0.05;
  6065. this.maxCameraSpeed = 20;
  6066. }
  6067. FollowCamera.prototype.getRadians = function (degrees) {
  6068. return degrees * Math.PI / 180;
  6069. };
  6070. FollowCamera.prototype.follow = function (cameraTarget) {
  6071. if (!cameraTarget)
  6072. return;
  6073. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6074. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6075. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6076. var dx = targetX - this.position.x;
  6077. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6078. var dz = (targetZ) - this.position.z;
  6079. var vx = dx * this.cameraAcceleration * 2;
  6080. var vy = dy * this.cameraAcceleration;
  6081. var vz = dz * this.cameraAcceleration * 2;
  6082. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6083. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6084. }
  6085. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6086. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6087. }
  6088. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6089. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6090. }
  6091. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6092. this.setTarget(cameraTarget.position);
  6093. };
  6094. FollowCamera.prototype._update = function () {
  6095. _super.prototype._update.call(this);
  6096. this.follow(this.target);
  6097. };
  6098. return FollowCamera;
  6099. })(BABYLON.TargetCamera);
  6100. BABYLON.FollowCamera = FollowCamera;
  6101. })(BABYLON || (BABYLON = {}));
  6102. //# sourceMappingURL=babylon.followCamera.js.map
  6103. var BABYLON;
  6104. (function (BABYLON) {
  6105. var FreeCamera = (function (_super) {
  6106. __extends(FreeCamera, _super);
  6107. function FreeCamera(name, position, scene) {
  6108. _super.call(this, name, position, scene);
  6109. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6110. this.keysUp = [38];
  6111. this.keysDown = [40];
  6112. this.keysLeft = [37];
  6113. this.keysRight = [39];
  6114. this.checkCollisions = false;
  6115. this.applyGravity = false;
  6116. this.angularSensibility = 2000.0;
  6117. this._keys = [];
  6118. this._collider = new BABYLON.Collider();
  6119. this._needMoveForGravity = true;
  6120. this._oldPosition = BABYLON.Vector3.Zero();
  6121. this._diffPosition = BABYLON.Vector3.Zero();
  6122. this._newPosition = BABYLON.Vector3.Zero();
  6123. }
  6124. // Controls
  6125. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6126. var _this = this;
  6127. var previousPosition;
  6128. var engine = this.getEngine();
  6129. if (this._attachedElement) {
  6130. return;
  6131. }
  6132. this._attachedElement = element;
  6133. if (this._onMouseDown === undefined) {
  6134. this._onMouseDown = function (evt) {
  6135. previousPosition = {
  6136. x: evt.clientX,
  6137. y: evt.clientY
  6138. };
  6139. if (!noPreventDefault) {
  6140. evt.preventDefault();
  6141. }
  6142. };
  6143. this._onMouseUp = function (evt) {
  6144. previousPosition = null;
  6145. if (!noPreventDefault) {
  6146. evt.preventDefault();
  6147. }
  6148. };
  6149. this._onMouseOut = function (evt) {
  6150. previousPosition = null;
  6151. _this._keys = [];
  6152. if (!noPreventDefault) {
  6153. evt.preventDefault();
  6154. }
  6155. };
  6156. this._onMouseMove = function (evt) {
  6157. if (!previousPosition && !engine.isPointerLock) {
  6158. return;
  6159. }
  6160. var offsetX;
  6161. var offsetY;
  6162. if (!engine.isPointerLock) {
  6163. offsetX = evt.clientX - previousPosition.x;
  6164. offsetY = evt.clientY - previousPosition.y;
  6165. } else {
  6166. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6167. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6168. }
  6169. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6170. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6171. previousPosition = {
  6172. x: evt.clientX,
  6173. y: evt.clientY
  6174. };
  6175. if (!noPreventDefault) {
  6176. evt.preventDefault();
  6177. }
  6178. };
  6179. this._onKeyDown = function (evt) {
  6180. 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) {
  6181. var index = _this._keys.indexOf(evt.keyCode);
  6182. if (index === -1) {
  6183. _this._keys.push(evt.keyCode);
  6184. }
  6185. if (!noPreventDefault) {
  6186. evt.preventDefault();
  6187. }
  6188. }
  6189. };
  6190. this._onKeyUp = function (evt) {
  6191. 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) {
  6192. var index = _this._keys.indexOf(evt.keyCode);
  6193. if (index >= 0) {
  6194. _this._keys.splice(index, 1);
  6195. }
  6196. if (!noPreventDefault) {
  6197. evt.preventDefault();
  6198. }
  6199. }
  6200. };
  6201. this._onLostFocus = function () {
  6202. _this._keys = [];
  6203. };
  6204. this._reset = function () {
  6205. _this._keys = [];
  6206. previousPosition = null;
  6207. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6208. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6209. };
  6210. }
  6211. element.addEventListener("mousedown", this._onMouseDown, false);
  6212. element.addEventListener("mouseup", this._onMouseUp, false);
  6213. element.addEventListener("mouseout", this._onMouseOut, false);
  6214. element.addEventListener("mousemove", this._onMouseMove, false);
  6215. BABYLON.Tools.RegisterTopRootEvents([
  6216. { name: "keydown", handler: this._onKeyDown },
  6217. { name: "keyup", handler: this._onKeyUp },
  6218. { name: "blur", handler: this._onLostFocus }
  6219. ]);
  6220. };
  6221. FreeCamera.prototype.detachControl = function (element) {
  6222. if (this._attachedElement != element) {
  6223. return;
  6224. }
  6225. element.removeEventListener("mousedown", this._onMouseDown);
  6226. element.removeEventListener("mouseup", this._onMouseUp);
  6227. element.removeEventListener("mouseout", this._onMouseOut);
  6228. element.removeEventListener("mousemove", this._onMouseMove);
  6229. BABYLON.Tools.UnregisterTopRootEvents([
  6230. { name: "keydown", handler: this._onKeyDown },
  6231. { name: "keyup", handler: this._onKeyUp },
  6232. { name: "blur", handler: this._onLostFocus }
  6233. ]);
  6234. this._attachedElement = null;
  6235. if (this._reset) {
  6236. this._reset();
  6237. }
  6238. };
  6239. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6240. var globalPosition;
  6241. if (this.parent) {
  6242. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6243. } else {
  6244. globalPosition = this.position;
  6245. }
  6246. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6247. this._collider.radius = this.ellipsoid;
  6248. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6249. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6250. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6251. this.position.addInPlace(this._diffPosition);
  6252. if (this.onCollide) {
  6253. this.onCollide(this._collider.collidedMesh);
  6254. }
  6255. }
  6256. };
  6257. FreeCamera.prototype._checkInputs = function () {
  6258. if (!this._localDirection) {
  6259. this._localDirection = BABYLON.Vector3.Zero();
  6260. this._transformedDirection = BABYLON.Vector3.Zero();
  6261. }
  6262. for (var index = 0; index < this._keys.length; index++) {
  6263. var keyCode = this._keys[index];
  6264. var speed = this._computeLocalCameraSpeed();
  6265. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6266. this._localDirection.copyFromFloats(-speed, 0, 0);
  6267. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6268. this._localDirection.copyFromFloats(0, 0, speed);
  6269. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6270. this._localDirection.copyFromFloats(speed, 0, 0);
  6271. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6272. this._localDirection.copyFromFloats(0, 0, -speed);
  6273. }
  6274. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6275. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6276. this.cameraDirection.addInPlace(this._transformedDirection);
  6277. }
  6278. };
  6279. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6280. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6281. };
  6282. FreeCamera.prototype._updatePosition = function () {
  6283. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6284. this._collideWithWorld(this.cameraDirection);
  6285. if (this.applyGravity) {
  6286. var oldPosition = this.position;
  6287. this._collideWithWorld(this.getScene().gravity);
  6288. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6289. }
  6290. } else {
  6291. this.position.addInPlace(this.cameraDirection);
  6292. }
  6293. };
  6294. FreeCamera.prototype._update = function () {
  6295. this._checkInputs();
  6296. _super.prototype._update.call(this);
  6297. };
  6298. return FreeCamera;
  6299. })(BABYLON.TargetCamera);
  6300. BABYLON.FreeCamera = FreeCamera;
  6301. })(BABYLON || (BABYLON = {}));
  6302. //# sourceMappingURL=babylon.freeCamera.js.map
  6303. var BABYLON;
  6304. (function (BABYLON) {
  6305. // We're mainly based on the logic defined into the FreeCamera code
  6306. var TouchCamera = (function (_super) {
  6307. __extends(TouchCamera, _super);
  6308. function TouchCamera(name, position, scene) {
  6309. _super.call(this, name, position, scene);
  6310. this._offsetX = null;
  6311. this._offsetY = null;
  6312. this._pointerCount = 0;
  6313. this._pointerPressed = [];
  6314. this.angularSensibility = 200000.0;
  6315. this.moveSensibility = 500.0;
  6316. }
  6317. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6318. var _this = this;
  6319. var previousPosition;
  6320. if (this._attachedCanvas) {
  6321. return;
  6322. }
  6323. this._attachedCanvas = canvas;
  6324. if (this._onPointerDown === undefined) {
  6325. this._onPointerDown = function (evt) {
  6326. if (!noPreventDefault) {
  6327. evt.preventDefault();
  6328. }
  6329. _this._pointerPressed.push(evt.pointerId);
  6330. if (_this._pointerPressed.length !== 1) {
  6331. return;
  6332. }
  6333. previousPosition = {
  6334. x: evt.clientX,
  6335. y: evt.clientY
  6336. };
  6337. };
  6338. this._onPointerUp = function (evt) {
  6339. if (!noPreventDefault) {
  6340. evt.preventDefault();
  6341. }
  6342. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6343. if (index === -1) {
  6344. return;
  6345. }
  6346. _this._pointerPressed.splice(index, 1);
  6347. if (index != 0) {
  6348. return;
  6349. }
  6350. previousPosition = null;
  6351. _this._offsetX = null;
  6352. _this._offsetY = null;
  6353. };
  6354. this._onPointerMove = function (evt) {
  6355. if (!noPreventDefault) {
  6356. evt.preventDefault();
  6357. }
  6358. if (!previousPosition) {
  6359. return;
  6360. }
  6361. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6362. if (index != 0) {
  6363. return;
  6364. }
  6365. _this._offsetX = evt.clientX - previousPosition.x;
  6366. _this._offsetY = -(evt.clientY - previousPosition.y);
  6367. };
  6368. this._onLostFocus = function () {
  6369. _this._offsetX = null;
  6370. _this._offsetY = null;
  6371. };
  6372. }
  6373. canvas.addEventListener("pointerdown", this._onPointerDown);
  6374. canvas.addEventListener("pointerup", this._onPointerUp);
  6375. canvas.addEventListener("pointerout", this._onPointerUp);
  6376. canvas.addEventListener("pointermove", this._onPointerMove);
  6377. BABYLON.Tools.RegisterTopRootEvents([
  6378. { name: "blur", handler: this._onLostFocus }
  6379. ]);
  6380. };
  6381. TouchCamera.prototype.detachControl = function (canvas) {
  6382. if (this._attachedCanvas != canvas) {
  6383. return;
  6384. }
  6385. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6386. canvas.removeEventListener("pointerup", this._onPointerUp);
  6387. canvas.removeEventListener("pointerout", this._onPointerUp);
  6388. canvas.removeEventListener("pointermove", this._onPointerMove);
  6389. BABYLON.Tools.UnregisterTopRootEvents([
  6390. { name: "blur", handler: this._onLostFocus }
  6391. ]);
  6392. this._attachedCanvas = null;
  6393. };
  6394. TouchCamera.prototype._checkInputs = function () {
  6395. if (!this._offsetX) {
  6396. return;
  6397. }
  6398. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6399. if (this._pointerPressed.length > 1) {
  6400. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6401. } else {
  6402. var speed = this._computeLocalCameraSpeed();
  6403. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6404. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6405. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6406. }
  6407. };
  6408. return TouchCamera;
  6409. })(BABYLON.FreeCamera);
  6410. BABYLON.TouchCamera = TouchCamera;
  6411. })(BABYLON || (BABYLON = {}));
  6412. //# sourceMappingURL=babylon.touchCamera.js.map
  6413. var BABYLON;
  6414. (function (BABYLON) {
  6415. // We're mainly based on the logic defined into the FreeCamera code
  6416. var DeviceOrientationCamera = (function (_super) {
  6417. __extends(DeviceOrientationCamera, _super);
  6418. function DeviceOrientationCamera(name, position, scene) {
  6419. var _this = this;
  6420. _super.call(this, name, position, scene);
  6421. this._offsetX = null;
  6422. this._offsetY = null;
  6423. this._orientationGamma = 0;
  6424. this._orientationBeta = 0;
  6425. this._initialOrientationGamma = 0;
  6426. this._initialOrientationBeta = 0;
  6427. this.angularSensibility = 10000.0;
  6428. this.moveSensibility = 50.0;
  6429. window.addEventListener("resize", function () {
  6430. _this._initialOrientationGamma = null;
  6431. }, false);
  6432. }
  6433. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6434. var _this = this;
  6435. if (this._attachedCanvas) {
  6436. return;
  6437. }
  6438. this._attachedCanvas = canvas;
  6439. if (!this._orientationChanged) {
  6440. this._orientationChanged = function (evt) {
  6441. if (!_this._initialOrientationGamma) {
  6442. _this._initialOrientationGamma = evt.gamma;
  6443. _this._initialOrientationBeta = evt.beta;
  6444. }
  6445. _this._orientationGamma = evt.gamma;
  6446. _this._orientationBeta = evt.beta;
  6447. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6448. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6449. };
  6450. }
  6451. window.addEventListener("deviceorientation", this._orientationChanged);
  6452. };
  6453. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6454. if (this._attachedCanvas != canvas) {
  6455. return;
  6456. }
  6457. window.removeEventListener("deviceorientation", this._orientationChanged);
  6458. this._attachedCanvas = null;
  6459. this._orientationGamma = 0;
  6460. this._orientationBeta = 0;
  6461. this._initialOrientationGamma = 0;
  6462. this._initialOrientationBeta = 0;
  6463. };
  6464. DeviceOrientationCamera.prototype._checkInputs = function () {
  6465. if (!this._offsetX) {
  6466. return;
  6467. }
  6468. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6469. var speed = this._computeLocalCameraSpeed();
  6470. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6471. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6472. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6473. };
  6474. return DeviceOrientationCamera;
  6475. })(BABYLON.FreeCamera);
  6476. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6477. })(BABYLON || (BABYLON = {}));
  6478. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6479. var BABYLON;
  6480. (function (BABYLON) {
  6481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6482. var ArcRotateCamera = (function (_super) {
  6483. __extends(ArcRotateCamera, _super);
  6484. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6485. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6486. this.alpha = alpha;
  6487. this.beta = beta;
  6488. this.radius = radius;
  6489. this.target = target;
  6490. this.inertialAlphaOffset = 0;
  6491. this.inertialBetaOffset = 0;
  6492. this.inertialRadiusOffset = 0;
  6493. this.lowerAlphaLimit = null;
  6494. this.upperAlphaLimit = null;
  6495. this.lowerBetaLimit = 0.01;
  6496. this.upperBetaLimit = Math.PI;
  6497. this.lowerRadiusLimit = null;
  6498. this.upperRadiusLimit = null;
  6499. this.angularSensibility = 1000.0;
  6500. this.wheelPrecision = 3.0;
  6501. this.keysUp = [38];
  6502. this.keysDown = [40];
  6503. this.keysLeft = [37];
  6504. this.keysRight = [39];
  6505. this.zoomOnFactor = 1;
  6506. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6507. this._keys = [];
  6508. this._viewMatrix = new BABYLON.Matrix();
  6509. this.checkCollisions = false;
  6510. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6511. this._collider = new BABYLON.Collider();
  6512. this._previousPosition = BABYLON.Vector3.Zero();
  6513. this._collisionVelocity = BABYLON.Vector3.Zero();
  6514. this._newPosition = BABYLON.Vector3.Zero();
  6515. // Pinch
  6516. // value for pinch step scaling
  6517. // set to 20 by default
  6518. this.pinchPrecision = 20;
  6519. this.getViewMatrix();
  6520. }
  6521. ArcRotateCamera.prototype._getTargetPosition = function () {
  6522. return this.target.position || this.target;
  6523. };
  6524. // Cache
  6525. ArcRotateCamera.prototype._initCache = function () {
  6526. _super.prototype._initCache.call(this);
  6527. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6528. this._cache.alpha = undefined;
  6529. this._cache.beta = undefined;
  6530. this._cache.radius = undefined;
  6531. this._cache.targetScreenOffset = undefined;
  6532. };
  6533. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6534. if (!ignoreParentClass) {
  6535. _super.prototype._updateCache.call(this);
  6536. }
  6537. this._cache.target.copyFrom(this._getTargetPosition());
  6538. this._cache.alpha = this.alpha;
  6539. this._cache.beta = this.beta;
  6540. this._cache.radius = this.radius;
  6541. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6542. };
  6543. // Synchronized
  6544. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6545. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6546. return false;
  6547. 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);
  6548. };
  6549. // Methods
  6550. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6551. var _this = this;
  6552. var previousPosition;
  6553. var pointerId;
  6554. // to know if pinch started
  6555. var pinchStarted = false;
  6556. // two pinch point on X
  6557. // that will use for find if user action is pinch open or pinch close
  6558. var pinchPointX1, pinchPointX2;
  6559. if (this._attachedElement) {
  6560. return;
  6561. }
  6562. this._attachedElement = element;
  6563. var engine = this.getEngine();
  6564. if (this._onPointerDown === undefined) {
  6565. this._onPointerDown = function (evt) {
  6566. if (pointerId) {
  6567. return;
  6568. }
  6569. pointerId = evt.pointerId;
  6570. previousPosition = {
  6571. x: evt.clientX,
  6572. y: evt.clientY
  6573. };
  6574. if (!noPreventDefault) {
  6575. evt.preventDefault();
  6576. }
  6577. };
  6578. this._onPointerUp = function (evt) {
  6579. previousPosition = null;
  6580. pointerId = null;
  6581. if (!noPreventDefault) {
  6582. evt.preventDefault();
  6583. }
  6584. };
  6585. this._onPointerMove = function (evt) {
  6586. if (!previousPosition) {
  6587. return;
  6588. }
  6589. if (pointerId !== evt.pointerId) {
  6590. return;
  6591. }
  6592. // return pinch is started
  6593. if (pinchStarted) {
  6594. return;
  6595. }
  6596. var offsetX = evt.clientX - previousPosition.x;
  6597. var offsetY = evt.clientY - previousPosition.y;
  6598. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6599. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6600. previousPosition = {
  6601. x: evt.clientX,
  6602. y: evt.clientY
  6603. };
  6604. if (!noPreventDefault) {
  6605. evt.preventDefault();
  6606. }
  6607. };
  6608. this._onMouseMove = function (evt) {
  6609. if (!engine.isPointerLock) {
  6610. return;
  6611. }
  6612. // return pinch is started
  6613. if (pinchStarted) {
  6614. return;
  6615. }
  6616. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6617. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6618. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6619. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6620. if (!noPreventDefault) {
  6621. evt.preventDefault();
  6622. }
  6623. };
  6624. this._wheel = function (event) {
  6625. var delta = 0;
  6626. if (event.wheelDelta) {
  6627. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6628. } else if (event.detail) {
  6629. delta = -event.detail / _this.wheelPrecision;
  6630. }
  6631. if (delta)
  6632. _this.inertialRadiusOffset += delta;
  6633. if (event.preventDefault) {
  6634. if (!noPreventDefault) {
  6635. event.preventDefault();
  6636. }
  6637. }
  6638. };
  6639. this._onKeyDown = function (evt) {
  6640. 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) {
  6641. var index = _this._keys.indexOf(evt.keyCode);
  6642. if (index === -1) {
  6643. _this._keys.push(evt.keyCode);
  6644. }
  6645. if (evt.preventDefault) {
  6646. if (!noPreventDefault) {
  6647. evt.preventDefault();
  6648. }
  6649. }
  6650. }
  6651. };
  6652. this._onKeyUp = function (evt) {
  6653. 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) {
  6654. var index = _this._keys.indexOf(evt.keyCode);
  6655. if (index >= 0) {
  6656. _this._keys.splice(index, 1);
  6657. }
  6658. if (evt.preventDefault) {
  6659. if (!noPreventDefault) {
  6660. evt.preventDefault();
  6661. }
  6662. }
  6663. }
  6664. };
  6665. this._onLostFocus = function () {
  6666. _this._keys = [];
  6667. pointerId = null;
  6668. };
  6669. this._onGestureStart = function (e) {
  6670. if (window.MSGesture === undefined) {
  6671. return;
  6672. }
  6673. if (!_this._MSGestureHandler) {
  6674. _this._MSGestureHandler = new MSGesture();
  6675. _this._MSGestureHandler.target = element;
  6676. }
  6677. _this._MSGestureHandler.addPointer(e.pointerId);
  6678. };
  6679. this._onGesture = function (e) {
  6680. _this.radius *= e.scale;
  6681. if (e.preventDefault) {
  6682. if (!noPreventDefault) {
  6683. e.stopPropagation();
  6684. e.preventDefault();
  6685. }
  6686. }
  6687. };
  6688. this._reset = function () {
  6689. _this._keys = [];
  6690. _this.inertialAlphaOffset = 0;
  6691. _this.inertialBetaOffset = 0;
  6692. _this.inertialRadiusOffset = 0;
  6693. previousPosition = null;
  6694. pointerId = null;
  6695. };
  6696. this._touchStart = function (event) {
  6697. if (event.touches.length == 2) {
  6698. //-- start pinch if two fingers on the screen
  6699. pinchStarted = true;
  6700. _this._pinchStart(event);
  6701. }
  6702. };
  6703. this._touchMove = function (event) {
  6704. if (pinchStarted) {
  6705. //-- make scaling
  6706. _this._pinchMove(event);
  6707. }
  6708. };
  6709. this._touchEnd = function (event) {
  6710. if (pinchStarted) {
  6711. //-- end of pinch
  6712. _this._pinchEnd(event);
  6713. }
  6714. };
  6715. this._pinchStart = function (event) {
  6716. // save origin touch point
  6717. pinchPointX1 = event.touches[0].clientX;
  6718. pinchPointX2 = event.touches[1].clientX;
  6719. // block the camera
  6720. // if not it rotate around target during pinch
  6721. pinchStarted = true;
  6722. };
  6723. this._pinchMove = function (event) {
  6724. // variable for new camera's radius
  6725. var delta = 0;
  6726. // variables to know if pinch open or pinch close
  6727. var direction = 1;
  6728. var distanceXOrigine, distanceXNow;
  6729. if (event.touches.length != 2)
  6730. return;
  6731. // calculate absolute distances of the two fingers
  6732. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6733. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6734. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6735. if (distanceXNow < distanceXOrigine) {
  6736. direction = -1;
  6737. }
  6738. // calculate new radius
  6739. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6740. // set new radius
  6741. _this.inertialRadiusOffset += delta;
  6742. // save origin touch point
  6743. pinchPointX1 = event.touches[0].clientX;
  6744. pinchPointX2 = event.touches[1].clientX;
  6745. };
  6746. this._pinchEnd = function (event) {
  6747. // cancel pinch and deblock camera rotation
  6748. pinchStarted = false;
  6749. };
  6750. }
  6751. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6752. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6753. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6754. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6755. element.addEventListener("mousemove", this._onMouseMove, false);
  6756. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6757. element.addEventListener("MSGestureChange", this._onGesture, false);
  6758. element.addEventListener('mousewheel', this._wheel, false);
  6759. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6760. // pinch
  6761. element.addEventListener('touchstart', this._touchStart, false);
  6762. element.addEventListener('touchmove', this._touchMove, false);
  6763. element.addEventListener('touchend', this._touchEnd, false);
  6764. BABYLON.Tools.RegisterTopRootEvents([
  6765. { name: "keydown", handler: this._onKeyDown },
  6766. { name: "keyup", handler: this._onKeyUp },
  6767. { name: "blur", handler: this._onLostFocus }
  6768. ]);
  6769. };
  6770. ArcRotateCamera.prototype.detachControl = function (element) {
  6771. if (this._attachedElement != element) {
  6772. return;
  6773. }
  6774. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6775. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6776. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6777. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6778. element.removeEventListener("mousemove", this._onMouseMove);
  6779. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6780. element.removeEventListener("MSGestureChange", this._onGesture);
  6781. element.removeEventListener('mousewheel', this._wheel);
  6782. element.removeEventListener('DOMMouseScroll', this._wheel);
  6783. // pinch
  6784. element.removeEventListener('touchstart', this._touchStart);
  6785. element.removeEventListener('touchmove', this._touchMove);
  6786. element.removeEventListener('touchend', this._touchEnd);
  6787. BABYLON.Tools.UnregisterTopRootEvents([
  6788. { name: "keydown", handler: this._onKeyDown },
  6789. { name: "keyup", handler: this._onKeyUp },
  6790. { name: "blur", handler: this._onLostFocus }
  6791. ]);
  6792. this._MSGestureHandler = null;
  6793. this._attachedElement = null;
  6794. if (this._reset) {
  6795. this._reset();
  6796. }
  6797. };
  6798. ArcRotateCamera.prototype._update = function () {
  6799. for (var index = 0; index < this._keys.length; index++) {
  6800. var keyCode = this._keys[index];
  6801. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6802. this.inertialAlphaOffset -= 0.01;
  6803. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6804. this.inertialBetaOffset -= 0.01;
  6805. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6806. this.inertialAlphaOffset += 0.01;
  6807. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6808. this.inertialBetaOffset += 0.01;
  6809. }
  6810. }
  6811. // Inertia
  6812. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6813. this.alpha += this.inertialAlphaOffset;
  6814. this.beta += this.inertialBetaOffset;
  6815. this.radius -= this.inertialRadiusOffset;
  6816. this.inertialAlphaOffset *= this.inertia;
  6817. this.inertialBetaOffset *= this.inertia;
  6818. this.inertialRadiusOffset *= this.inertia;
  6819. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6820. this.inertialAlphaOffset = 0;
  6821. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6822. this.inertialBetaOffset = 0;
  6823. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6824. this.inertialRadiusOffset = 0;
  6825. }
  6826. // Limits
  6827. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6828. this.alpha = this.lowerAlphaLimit;
  6829. }
  6830. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6831. this.alpha = this.upperAlphaLimit;
  6832. }
  6833. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6834. this.beta = this.lowerBetaLimit;
  6835. }
  6836. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6837. this.beta = this.upperBetaLimit;
  6838. }
  6839. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6840. this.radius = this.lowerRadiusLimit;
  6841. }
  6842. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6843. this.radius = this.upperRadiusLimit;
  6844. }
  6845. };
  6846. ArcRotateCamera.prototype.setPosition = function (position) {
  6847. var radiusv3 = position.subtract(this._getTargetPosition());
  6848. this.radius = radiusv3.length();
  6849. // Alpha
  6850. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6851. if (radiusv3.z < 0) {
  6852. this.alpha = 2 * Math.PI - this.alpha;
  6853. }
  6854. // Beta
  6855. this.beta = Math.acos(radiusv3.y / this.radius);
  6856. };
  6857. ArcRotateCamera.prototype._getViewMatrix = function () {
  6858. // Compute
  6859. var cosa = Math.cos(this.alpha);
  6860. var sina = Math.sin(this.alpha);
  6861. var cosb = Math.cos(this.beta);
  6862. var sinb = Math.sin(this.beta);
  6863. var target = this._getTargetPosition();
  6864. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6865. if (this.checkCollisions) {
  6866. this._collider.radius = this.collisionRadius;
  6867. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6868. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6869. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6870. this.position.copyFrom(this._previousPosition);
  6871. this.alpha = this._previousAlpha;
  6872. this.beta = this._previousBeta;
  6873. this.radius = this._previousRadius;
  6874. if (this.onCollide) {
  6875. this.onCollide(this._collider.collidedMesh);
  6876. }
  6877. }
  6878. }
  6879. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6880. this._previousAlpha = this.alpha;
  6881. this._previousBeta = this.beta;
  6882. this._previousRadius = this.radius;
  6883. this._previousPosition.copyFrom(this.position);
  6884. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6885. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6886. return this._viewMatrix;
  6887. };
  6888. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6889. meshes = meshes || this.getScene().meshes;
  6890. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6891. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6892. this.radius = distance * this.zoomOnFactor;
  6893. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6894. };
  6895. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6896. var meshesOrMinMaxVector;
  6897. var distance;
  6898. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6899. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6900. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6901. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6902. } else {
  6903. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6904. distance = meshesOrMinMaxVectorAndDistance.distance;
  6905. }
  6906. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6907. this.maxZ = distance * 2;
  6908. };
  6909. return ArcRotateCamera;
  6910. })(BABYLON.Camera);
  6911. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6912. })(BABYLON || (BABYLON = {}));
  6913. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  6914. var BABYLON;
  6915. (function (BABYLON) {
  6916. var Scene = (function () {
  6917. // Constructor
  6918. function Scene(engine) {
  6919. // Members
  6920. this.autoClear = true;
  6921. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6922. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6923. this.forceWireframe = false;
  6924. this.forcePointsCloud = false;
  6925. this.forceShowBoundingBoxes = false;
  6926. this.animationsEnabled = true;
  6927. this.cameraToUseForPointers = null;
  6928. // Fog
  6929. this.fogEnabled = true;
  6930. this.fogMode = Scene.FOGMODE_NONE;
  6931. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6932. this.fogDensity = 0.1;
  6933. this.fogStart = 0;
  6934. this.fogEnd = 1000.0;
  6935. // Lights
  6936. this.shadowsEnabled = true;
  6937. this.lightsEnabled = true;
  6938. this.lights = new Array();
  6939. // Cameras
  6940. this.cameras = new Array();
  6941. this.activeCameras = new Array();
  6942. // Meshes
  6943. this.meshes = new Array();
  6944. // Geometries
  6945. this._geometries = new Array();
  6946. this.materials = new Array();
  6947. this.multiMaterials = new Array();
  6948. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6949. // Textures
  6950. this.texturesEnabled = true;
  6951. this.textures = new Array();
  6952. // Particles
  6953. this.particlesEnabled = true;
  6954. this.particleSystems = new Array();
  6955. // Sprites
  6956. this.spriteManagers = new Array();
  6957. // Layers
  6958. this.layers = new Array();
  6959. // Skeletons
  6960. this.skeletonsEnabled = true;
  6961. this.skeletons = new Array();
  6962. // Lens flares
  6963. this.lensFlaresEnabled = true;
  6964. this.lensFlareSystems = new Array();
  6965. // Collisions
  6966. this.collisionsEnabled = true;
  6967. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6968. // Postprocesses
  6969. this.postProcessesEnabled = true;
  6970. // Customs render targets
  6971. this.renderTargetsEnabled = true;
  6972. this.customRenderTargets = new Array();
  6973. // Imported meshes
  6974. this.importedMeshesFiles = new Array();
  6975. this._actionManagers = new Array();
  6976. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6977. // Procedural textures
  6978. this.proceduralTexturesEnabled = true;
  6979. this._proceduralTextures = new Array();
  6980. this.soundTracks = new Array();
  6981. this._totalVertices = 0;
  6982. this._activeVertices = 0;
  6983. this._activeParticles = 0;
  6984. this._lastFrameDuration = 0;
  6985. this._evaluateActiveMeshesDuration = 0;
  6986. this._renderTargetsDuration = 0;
  6987. this._particlesDuration = 0;
  6988. this._renderDuration = 0;
  6989. this._spritesDuration = 0;
  6990. this._animationRatio = 0;
  6991. this._renderId = 0;
  6992. this._executeWhenReadyTimeoutId = -1;
  6993. this._toBeDisposed = new BABYLON.SmartArray(256);
  6994. this._onReadyCallbacks = new Array();
  6995. this._pendingData = [];
  6996. this._onBeforeRenderCallbacks = new Array();
  6997. this._onAfterRenderCallbacks = new Array();
  6998. this._activeMeshes = new BABYLON.SmartArray(256);
  6999. this._processedMaterials = new BABYLON.SmartArray(256);
  7000. this._renderTargets = new BABYLON.SmartArray(256);
  7001. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7002. this._activeSkeletons = new BABYLON.SmartArray(32);
  7003. this._activeBones = 0;
  7004. this._activeAnimatables = new Array();
  7005. this._transformMatrix = BABYLON.Matrix.Zero();
  7006. this._scaledPosition = BABYLON.Vector3.Zero();
  7007. this._scaledVelocity = BABYLON.Vector3.Zero();
  7008. this._engine = engine;
  7009. engine.scenes.push(this);
  7010. this._renderingManager = new BABYLON.RenderingManager(this);
  7011. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7012. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7013. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7014. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7015. this.attachControl();
  7016. this._debugLayer = new BABYLON.DebugLayer(this);
  7017. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7018. }
  7019. Object.defineProperty(Scene.prototype, "debugLayer", {
  7020. // Properties
  7021. get: function () {
  7022. return this._debugLayer;
  7023. },
  7024. enumerable: true,
  7025. configurable: true
  7026. });
  7027. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7028. get: function () {
  7029. return this._meshUnderPointer;
  7030. },
  7031. enumerable: true,
  7032. configurable: true
  7033. });
  7034. Object.defineProperty(Scene.prototype, "pointerX", {
  7035. get: function () {
  7036. return this._pointerX;
  7037. },
  7038. enumerable: true,
  7039. configurable: true
  7040. });
  7041. Object.defineProperty(Scene.prototype, "pointerY", {
  7042. get: function () {
  7043. return this._pointerY;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Scene.prototype.getCachedMaterial = function () {
  7049. return this._cachedMaterial;
  7050. };
  7051. Scene.prototype.getBoundingBoxRenderer = function () {
  7052. return this._boundingBoxRenderer;
  7053. };
  7054. Scene.prototype.getOutlineRenderer = function () {
  7055. return this._outlineRenderer;
  7056. };
  7057. Scene.prototype.getEngine = function () {
  7058. return this._engine;
  7059. };
  7060. Scene.prototype.getTotalVertices = function () {
  7061. return this._totalVertices;
  7062. };
  7063. Scene.prototype.getActiveVertices = function () {
  7064. return this._activeVertices;
  7065. };
  7066. Scene.prototype.getActiveParticles = function () {
  7067. return this._activeParticles;
  7068. };
  7069. Scene.prototype.getActiveBones = function () {
  7070. return this._activeBones;
  7071. };
  7072. // Stats
  7073. Scene.prototype.getLastFrameDuration = function () {
  7074. return this._lastFrameDuration;
  7075. };
  7076. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7077. return this._evaluateActiveMeshesDuration;
  7078. };
  7079. Scene.prototype.getActiveMeshes = function () {
  7080. return this._activeMeshes;
  7081. };
  7082. Scene.prototype.getRenderTargetsDuration = function () {
  7083. return this._renderTargetsDuration;
  7084. };
  7085. Scene.prototype.getRenderDuration = function () {
  7086. return this._renderDuration;
  7087. };
  7088. Scene.prototype.getParticlesDuration = function () {
  7089. return this._particlesDuration;
  7090. };
  7091. Scene.prototype.getSpritesDuration = function () {
  7092. return this._spritesDuration;
  7093. };
  7094. Scene.prototype.getAnimationRatio = function () {
  7095. return this._animationRatio;
  7096. };
  7097. Scene.prototype.getRenderId = function () {
  7098. return this._renderId;
  7099. };
  7100. Scene.prototype._updatePointerPosition = function (evt) {
  7101. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7102. this._pointerX = evt.clientX - canvasRect.left;
  7103. this._pointerY = evt.clientY - canvasRect.top;
  7104. if (this.cameraToUseForPointers) {
  7105. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7106. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7107. }
  7108. };
  7109. // Pointers handling
  7110. Scene.prototype.attachControl = function () {
  7111. var _this = this;
  7112. this._onPointerMove = function (evt) {
  7113. var canvas = _this._engine.getRenderingCanvas();
  7114. _this._updatePointerPosition(evt);
  7115. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7116. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7117. }, false, _this.cameraToUseForPointers);
  7118. if (pickResult.hit) {
  7119. _this._meshUnderPointer = pickResult.pickedMesh;
  7120. _this.setPointerOverMesh(pickResult.pickedMesh);
  7121. canvas.style.cursor = "pointer";
  7122. } else {
  7123. _this.setPointerOverMesh(null);
  7124. canvas.style.cursor = "";
  7125. _this._meshUnderPointer = null;
  7126. }
  7127. };
  7128. this._onPointerDown = function (evt) {
  7129. var predicate = null;
  7130. if (!_this.onPointerDown) {
  7131. predicate = function (mesh) {
  7132. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7133. };
  7134. }
  7135. _this._updatePointerPosition(evt);
  7136. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7137. if (pickResult.hit) {
  7138. if (pickResult.pickedMesh.actionManager) {
  7139. switch (evt.button) {
  7140. case 0:
  7141. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7142. break;
  7143. case 1:
  7144. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7145. break;
  7146. case 2:
  7147. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7148. break;
  7149. }
  7150. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7151. }
  7152. }
  7153. if (_this.onPointerDown) {
  7154. _this.onPointerDown(evt, pickResult);
  7155. }
  7156. };
  7157. this._onKeyDown = function (evt) {
  7158. if (_this.actionManager) {
  7159. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7160. }
  7161. };
  7162. this._onKeyUp = function (evt) {
  7163. if (_this.actionManager) {
  7164. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7165. }
  7166. };
  7167. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7168. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7169. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7170. window.addEventListener("keydown", this._onKeyDown, false);
  7171. window.addEventListener("keyup", this._onKeyUp, false);
  7172. };
  7173. Scene.prototype.detachControl = function () {
  7174. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7175. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7176. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7177. window.removeEventListener("keydown", this._onKeyDown);
  7178. window.removeEventListener("keyup", this._onKeyUp);
  7179. };
  7180. // Ready
  7181. Scene.prototype.isReady = function () {
  7182. if (this._pendingData.length > 0) {
  7183. return false;
  7184. }
  7185. for (var index = 0; index < this._geometries.length; index++) {
  7186. var geometry = this._geometries[index];
  7187. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7188. return false;
  7189. }
  7190. }
  7191. for (index = 0; index < this.meshes.length; index++) {
  7192. var mesh = this.meshes[index];
  7193. if (!mesh.isReady()) {
  7194. return false;
  7195. }
  7196. var mat = mesh.material;
  7197. if (mat) {
  7198. if (!mat.isReady(mesh)) {
  7199. return false;
  7200. }
  7201. }
  7202. }
  7203. return true;
  7204. };
  7205. Scene.prototype.resetCachedMaterial = function () {
  7206. this._cachedMaterial = null;
  7207. };
  7208. Scene.prototype.registerBeforeRender = function (func) {
  7209. this._onBeforeRenderCallbacks.push(func);
  7210. };
  7211. Scene.prototype.unregisterBeforeRender = function (func) {
  7212. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7213. if (index > -1) {
  7214. this._onBeforeRenderCallbacks.splice(index, 1);
  7215. }
  7216. };
  7217. Scene.prototype.registerAfterRender = function (func) {
  7218. this._onAfterRenderCallbacks.push(func);
  7219. };
  7220. Scene.prototype.unregisterAfterRender = function (func) {
  7221. var index = this._onAfterRenderCallbacks.indexOf(func);
  7222. if (index > -1) {
  7223. this._onAfterRenderCallbacks.splice(index, 1);
  7224. }
  7225. };
  7226. Scene.prototype._addPendingData = function (data) {
  7227. this._pendingData.push(data);
  7228. };
  7229. Scene.prototype._removePendingData = function (data) {
  7230. var index = this._pendingData.indexOf(data);
  7231. if (index !== -1) {
  7232. this._pendingData.splice(index, 1);
  7233. }
  7234. };
  7235. Scene.prototype.getWaitingItemsCount = function () {
  7236. return this._pendingData.length;
  7237. };
  7238. Scene.prototype.executeWhenReady = function (func) {
  7239. var _this = this;
  7240. this._onReadyCallbacks.push(func);
  7241. if (this._executeWhenReadyTimeoutId !== -1) {
  7242. return;
  7243. }
  7244. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7245. _this._checkIsReady();
  7246. }, 150);
  7247. };
  7248. Scene.prototype._checkIsReady = function () {
  7249. var _this = this;
  7250. if (this.isReady()) {
  7251. this._onReadyCallbacks.forEach(function (func) {
  7252. func();
  7253. });
  7254. this._onReadyCallbacks = [];
  7255. this._executeWhenReadyTimeoutId = -1;
  7256. return;
  7257. }
  7258. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7259. _this._checkIsReady();
  7260. }, 150);
  7261. };
  7262. // Animations
  7263. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7264. if (speedRatio === undefined) {
  7265. speedRatio = 1.0;
  7266. }
  7267. this.stopAnimation(target);
  7268. if (!animatable) {
  7269. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7270. }
  7271. // Local animations
  7272. if (target.animations) {
  7273. animatable.appendAnimations(target, target.animations);
  7274. }
  7275. // Children animations
  7276. if (target.getAnimatables) {
  7277. var animatables = target.getAnimatables();
  7278. for (var index = 0; index < animatables.length; index++) {
  7279. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7280. }
  7281. }
  7282. return animatable;
  7283. };
  7284. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7285. if (speedRatio === undefined) {
  7286. speedRatio = 1.0;
  7287. }
  7288. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7289. return animatable;
  7290. };
  7291. Scene.prototype.getAnimatableByTarget = function (target) {
  7292. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7293. if (this._activeAnimatables[index].target === target) {
  7294. return this._activeAnimatables[index];
  7295. }
  7296. }
  7297. return null;
  7298. };
  7299. Scene.prototype.stopAnimation = function (target) {
  7300. var animatable = this.getAnimatableByTarget(target);
  7301. if (animatable) {
  7302. animatable.stop();
  7303. }
  7304. };
  7305. Scene.prototype._animate = function () {
  7306. if (!this.animationsEnabled) {
  7307. return;
  7308. }
  7309. if (!this._animationStartDate) {
  7310. this._animationStartDate = BABYLON.Tools.Now;
  7311. }
  7312. // Getting time
  7313. var now = BABYLON.Tools.Now;
  7314. var delay = now - this._animationStartDate;
  7315. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7316. if (!this._activeAnimatables[index]._animate(delay)) {
  7317. this._activeAnimatables.splice(index, 1);
  7318. index--;
  7319. }
  7320. }
  7321. };
  7322. // Matrix
  7323. Scene.prototype.getViewMatrix = function () {
  7324. return this._viewMatrix;
  7325. };
  7326. Scene.prototype.getProjectionMatrix = function () {
  7327. return this._projectionMatrix;
  7328. };
  7329. Scene.prototype.getTransformMatrix = function () {
  7330. return this._transformMatrix;
  7331. };
  7332. Scene.prototype.setTransformMatrix = function (view, projection) {
  7333. this._viewMatrix = view;
  7334. this._projectionMatrix = projection;
  7335. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7336. };
  7337. // Methods
  7338. Scene.prototype.setActiveCameraByID = function (id) {
  7339. var camera = this.getCameraByID(id);
  7340. if (camera) {
  7341. this.activeCamera = camera;
  7342. return camera;
  7343. }
  7344. return null;
  7345. };
  7346. Scene.prototype.setActiveCameraByName = function (name) {
  7347. var camera = this.getCameraByName(name);
  7348. if (camera) {
  7349. this.activeCamera = camera;
  7350. return camera;
  7351. }
  7352. return null;
  7353. };
  7354. Scene.prototype.getMaterialByID = function (id) {
  7355. for (var index = 0; index < this.materials.length; index++) {
  7356. if (this.materials[index].id === id) {
  7357. return this.materials[index];
  7358. }
  7359. }
  7360. return null;
  7361. };
  7362. Scene.prototype.getMaterialByName = function (name) {
  7363. for (var index = 0; index < this.materials.length; index++) {
  7364. if (this.materials[index].name === name) {
  7365. return this.materials[index];
  7366. }
  7367. }
  7368. return null;
  7369. };
  7370. Scene.prototype.getCameraByID = function (id) {
  7371. for (var index = 0; index < this.cameras.length; index++) {
  7372. if (this.cameras[index].id === id) {
  7373. return this.cameras[index];
  7374. }
  7375. }
  7376. return null;
  7377. };
  7378. Scene.prototype.getCameraByName = function (name) {
  7379. for (var index = 0; index < this.cameras.length; index++) {
  7380. if (this.cameras[index].name === name) {
  7381. return this.cameras[index];
  7382. }
  7383. }
  7384. return null;
  7385. };
  7386. Scene.prototype.getLightByName = function (name) {
  7387. for (var index = 0; index < this.lights.length; index++) {
  7388. if (this.lights[index].name === name) {
  7389. return this.lights[index];
  7390. }
  7391. }
  7392. return null;
  7393. };
  7394. Scene.prototype.getLightByID = function (id) {
  7395. for (var index = 0; index < this.lights.length; index++) {
  7396. if (this.lights[index].id === id) {
  7397. return this.lights[index];
  7398. }
  7399. }
  7400. return null;
  7401. };
  7402. Scene.prototype.getGeometryByID = function (id) {
  7403. for (var index = 0; index < this._geometries.length; index++) {
  7404. if (this._geometries[index].id === id) {
  7405. return this._geometries[index];
  7406. }
  7407. }
  7408. return null;
  7409. };
  7410. Scene.prototype.pushGeometry = function (geometry, force) {
  7411. if (!force && this.getGeometryByID(geometry.id)) {
  7412. return false;
  7413. }
  7414. this._geometries.push(geometry);
  7415. return true;
  7416. };
  7417. Scene.prototype.getGeometries = function () {
  7418. return this._geometries;
  7419. };
  7420. Scene.prototype.getMeshByID = function (id) {
  7421. for (var index = 0; index < this.meshes.length; index++) {
  7422. if (this.meshes[index].id === id) {
  7423. return this.meshes[index];
  7424. }
  7425. }
  7426. return null;
  7427. };
  7428. Scene.prototype.getLastMeshByID = function (id) {
  7429. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7430. if (this.meshes[index].id === id) {
  7431. return this.meshes[index];
  7432. }
  7433. }
  7434. return null;
  7435. };
  7436. Scene.prototype.getLastEntryByID = function (id) {
  7437. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7438. if (this.meshes[index].id === id) {
  7439. return this.meshes[index];
  7440. }
  7441. }
  7442. for (index = this.cameras.length - 1; index >= 0; index--) {
  7443. if (this.cameras[index].id === id) {
  7444. return this.cameras[index];
  7445. }
  7446. }
  7447. for (index = this.lights.length - 1; index >= 0; index--) {
  7448. if (this.lights[index].id === id) {
  7449. return this.lights[index];
  7450. }
  7451. }
  7452. return null;
  7453. };
  7454. Scene.prototype.getMeshByName = function (name) {
  7455. for (var index = 0; index < this.meshes.length; index++) {
  7456. if (this.meshes[index].name === name) {
  7457. return this.meshes[index];
  7458. }
  7459. }
  7460. return null;
  7461. };
  7462. Scene.prototype.getLastSkeletonByID = function (id) {
  7463. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7464. if (this.skeletons[index].id === id) {
  7465. return this.skeletons[index];
  7466. }
  7467. }
  7468. return null;
  7469. };
  7470. Scene.prototype.getSkeletonById = function (id) {
  7471. for (var index = 0; index < this.skeletons.length; index++) {
  7472. if (this.skeletons[index].id === id) {
  7473. return this.skeletons[index];
  7474. }
  7475. }
  7476. return null;
  7477. };
  7478. Scene.prototype.getSkeletonByName = function (name) {
  7479. for (var index = 0; index < this.skeletons.length; index++) {
  7480. if (this.skeletons[index].name === name) {
  7481. return this.skeletons[index];
  7482. }
  7483. }
  7484. return null;
  7485. };
  7486. Scene.prototype.isActiveMesh = function (mesh) {
  7487. return (this._activeMeshes.indexOf(mesh) !== -1);
  7488. };
  7489. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7490. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7491. var material = subMesh.getMaterial();
  7492. if (mesh.showSubMeshesBoundingBox) {
  7493. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7494. }
  7495. if (material) {
  7496. // Render targets
  7497. if (material.getRenderTargetTextures) {
  7498. if (this._processedMaterials.indexOf(material) === -1) {
  7499. this._processedMaterials.push(material);
  7500. this._renderTargets.concat(material.getRenderTargetTextures());
  7501. }
  7502. }
  7503. // Dispatch
  7504. this._activeVertices += subMesh.indexCount;
  7505. this._renderingManager.dispatch(subMesh);
  7506. }
  7507. }
  7508. };
  7509. Scene.prototype._evaluateActiveMeshes = function () {
  7510. this._activeMeshes.reset();
  7511. this._renderingManager.reset();
  7512. this._processedMaterials.reset();
  7513. this._activeParticleSystems.reset();
  7514. this._activeSkeletons.reset();
  7515. this._boundingBoxRenderer.reset();
  7516. if (!this._frustumPlanes) {
  7517. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7518. } else {
  7519. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7520. }
  7521. // Meshes
  7522. var meshes;
  7523. var len;
  7524. if (this._selectionOctree) {
  7525. var selection = this._selectionOctree.select(this._frustumPlanes);
  7526. meshes = selection.data;
  7527. len = selection.length;
  7528. } else {
  7529. len = this.meshes.length;
  7530. meshes = this.meshes;
  7531. }
  7532. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7533. var mesh = meshes[meshIndex];
  7534. if (mesh.isBlocked) {
  7535. continue;
  7536. }
  7537. this._totalVertices += mesh.getTotalVertices();
  7538. if (!mesh.isReady()) {
  7539. continue;
  7540. }
  7541. mesh.computeWorldMatrix();
  7542. // Intersections
  7543. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7544. this._meshesForIntersections.pushNoDuplicate(mesh);
  7545. }
  7546. // Switch to current LOD
  7547. var meshLOD = mesh.getLOD(this.activeCamera);
  7548. if (!meshLOD) {
  7549. continue;
  7550. }
  7551. mesh._preActivate();
  7552. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7553. this._activeMeshes.push(mesh);
  7554. mesh._activate(this._renderId);
  7555. this._activeMesh(meshLOD);
  7556. }
  7557. }
  7558. // Particle systems
  7559. var beforeParticlesDate = BABYLON.Tools.Now;
  7560. if (this.particlesEnabled) {
  7561. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7562. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7563. var particleSystem = this.particleSystems[particleIndex];
  7564. if (!particleSystem.isStarted()) {
  7565. continue;
  7566. }
  7567. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7568. this._activeParticleSystems.push(particleSystem);
  7569. particleSystem.animate();
  7570. }
  7571. }
  7572. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7573. }
  7574. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7575. };
  7576. Scene.prototype._activeMesh = function (mesh) {
  7577. if (mesh.skeleton && this.skeletonsEnabled) {
  7578. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7579. }
  7580. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7581. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7582. }
  7583. if (mesh && mesh.subMeshes) {
  7584. // Submeshes Octrees
  7585. var len;
  7586. var subMeshes;
  7587. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7588. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7589. len = intersections.length;
  7590. subMeshes = intersections.data;
  7591. } else {
  7592. subMeshes = mesh.subMeshes;
  7593. len = subMeshes.length;
  7594. }
  7595. for (var subIndex = 0; subIndex < len; subIndex++) {
  7596. var subMesh = subMeshes[subIndex];
  7597. this._evaluateSubMesh(subMesh, mesh);
  7598. }
  7599. }
  7600. };
  7601. Scene.prototype.updateTransformMatrix = function (force) {
  7602. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7603. };
  7604. Scene.prototype._renderForCamera = function (camera) {
  7605. var engine = this._engine;
  7606. this.activeCamera = camera;
  7607. if (!this.activeCamera)
  7608. throw new Error("Active camera not set");
  7609. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7610. // Viewport
  7611. engine.setViewport(this.activeCamera.viewport);
  7612. // Camera
  7613. this._renderId++;
  7614. this.updateTransformMatrix();
  7615. if (this.beforeCameraRender) {
  7616. this.beforeCameraRender(this.activeCamera);
  7617. }
  7618. // Meshes
  7619. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7620. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7621. this._evaluateActiveMeshes();
  7622. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7623. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7624. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7625. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7626. skeleton.prepare();
  7627. this._activeBones += skeleton.bones.length;
  7628. }
  7629. // Render targets
  7630. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7631. if (this.renderTargetsEnabled) {
  7632. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7633. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7634. var renderTarget = this._renderTargets.data[renderIndex];
  7635. if (renderTarget._shouldRender()) {
  7636. this._renderId++;
  7637. renderTarget.render();
  7638. }
  7639. }
  7640. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7641. this._renderId++;
  7642. }
  7643. if (this._renderTargets.length > 0) {
  7644. engine.restoreDefaultFramebuffer();
  7645. }
  7646. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7647. // Prepare Frame
  7648. this.postProcessManager._prepareFrame();
  7649. var beforeRenderDate = BABYLON.Tools.Now;
  7650. // Backgrounds
  7651. if (this.layers.length) {
  7652. engine.setDepthBuffer(false);
  7653. var layerIndex;
  7654. var layer;
  7655. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7656. layer = this.layers[layerIndex];
  7657. if (layer.isBackground) {
  7658. layer.render();
  7659. }
  7660. }
  7661. engine.setDepthBuffer(true);
  7662. }
  7663. // Render
  7664. BABYLON.Tools.StartPerformanceCounter("Main render");
  7665. this._renderingManager.render(null, null, true, true);
  7666. BABYLON.Tools.EndPerformanceCounter("Main render");
  7667. // Bounding boxes
  7668. this._boundingBoxRenderer.render();
  7669. // Lens flares
  7670. if (this.lensFlaresEnabled) {
  7671. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7672. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7673. this.lensFlareSystems[lensFlareSystemIndex].render();
  7674. }
  7675. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7676. }
  7677. // Foregrounds
  7678. if (this.layers.length) {
  7679. engine.setDepthBuffer(false);
  7680. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7681. layer = this.layers[layerIndex];
  7682. if (!layer.isBackground) {
  7683. layer.render();
  7684. }
  7685. }
  7686. engine.setDepthBuffer(true);
  7687. }
  7688. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7689. // Finalize frame
  7690. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7691. // Update camera
  7692. this.activeCamera._updateFromScene();
  7693. // Reset some special arrays
  7694. this._renderTargets.reset();
  7695. if (this.afterCameraRender) {
  7696. this.afterCameraRender(this.activeCamera);
  7697. }
  7698. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7699. };
  7700. Scene.prototype._processSubCameras = function (camera) {
  7701. if (camera.subCameras.length === 0) {
  7702. this._renderForCamera(camera);
  7703. return;
  7704. }
  7705. for (var index = 0; index < camera.subCameras.length; index++) {
  7706. this._renderForCamera(camera.subCameras[index]);
  7707. }
  7708. this.activeCamera = camera;
  7709. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7710. // Update camera
  7711. this.activeCamera._updateFromScene();
  7712. };
  7713. Scene.prototype._checkIntersections = function () {
  7714. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7715. var sourceMesh = this._meshesForIntersections.data[index];
  7716. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7717. var action = sourceMesh.actionManager.actions[actionIndex];
  7718. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7719. var otherMesh = action.getTriggerParameter();
  7720. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7721. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7722. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7723. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7724. sourceMesh._intersectionsInProgress.push(otherMesh);
  7725. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7726. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7727. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7728. if (indexOfOther > -1) {
  7729. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7730. }
  7731. }
  7732. }
  7733. }
  7734. }
  7735. };
  7736. Scene.prototype.render = function () {
  7737. var startDate = BABYLON.Tools.Now;
  7738. this._particlesDuration = 0;
  7739. this._spritesDuration = 0;
  7740. this._activeParticles = 0;
  7741. this._renderDuration = 0;
  7742. this._renderTargetsDuration = 0;
  7743. this._evaluateActiveMeshesDuration = 0;
  7744. this._totalVertices = 0;
  7745. this._activeVertices = 0;
  7746. this._activeBones = 0;
  7747. this.getEngine().resetDrawCalls();
  7748. this._meshesForIntersections.reset();
  7749. this.resetCachedMaterial();
  7750. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7751. // Actions
  7752. if (this.actionManager) {
  7753. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7754. }
  7755. // Before render
  7756. if (this.beforeRender) {
  7757. this.beforeRender();
  7758. }
  7759. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7760. this._onBeforeRenderCallbacks[callbackIndex]();
  7761. }
  7762. // Animations
  7763. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7764. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7765. this._animate();
  7766. // Physics
  7767. if (this._physicsEngine) {
  7768. BABYLON.Tools.StartPerformanceCounter("Physics");
  7769. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7770. BABYLON.Tools.EndPerformanceCounter("Physics");
  7771. }
  7772. // Customs render targets
  7773. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7774. var engine = this.getEngine();
  7775. if (this.renderTargetsEnabled) {
  7776. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7777. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7778. var renderTarget = this.customRenderTargets[customIndex];
  7779. if (renderTarget._shouldRender()) {
  7780. this._renderId++;
  7781. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7782. if (!this.activeCamera)
  7783. throw new Error("Active camera not set");
  7784. // Viewport
  7785. engine.setViewport(this.activeCamera.viewport);
  7786. // Camera
  7787. this.updateTransformMatrix();
  7788. renderTarget.render();
  7789. }
  7790. }
  7791. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7792. this._renderId++;
  7793. }
  7794. if (this.customRenderTargets.length > 0) {
  7795. engine.restoreDefaultFramebuffer();
  7796. }
  7797. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7798. // Procedural textures
  7799. if (this.proceduralTexturesEnabled) {
  7800. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7801. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7802. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7803. if (proceduralTexture._shouldRender()) {
  7804. proceduralTexture.render();
  7805. }
  7806. }
  7807. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7808. }
  7809. // Clear
  7810. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7811. // Shadows
  7812. if (this.shadowsEnabled) {
  7813. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7814. var light = this.lights[lightIndex];
  7815. var shadowGenerator = light.getShadowGenerator();
  7816. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7817. this._renderTargets.push(shadowGenerator.getShadowMap());
  7818. }
  7819. }
  7820. }
  7821. // RenderPipeline
  7822. this.postProcessRenderPipelineManager.update();
  7823. // Multi-cameras?
  7824. if (this.activeCameras.length > 0) {
  7825. var currentRenderId = this._renderId;
  7826. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7827. this._renderId = currentRenderId;
  7828. this._processSubCameras(this.activeCameras[cameraIndex]);
  7829. }
  7830. } else {
  7831. if (!this.activeCamera) {
  7832. throw new Error("No camera defined");
  7833. }
  7834. this._processSubCameras(this.activeCamera);
  7835. }
  7836. // Intersection checks
  7837. this._checkIntersections();
  7838. // Update the audio listener attached to the camera
  7839. this._updateAudioParameters();
  7840. // After render
  7841. if (this.afterRender) {
  7842. this.afterRender();
  7843. }
  7844. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7845. this._onAfterRenderCallbacks[callbackIndex]();
  7846. }
  7847. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7848. this._toBeDisposed.data[index].dispose();
  7849. this._toBeDisposed[index] = null;
  7850. }
  7851. this._toBeDisposed.reset();
  7852. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7853. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7854. };
  7855. Scene.prototype._updateAudioParameters = function () {
  7856. var listeningCamera;
  7857. var audioEngine = this._engine.getAudioEngine();
  7858. if (this.activeCameras.length > 0) {
  7859. listeningCamera = this.activeCameras[0];
  7860. } else {
  7861. listeningCamera = this.activeCamera;
  7862. }
  7863. if (listeningCamera && audioEngine.canUseWebAudio) {
  7864. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7865. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7866. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7867. cameraDirection.normalize();
  7868. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7869. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7870. var sound = this.mainSoundTrack.soundCollection[i];
  7871. if (sound.useBabylonJSAttenuation) {
  7872. sound.updateDistanceFromListener();
  7873. }
  7874. }
  7875. for (var i = 0; i < this.soundTracks.length; i++) {
  7876. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7877. var sound = this.soundTracks[i].soundCollection[j];
  7878. if (sound.useBabylonJSAttenuation) {
  7879. sound.updateDistanceFromListener();
  7880. }
  7881. }
  7882. }
  7883. }
  7884. };
  7885. Scene.prototype.dispose = function () {
  7886. this.beforeRender = null;
  7887. this.afterRender = null;
  7888. this.skeletons = [];
  7889. this._boundingBoxRenderer.dispose();
  7890. // Debug layer
  7891. this.debugLayer.hide();
  7892. // Events
  7893. if (this.onDispose) {
  7894. this.onDispose();
  7895. }
  7896. this._onBeforeRenderCallbacks = [];
  7897. this._onAfterRenderCallbacks = [];
  7898. this.detachControl();
  7899. // Detach cameras
  7900. var canvas = this._engine.getRenderingCanvas();
  7901. var index;
  7902. for (index = 0; index < this.cameras.length; index++) {
  7903. this.cameras[index].detachControl(canvas);
  7904. }
  7905. while (this.lights.length) {
  7906. this.lights[0].dispose();
  7907. }
  7908. while (this.meshes.length) {
  7909. this.meshes[0].dispose(true);
  7910. }
  7911. while (this.cameras.length) {
  7912. this.cameras[0].dispose();
  7913. }
  7914. while (this.materials.length) {
  7915. this.materials[0].dispose();
  7916. }
  7917. while (this.particleSystems.length) {
  7918. this.particleSystems[0].dispose();
  7919. }
  7920. while (this.spriteManagers.length) {
  7921. this.spriteManagers[0].dispose();
  7922. }
  7923. while (this.layers.length) {
  7924. this.layers[0].dispose();
  7925. }
  7926. while (this.textures.length) {
  7927. this.textures[0].dispose();
  7928. }
  7929. // Post-processes
  7930. this.postProcessManager.dispose();
  7931. // Physics
  7932. if (this._physicsEngine) {
  7933. this.disablePhysicsEngine();
  7934. }
  7935. // Remove from engine
  7936. index = this._engine.scenes.indexOf(this);
  7937. if (index > -1) {
  7938. this._engine.scenes.splice(index, 1);
  7939. }
  7940. this._engine.wipeCaches();
  7941. };
  7942. // Collisions
  7943. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7944. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7945. position.divideToRef(collider.radius, this._scaledPosition);
  7946. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7947. collider.retry = 0;
  7948. collider.initialVelocity = this._scaledVelocity;
  7949. collider.initialPosition = this._scaledPosition;
  7950. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7951. finalPosition.multiplyInPlace(collider.radius);
  7952. };
  7953. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7954. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7955. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7956. if (collider.retry >= maximumRetry) {
  7957. finalPosition.copyFrom(position);
  7958. return;
  7959. }
  7960. collider._initialize(position, velocity, closeDistance);
  7961. for (var index = 0; index < this.meshes.length; index++) {
  7962. var mesh = this.meshes[index];
  7963. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7964. mesh._checkCollision(collider);
  7965. }
  7966. }
  7967. if (!collider.collisionFound) {
  7968. position.addToRef(velocity, finalPosition);
  7969. return;
  7970. }
  7971. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  7972. collider._getResponse(position, velocity);
  7973. }
  7974. if (velocity.length() <= closeDistance) {
  7975. finalPosition.copyFrom(position);
  7976. return;
  7977. }
  7978. collider.retry++;
  7979. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7980. };
  7981. // Octrees
  7982. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7983. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7984. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7985. if (!this._selectionOctree) {
  7986. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7987. }
  7988. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7989. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7990. for (var index = 0; index < this.meshes.length; index++) {
  7991. var mesh = this.meshes[index];
  7992. mesh.computeWorldMatrix(true);
  7993. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7994. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7995. BABYLON.Tools.CheckExtends(minBox, min, max);
  7996. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7997. }
  7998. // Update octree
  7999. this._selectionOctree.update(min, max, this.meshes);
  8000. return this._selectionOctree;
  8001. };
  8002. // Picking
  8003. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8004. var engine = this._engine;
  8005. if (!camera) {
  8006. if (!this.activeCamera)
  8007. throw new Error("Active camera not set");
  8008. camera = this.activeCamera;
  8009. }
  8010. var cameraViewport = camera.viewport;
  8011. var viewport = cameraViewport.toGlobal(engine);
  8012. // Moving coordinates to local viewport world
  8013. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8014. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8015. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8016. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8017. };
  8018. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8019. var pickingInfo = null;
  8020. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8021. var mesh = this.meshes[meshIndex];
  8022. if (predicate) {
  8023. if (!predicate(mesh)) {
  8024. continue;
  8025. }
  8026. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8027. continue;
  8028. }
  8029. var world = mesh.getWorldMatrix();
  8030. var ray = rayFunction(world);
  8031. var result = mesh.intersects(ray, fastCheck);
  8032. if (!result || !result.hit)
  8033. continue;
  8034. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8035. continue;
  8036. pickingInfo = result;
  8037. if (fastCheck) {
  8038. break;
  8039. }
  8040. }
  8041. return pickingInfo || new BABYLON.PickingInfo();
  8042. };
  8043. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8044. var _this = this;
  8045. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8046. /// <param name="x">X position on screen</param>
  8047. /// <param name="y">Y position on screen</param>
  8048. /// <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>
  8049. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8050. /// <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>
  8051. return this._internalPick(function (world) {
  8052. return _this.createPickingRay(x, y, world, camera);
  8053. }, predicate, fastCheck);
  8054. };
  8055. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8056. var _this = this;
  8057. return this._internalPick(function (world) {
  8058. if (!_this._pickWithRayInverseMatrix) {
  8059. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8060. }
  8061. world.invertToRef(_this._pickWithRayInverseMatrix);
  8062. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8063. }, predicate, fastCheck);
  8064. };
  8065. Scene.prototype.setPointerOverMesh = function (mesh) {
  8066. if (this._pointerOverMesh === mesh) {
  8067. return;
  8068. }
  8069. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8070. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8071. }
  8072. this._pointerOverMesh = mesh;
  8073. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8074. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8075. }
  8076. };
  8077. Scene.prototype.getPointerOverMesh = function () {
  8078. return this._pointerOverMesh;
  8079. };
  8080. // Physics
  8081. Scene.prototype.getPhysicsEngine = function () {
  8082. return this._physicsEngine;
  8083. };
  8084. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8085. if (this._physicsEngine) {
  8086. return true;
  8087. }
  8088. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8089. if (!this._physicsEngine.isSupported()) {
  8090. this._physicsEngine = null;
  8091. return false;
  8092. }
  8093. this._physicsEngine._initialize(gravity);
  8094. return true;
  8095. };
  8096. Scene.prototype.disablePhysicsEngine = function () {
  8097. if (!this._physicsEngine) {
  8098. return;
  8099. }
  8100. this._physicsEngine.dispose();
  8101. this._physicsEngine = undefined;
  8102. };
  8103. Scene.prototype.isPhysicsEnabled = function () {
  8104. return this._physicsEngine !== undefined;
  8105. };
  8106. Scene.prototype.setGravity = function (gravity) {
  8107. if (!this._physicsEngine) {
  8108. return;
  8109. }
  8110. this._physicsEngine._setGravity(gravity);
  8111. };
  8112. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8113. if (parts.parts) {
  8114. options = parts;
  8115. parts = parts.parts;
  8116. }
  8117. if (!this._physicsEngine) {
  8118. return null;
  8119. }
  8120. for (var index = 0; index < parts.length; index++) {
  8121. var mesh = parts[index].mesh;
  8122. mesh._physicImpostor = parts[index].impostor;
  8123. mesh._physicsMass = options.mass / parts.length;
  8124. mesh._physicsFriction = options.friction;
  8125. mesh._physicRestitution = options.restitution;
  8126. }
  8127. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8128. };
  8129. //ANY
  8130. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8131. for (var index = 0; index < compound.parts.length; index++) {
  8132. var mesh = compound.parts[index].mesh;
  8133. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8134. this._physicsEngine._unregisterMesh(mesh);
  8135. }
  8136. };
  8137. // Tags
  8138. Scene.prototype._getByTags = function (list, tagsQuery) {
  8139. if (tagsQuery === undefined) {
  8140. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8141. return list;
  8142. }
  8143. var listByTags = [];
  8144. for (var i in list) {
  8145. var item = list[i];
  8146. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8147. listByTags.push(item);
  8148. }
  8149. }
  8150. return listByTags;
  8151. };
  8152. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8153. return this._getByTags(this.meshes, tagsQuery);
  8154. };
  8155. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8156. return this._getByTags(this.cameras, tagsQuery);
  8157. };
  8158. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8159. return this._getByTags(this.lights, tagsQuery);
  8160. };
  8161. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8162. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8163. };
  8164. Scene.FOGMODE_NONE = 0;
  8165. Scene.FOGMODE_EXP = 1;
  8166. Scene.FOGMODE_EXP2 = 2;
  8167. Scene.FOGMODE_LINEAR = 3;
  8168. Scene.MinDeltaTime = 1.0;
  8169. Scene.MaxDeltaTime = 1000.0;
  8170. return Scene;
  8171. })();
  8172. BABYLON.Scene = Scene;
  8173. })(BABYLON || (BABYLON = {}));
  8174. //# sourceMappingURL=babylon.scene.js.map
  8175. var BABYLON;
  8176. (function (BABYLON) {
  8177. var VertexBuffer = (function () {
  8178. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8179. if (engine instanceof BABYLON.Mesh) {
  8180. this._engine = engine.getScene().getEngine();
  8181. } else {
  8182. this._engine = engine;
  8183. }
  8184. this._updatable = updatable;
  8185. this._data = data;
  8186. if (!postponeInternalCreation) {
  8187. this.create();
  8188. }
  8189. this._kind = kind;
  8190. if (stride) {
  8191. this._strideSize = stride;
  8192. return;
  8193. }
  8194. switch (kind) {
  8195. case VertexBuffer.PositionKind:
  8196. this._strideSize = 3;
  8197. break;
  8198. case VertexBuffer.NormalKind:
  8199. this._strideSize = 3;
  8200. break;
  8201. case VertexBuffer.UVKind:
  8202. this._strideSize = 2;
  8203. break;
  8204. case VertexBuffer.UV2Kind:
  8205. this._strideSize = 2;
  8206. break;
  8207. case VertexBuffer.ColorKind:
  8208. this._strideSize = 4;
  8209. break;
  8210. case VertexBuffer.MatricesIndicesKind:
  8211. this._strideSize = 4;
  8212. break;
  8213. case VertexBuffer.MatricesWeightsKind:
  8214. this._strideSize = 4;
  8215. break;
  8216. }
  8217. }
  8218. // Properties
  8219. VertexBuffer.prototype.isUpdatable = function () {
  8220. return this._updatable;
  8221. };
  8222. VertexBuffer.prototype.getData = function () {
  8223. return this._data;
  8224. };
  8225. VertexBuffer.prototype.getBuffer = function () {
  8226. return this._buffer;
  8227. };
  8228. VertexBuffer.prototype.getStrideSize = function () {
  8229. return this._strideSize;
  8230. };
  8231. // Methods
  8232. VertexBuffer.prototype.create = function (data) {
  8233. if (!data && this._buffer) {
  8234. return;
  8235. }
  8236. data = data || this._data;
  8237. if (!this._buffer) {
  8238. if (this._updatable) {
  8239. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8240. } else {
  8241. this._buffer = this._engine.createVertexBuffer(data);
  8242. }
  8243. }
  8244. if (this._updatable) {
  8245. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8246. this._data = data;
  8247. }
  8248. };
  8249. VertexBuffer.prototype.update = function (data) {
  8250. this.create(data);
  8251. };
  8252. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8253. if (!this._buffer) {
  8254. return;
  8255. }
  8256. if (this._updatable) {
  8257. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8258. this._data = null;
  8259. }
  8260. };
  8261. VertexBuffer.prototype.dispose = function () {
  8262. if (!this._buffer) {
  8263. return;
  8264. }
  8265. if (this._engine._releaseBuffer(this._buffer)) {
  8266. this._buffer = null;
  8267. }
  8268. };
  8269. Object.defineProperty(VertexBuffer, "PositionKind", {
  8270. get: function () {
  8271. return VertexBuffer._PositionKind;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(VertexBuffer, "NormalKind", {
  8277. get: function () {
  8278. return VertexBuffer._NormalKind;
  8279. },
  8280. enumerable: true,
  8281. configurable: true
  8282. });
  8283. Object.defineProperty(VertexBuffer, "UVKind", {
  8284. get: function () {
  8285. return VertexBuffer._UVKind;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8291. get: function () {
  8292. return VertexBuffer._UV2Kind;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(VertexBuffer, "ColorKind", {
  8298. get: function () {
  8299. return VertexBuffer._ColorKind;
  8300. },
  8301. enumerable: true,
  8302. configurable: true
  8303. });
  8304. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8305. get: function () {
  8306. return VertexBuffer._MatricesIndicesKind;
  8307. },
  8308. enumerable: true,
  8309. configurable: true
  8310. });
  8311. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8312. get: function () {
  8313. return VertexBuffer._MatricesWeightsKind;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. VertexBuffer._PositionKind = "position";
  8319. VertexBuffer._NormalKind = "normal";
  8320. VertexBuffer._UVKind = "uv";
  8321. VertexBuffer._UV2Kind = "uv2";
  8322. VertexBuffer._ColorKind = "color";
  8323. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8324. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8325. return VertexBuffer;
  8326. })();
  8327. BABYLON.VertexBuffer = VertexBuffer;
  8328. })(BABYLON || (BABYLON = {}));
  8329. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8330. var BABYLON;
  8331. (function (BABYLON) {
  8332. var AbstractMesh = (function (_super) {
  8333. __extends(AbstractMesh, _super);
  8334. function AbstractMesh(name, scene) {
  8335. _super.call(this, name, scene);
  8336. // Properties
  8337. this.position = new BABYLON.Vector3(0, 0, 0);
  8338. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8339. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8340. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8341. this.visibility = 1.0;
  8342. this.alphaIndex = Number.MAX_VALUE;
  8343. this.infiniteDistance = false;
  8344. this.isVisible = true;
  8345. this.isPickable = true;
  8346. this.showBoundingBox = false;
  8347. this.showSubMeshesBoundingBox = false;
  8348. this.onDispose = null;
  8349. this.checkCollisions = false;
  8350. this.isBlocker = false;
  8351. this.renderingGroupId = 0;
  8352. this.receiveShadows = false;
  8353. this.renderOutline = false;
  8354. this.outlineColor = BABYLON.Color3.Red();
  8355. this.outlineWidth = 0.02;
  8356. this.renderOverlay = false;
  8357. this.overlayColor = BABYLON.Color3.Red();
  8358. this.overlayAlpha = 0.5;
  8359. this.hasVertexAlpha = false;
  8360. this.useVertexColors = true;
  8361. this.applyFog = true;
  8362. this.useOctreeForRenderingSelection = true;
  8363. this.useOctreeForPicking = true;
  8364. this.useOctreeForCollisions = true;
  8365. this.layerMask = 0xFFFFFFFF;
  8366. // Physics
  8367. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8368. // Collisions
  8369. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8370. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8371. this._collider = new BABYLON.Collider();
  8372. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8373. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8374. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8375. // Cache
  8376. this._localScaling = BABYLON.Matrix.Zero();
  8377. this._localRotation = BABYLON.Matrix.Zero();
  8378. this._localTranslation = BABYLON.Matrix.Zero();
  8379. this._localBillboard = BABYLON.Matrix.Zero();
  8380. this._localPivotScaling = BABYLON.Matrix.Zero();
  8381. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8382. this._localWorld = BABYLON.Matrix.Zero();
  8383. this._worldMatrix = BABYLON.Matrix.Zero();
  8384. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8385. this._absolutePosition = BABYLON.Vector3.Zero();
  8386. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8387. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8388. this._isDirty = false;
  8389. this._pivotMatrix = BABYLON.Matrix.Identity();
  8390. this._isDisposed = false;
  8391. this._renderId = 0;
  8392. this._intersectionsInProgress = new Array();
  8393. this._onAfterWorldMatrixUpdate = new Array();
  8394. scene.meshes.push(this);
  8395. }
  8396. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8397. get: function () {
  8398. return AbstractMesh._BILLBOARDMODE_NONE;
  8399. },
  8400. enumerable: true,
  8401. configurable: true
  8402. });
  8403. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8404. get: function () {
  8405. return AbstractMesh._BILLBOARDMODE_X;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8411. get: function () {
  8412. return AbstractMesh._BILLBOARDMODE_Y;
  8413. },
  8414. enumerable: true,
  8415. configurable: true
  8416. });
  8417. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8418. get: function () {
  8419. return AbstractMesh._BILLBOARDMODE_Z;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8425. get: function () {
  8426. return AbstractMesh._BILLBOARDMODE_ALL;
  8427. },
  8428. enumerable: true,
  8429. configurable: true
  8430. });
  8431. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8432. // Methods
  8433. get: function () {
  8434. return false;
  8435. },
  8436. enumerable: true,
  8437. configurable: true
  8438. });
  8439. AbstractMesh.prototype.getLOD = function (camera) {
  8440. return this;
  8441. };
  8442. AbstractMesh.prototype.getTotalVertices = function () {
  8443. return 0;
  8444. };
  8445. AbstractMesh.prototype.getIndices = function () {
  8446. return null;
  8447. };
  8448. AbstractMesh.prototype.getVerticesData = function (kind) {
  8449. return null;
  8450. };
  8451. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8452. return false;
  8453. };
  8454. AbstractMesh.prototype.getBoundingInfo = function () {
  8455. if (this._masterMesh) {
  8456. return this._masterMesh.getBoundingInfo();
  8457. }
  8458. if (!this._boundingInfo) {
  8459. this._updateBoundingInfo();
  8460. }
  8461. return this._boundingInfo;
  8462. };
  8463. AbstractMesh.prototype._preActivate = function () {
  8464. };
  8465. AbstractMesh.prototype._activate = function (renderId) {
  8466. this._renderId = renderId;
  8467. };
  8468. AbstractMesh.prototype.getWorldMatrix = function () {
  8469. if (this._masterMesh) {
  8470. return this._masterMesh.getWorldMatrix();
  8471. }
  8472. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8473. this.computeWorldMatrix();
  8474. }
  8475. return this._worldMatrix;
  8476. };
  8477. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8478. get: function () {
  8479. return this._worldMatrix;
  8480. },
  8481. enumerable: true,
  8482. configurable: true
  8483. });
  8484. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8485. get: function () {
  8486. return this._absolutePosition;
  8487. },
  8488. enumerable: true,
  8489. configurable: true
  8490. });
  8491. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8492. if (!this.rotationQuaternion) {
  8493. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8494. this.rotation = BABYLON.Vector3.Zero();
  8495. }
  8496. if (!space || space == 0 /* LOCAL */) {
  8497. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8498. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8499. } else {
  8500. if (this.parent) {
  8501. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8502. invertParentWorldMatrix.invert();
  8503. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8504. }
  8505. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8506. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8507. }
  8508. };
  8509. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8510. var displacementVector = axis.scale(distance);
  8511. if (!space || space == 0 /* LOCAL */) {
  8512. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8513. this.setPositionWithLocalVector(tempV3);
  8514. } else {
  8515. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8516. }
  8517. };
  8518. AbstractMesh.prototype.getAbsolutePosition = function () {
  8519. this.computeWorldMatrix();
  8520. return this._absolutePosition;
  8521. };
  8522. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8523. if (!absolutePosition) {
  8524. return;
  8525. }
  8526. var absolutePositionX;
  8527. var absolutePositionY;
  8528. var absolutePositionZ;
  8529. if (absolutePosition.x === undefined) {
  8530. if (arguments.length < 3) {
  8531. return;
  8532. }
  8533. absolutePositionX = arguments[0];
  8534. absolutePositionY = arguments[1];
  8535. absolutePositionZ = arguments[2];
  8536. } else {
  8537. absolutePositionX = absolutePosition.x;
  8538. absolutePositionY = absolutePosition.y;
  8539. absolutePositionZ = absolutePosition.z;
  8540. }
  8541. if (this.parent) {
  8542. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8543. invertParentWorldMatrix.invert();
  8544. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8545. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8546. } else {
  8547. this.position.x = absolutePositionX;
  8548. this.position.y = absolutePositionY;
  8549. this.position.z = absolutePositionZ;
  8550. }
  8551. };
  8552. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8553. this._pivotMatrix = matrix;
  8554. this._cache.pivotMatrixUpdated = true;
  8555. };
  8556. AbstractMesh.prototype.getPivotMatrix = function () {
  8557. return this._pivotMatrix;
  8558. };
  8559. AbstractMesh.prototype._isSynchronized = function () {
  8560. if (this._isDirty) {
  8561. return false;
  8562. }
  8563. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8564. return false;
  8565. if (this._cache.pivotMatrixUpdated) {
  8566. return false;
  8567. }
  8568. if (this.infiniteDistance) {
  8569. return false;
  8570. }
  8571. if (!this._cache.position.equals(this.position))
  8572. return false;
  8573. if (this.rotationQuaternion) {
  8574. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8575. return false;
  8576. } else {
  8577. if (!this._cache.rotation.equals(this.rotation))
  8578. return false;
  8579. }
  8580. if (!this._cache.scaling.equals(this.scaling))
  8581. return false;
  8582. return true;
  8583. };
  8584. AbstractMesh.prototype._initCache = function () {
  8585. _super.prototype._initCache.call(this);
  8586. this._cache.localMatrixUpdated = false;
  8587. this._cache.position = BABYLON.Vector3.Zero();
  8588. this._cache.scaling = BABYLON.Vector3.Zero();
  8589. this._cache.rotation = BABYLON.Vector3.Zero();
  8590. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8591. };
  8592. AbstractMesh.prototype.markAsDirty = function (property) {
  8593. if (property === "rotation") {
  8594. this.rotationQuaternion = null;
  8595. }
  8596. this._currentRenderId = Number.MAX_VALUE;
  8597. this._isDirty = true;
  8598. };
  8599. AbstractMesh.prototype._updateBoundingInfo = function () {
  8600. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8601. this._boundingInfo._update(this.worldMatrixFromCache);
  8602. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8603. };
  8604. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8605. if (!this.subMeshes) {
  8606. return;
  8607. }
  8608. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8609. var subMesh = this.subMeshes[subIndex];
  8610. subMesh.updateBoundingInfo(matrix);
  8611. }
  8612. };
  8613. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8614. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8615. return this._worldMatrix;
  8616. }
  8617. this._cache.position.copyFrom(this.position);
  8618. this._cache.scaling.copyFrom(this.scaling);
  8619. this._cache.pivotMatrixUpdated = false;
  8620. this._currentRenderId = this.getScene().getRenderId();
  8621. this._isDirty = false;
  8622. // Scaling
  8623. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8624. // Rotation
  8625. if (this.rotationQuaternion) {
  8626. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8627. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8628. } else {
  8629. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8630. this._cache.rotation.copyFrom(this.rotation);
  8631. }
  8632. // Translation
  8633. if (this.infiniteDistance && !this.parent) {
  8634. var camera = this.getScene().activeCamera;
  8635. var cameraWorldMatrix = camera.getWorldMatrix();
  8636. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8637. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8638. } else {
  8639. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8640. }
  8641. // Composing transformations
  8642. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8643. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8644. // Billboarding
  8645. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8646. var localPosition = this.position.clone();
  8647. var zero = this.getScene().activeCamera.position.clone();
  8648. if (this.parent && this.parent.position) {
  8649. localPosition.addInPlace(this.parent.position);
  8650. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8651. }
  8652. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8653. zero = this.getScene().activeCamera.position;
  8654. } else {
  8655. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8656. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8657. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8658. zero.y = localPosition.y + 0.001;
  8659. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8660. zero.z = localPosition.z + 0.001;
  8661. }
  8662. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8663. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8664. this._localBillboard.invert();
  8665. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8666. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8667. }
  8668. // Local world
  8669. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8670. // Parent
  8671. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8672. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8673. } else {
  8674. this._worldMatrix.copyFrom(this._localWorld);
  8675. }
  8676. // Bounding info
  8677. this._updateBoundingInfo();
  8678. // Absolute position
  8679. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8680. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8681. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8682. }
  8683. return this._worldMatrix;
  8684. };
  8685. /**
  8686. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8687. * @param func: callback function to add
  8688. */
  8689. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8690. this._onAfterWorldMatrixUpdate.push(func);
  8691. };
  8692. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8693. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8694. if (index > -1) {
  8695. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8696. }
  8697. };
  8698. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8699. this.computeWorldMatrix();
  8700. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8701. };
  8702. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8703. this.computeWorldMatrix();
  8704. var invLocalWorldMatrix = this._localWorld.clone();
  8705. invLocalWorldMatrix.invert();
  8706. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8707. };
  8708. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8709. this.computeWorldMatrix();
  8710. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8711. };
  8712. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8713. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8714. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8715. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8716. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8717. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8718. /// <returns>Mesh oriented towards targetMesh</returns>
  8719. yawCor = yawCor || 0; // default to zero if undefined
  8720. pitchCor = pitchCor || 0;
  8721. rollCor = rollCor || 0;
  8722. var dv = targetPoint.subtract(this.position);
  8723. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8724. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8725. var pitch = Math.atan2(dv.y, len);
  8726. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8727. };
  8728. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8729. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8730. return false;
  8731. }
  8732. return true;
  8733. };
  8734. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8735. if (!camera) {
  8736. camera = this.getScene().activeCamera;
  8737. }
  8738. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8739. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8740. return false;
  8741. }
  8742. return true;
  8743. };
  8744. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8745. if (!this._boundingInfo || !mesh._boundingInfo) {
  8746. return false;
  8747. }
  8748. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8749. };
  8750. AbstractMesh.prototype.intersectsPoint = function (point) {
  8751. if (!this._boundingInfo) {
  8752. return false;
  8753. }
  8754. return this._boundingInfo.intersectsPoint(point);
  8755. };
  8756. // Physics
  8757. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8758. var physicsEngine = this.getScene().getPhysicsEngine();
  8759. if (!physicsEngine) {
  8760. return;
  8761. }
  8762. if (impostor.impostor) {
  8763. // Old API
  8764. options = impostor;
  8765. impostor = impostor.impostor;
  8766. }
  8767. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8768. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8769. physicsEngine._unregisterMesh(this);
  8770. return;
  8771. }
  8772. options.mass = options.mass || 0;
  8773. options.friction = options.friction || 0.2;
  8774. options.restitution = options.restitution || 0.2;
  8775. this._physicImpostor = impostor;
  8776. this._physicsMass = options.mass;
  8777. this._physicsFriction = options.friction;
  8778. this._physicRestitution = options.restitution;
  8779. return physicsEngine._registerMesh(this, impostor, options);
  8780. };
  8781. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8782. if (!this._physicImpostor) {
  8783. return BABYLON.PhysicsEngine.NoImpostor;
  8784. }
  8785. return this._physicImpostor;
  8786. };
  8787. AbstractMesh.prototype.getPhysicsMass = function () {
  8788. if (!this._physicsMass) {
  8789. return 0;
  8790. }
  8791. return this._physicsMass;
  8792. };
  8793. AbstractMesh.prototype.getPhysicsFriction = function () {
  8794. if (!this._physicsFriction) {
  8795. return 0;
  8796. }
  8797. return this._physicsFriction;
  8798. };
  8799. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8800. if (!this._physicRestitution) {
  8801. return 0;
  8802. }
  8803. return this._physicRestitution;
  8804. };
  8805. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8806. if (!camera) {
  8807. camera = this.getScene().activeCamera;
  8808. }
  8809. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8810. };
  8811. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8812. if (!camera) {
  8813. camera = this.getScene().activeCamera;
  8814. }
  8815. return this.absolutePosition.subtract(camera.position).length();
  8816. };
  8817. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8818. if (!this._physicImpostor) {
  8819. return;
  8820. }
  8821. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8822. };
  8823. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8824. if (!this._physicImpostor) {
  8825. return;
  8826. }
  8827. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8828. };
  8829. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8830. if (!this._physicImpostor) {
  8831. return;
  8832. }
  8833. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8834. };
  8835. // Collisions
  8836. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8837. var globalPosition = this.getAbsolutePosition();
  8838. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8839. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8840. this._collider.radius = this.ellipsoid;
  8841. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8842. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8843. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8844. this.position.addInPlace(this._diffPositionForCollisions);
  8845. }
  8846. };
  8847. // Submeshes octree
  8848. /**
  8849. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8850. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8851. */
  8852. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8853. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8854. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8855. if (!this._submeshesOctree) {
  8856. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8857. }
  8858. this.computeWorldMatrix(true);
  8859. // Update octree
  8860. var bbox = this.getBoundingInfo().boundingBox;
  8861. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8862. return this._submeshesOctree;
  8863. };
  8864. // Collisions
  8865. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8866. this._generatePointsArray();
  8867. // Transformation
  8868. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8869. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8870. subMesh._lastColliderWorldVertices = [];
  8871. subMesh._trianglePlanes = [];
  8872. var start = subMesh.verticesStart;
  8873. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8874. for (var i = start; i < end; i++) {
  8875. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8876. }
  8877. }
  8878. // Collide
  8879. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8880. };
  8881. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8882. var subMeshes;
  8883. var len;
  8884. // Octrees
  8885. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8886. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8887. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8888. len = intersections.length;
  8889. subMeshes = intersections.data;
  8890. } else {
  8891. subMeshes = this.subMeshes;
  8892. len = subMeshes.length;
  8893. }
  8894. for (var index = 0; index < len; index++) {
  8895. var subMesh = subMeshes[index];
  8896. // Bounding test
  8897. if (len > 1 && !subMesh._checkCollision(collider))
  8898. continue;
  8899. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8900. }
  8901. };
  8902. AbstractMesh.prototype._checkCollision = function (collider) {
  8903. // Bounding box test
  8904. if (!this._boundingInfo._checkCollision(collider))
  8905. return;
  8906. // Transformation matrix
  8907. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8908. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8909. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8910. };
  8911. // Picking
  8912. AbstractMesh.prototype._generatePointsArray = function () {
  8913. return false;
  8914. };
  8915. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8916. var pickingInfo = new BABYLON.PickingInfo();
  8917. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8918. return pickingInfo;
  8919. }
  8920. if (!this._generatePointsArray()) {
  8921. return pickingInfo;
  8922. }
  8923. var intersectInfo = null;
  8924. // Octrees
  8925. var subMeshes;
  8926. var len;
  8927. if (this._submeshesOctree && this.useOctreeForPicking) {
  8928. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8929. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8930. len = intersections.length;
  8931. subMeshes = intersections.data;
  8932. } else {
  8933. subMeshes = this.subMeshes;
  8934. len = subMeshes.length;
  8935. }
  8936. for (var index = 0; index < len; index++) {
  8937. var subMesh = subMeshes[index];
  8938. // Bounding test
  8939. if (len > 1 && !subMesh.canIntersects(ray))
  8940. continue;
  8941. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8942. if (currentIntersectInfo) {
  8943. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8944. intersectInfo = currentIntersectInfo;
  8945. if (fastCheck) {
  8946. break;
  8947. }
  8948. }
  8949. }
  8950. }
  8951. if (intersectInfo) {
  8952. // Get picked point
  8953. var world = this.getWorldMatrix();
  8954. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8955. var direction = ray.direction.clone();
  8956. direction.normalize();
  8957. direction = direction.scale(intersectInfo.distance);
  8958. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8959. var pickedPoint = worldOrigin.add(worldDirection);
  8960. // Return result
  8961. pickingInfo.hit = true;
  8962. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8963. pickingInfo.pickedPoint = pickedPoint;
  8964. pickingInfo.pickedMesh = this;
  8965. pickingInfo.bu = intersectInfo.bu;
  8966. pickingInfo.bv = intersectInfo.bv;
  8967. pickingInfo.faceId = intersectInfo.faceId;
  8968. return pickingInfo;
  8969. }
  8970. return pickingInfo;
  8971. };
  8972. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8973. return null;
  8974. };
  8975. AbstractMesh.prototype.releaseSubMeshes = function () {
  8976. if (this.subMeshes) {
  8977. while (this.subMeshes.length) {
  8978. this.subMeshes[0].dispose();
  8979. }
  8980. } else {
  8981. this.subMeshes = new Array();
  8982. }
  8983. };
  8984. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8985. // Physics
  8986. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8987. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8988. }
  8989. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8990. var other = this._intersectionsInProgress[index];
  8991. var pos = other._intersectionsInProgress.indexOf(this);
  8992. other._intersectionsInProgress.splice(pos, 1);
  8993. }
  8994. this._intersectionsInProgress = [];
  8995. // SubMeshes
  8996. this.releaseSubMeshes();
  8997. // Remove from scene
  8998. var index = this.getScene().meshes.indexOf(this);
  8999. if (index != -1) {
  9000. // Remove from the scene if mesh found
  9001. this.getScene().meshes.splice(index, 1);
  9002. }
  9003. if (!doNotRecurse) {
  9004. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9005. if (this.getScene().particleSystems[index].emitter == this) {
  9006. this.getScene().particleSystems[index].dispose();
  9007. index--;
  9008. }
  9009. }
  9010. // Children
  9011. var objects = this.getScene().meshes.slice(0);
  9012. for (index = 0; index < objects.length; index++) {
  9013. if (objects[index].parent == this) {
  9014. objects[index].dispose();
  9015. }
  9016. }
  9017. } else {
  9018. for (index = 0; index < this.getScene().meshes.length; index++) {
  9019. var obj = this.getScene().meshes[index];
  9020. if (obj.parent === this) {
  9021. obj.parent = null;
  9022. obj.computeWorldMatrix(true);
  9023. }
  9024. }
  9025. }
  9026. this._onAfterWorldMatrixUpdate = [];
  9027. this._isDisposed = true;
  9028. // Callback
  9029. if (this.onDispose) {
  9030. this.onDispose();
  9031. }
  9032. };
  9033. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9034. AbstractMesh._BILLBOARDMODE_X = 1;
  9035. AbstractMesh._BILLBOARDMODE_Y = 2;
  9036. AbstractMesh._BILLBOARDMODE_Z = 4;
  9037. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9038. return AbstractMesh;
  9039. })(BABYLON.Node);
  9040. BABYLON.AbstractMesh = AbstractMesh;
  9041. })(BABYLON || (BABYLON = {}));
  9042. //# sourceMappingURL=babylon.abstractMesh.js.map
  9043. var BABYLON;
  9044. (function (BABYLON) {
  9045. var _InstancesBatch = (function () {
  9046. function _InstancesBatch() {
  9047. this.mustReturn = false;
  9048. this.visibleInstances = new Array();
  9049. this.renderSelf = new Array();
  9050. }
  9051. return _InstancesBatch;
  9052. })();
  9053. BABYLON._InstancesBatch = _InstancesBatch;
  9054. var Mesh = (function (_super) {
  9055. __extends(Mesh, _super);
  9056. /**
  9057. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9058. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9059. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9060. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9061. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9062. * When false, achieved by calling a clone(), also passing False.
  9063. * This will make creation of children, recursive.
  9064. */
  9065. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9066. if (typeof parent === "undefined") { parent = null; }
  9067. _super.call(this, name, scene);
  9068. // Members
  9069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9070. this.instances = new Array();
  9071. this._LODLevels = new Array();
  9072. this._onBeforeRenderCallbacks = new Array();
  9073. this._onAfterRenderCallbacks = new Array();
  9074. this._visibleInstances = {};
  9075. this._renderIdForInstances = new Array();
  9076. this._batchCache = new _InstancesBatch();
  9077. this._instancesBufferSize = 32 * 16 * 4;
  9078. if (source) {
  9079. // Geometry
  9080. if (source._geometry) {
  9081. source._geometry.applyToMesh(this);
  9082. }
  9083. // Deep copy
  9084. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9085. // Material
  9086. this.material = source.material;
  9087. if (!doNotCloneChildren) {
  9088. for (var index = 0; index < scene.meshes.length; index++) {
  9089. var mesh = scene.meshes[index];
  9090. if (mesh.parent === source) {
  9091. // doNotCloneChildren is always going to be False
  9092. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9093. }
  9094. }
  9095. }
  9096. for (index = 0; index < scene.particleSystems.length; index++) {
  9097. var system = scene.particleSystems[index];
  9098. if (system.emitter === source) {
  9099. system.clone(system.name, this);
  9100. }
  9101. }
  9102. this.computeWorldMatrix(true);
  9103. }
  9104. // Parent
  9105. if (parent !== null) {
  9106. this.parent = parent;
  9107. }
  9108. }
  9109. Mesh.prototype._clone = function () {
  9110. };
  9111. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9112. // Methods
  9113. get: function () {
  9114. return this._LODLevels.length > 0;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Mesh.prototype._sortLODLevels = function () {
  9120. this._LODLevels.sort(function (a, b) {
  9121. if (a.distance < b.distance) {
  9122. return 1;
  9123. }
  9124. if (a.distance > b.distance) {
  9125. return -1;
  9126. }
  9127. return 0;
  9128. });
  9129. };
  9130. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9131. if (mesh && mesh._masterMesh) {
  9132. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9133. return this;
  9134. }
  9135. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9136. this._LODLevels.push(level);
  9137. if (mesh) {
  9138. mesh._masterMesh = this;
  9139. }
  9140. this._sortLODLevels();
  9141. return this;
  9142. };
  9143. Mesh.prototype.removeLODLevel = function (mesh) {
  9144. for (var index = 0; index < this._LODLevels.length; index++) {
  9145. if (this._LODLevels[index].mesh === mesh) {
  9146. this._LODLevels.splice(index, 1);
  9147. if (mesh) {
  9148. mesh._masterMesh = null;
  9149. }
  9150. }
  9151. }
  9152. this._sortLODLevels();
  9153. return this;
  9154. };
  9155. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9156. if (!this._LODLevels || this._LODLevels.length === 0) {
  9157. return this;
  9158. }
  9159. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9160. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9161. return this;
  9162. }
  9163. for (var index = 0; index < this._LODLevels.length; index++) {
  9164. var level = this._LODLevels[index];
  9165. if (level.distance < distanceToCamera) {
  9166. if (level.mesh) {
  9167. level.mesh._preActivate();
  9168. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9169. }
  9170. return level.mesh;
  9171. }
  9172. }
  9173. return this;
  9174. };
  9175. Object.defineProperty(Mesh.prototype, "geometry", {
  9176. get: function () {
  9177. return this._geometry;
  9178. },
  9179. enumerable: true,
  9180. configurable: true
  9181. });
  9182. Mesh.prototype.getTotalVertices = function () {
  9183. if (!this._geometry) {
  9184. return 0;
  9185. }
  9186. return this._geometry.getTotalVertices();
  9187. };
  9188. Mesh.prototype.getVerticesData = function (kind) {
  9189. if (!this._geometry) {
  9190. return null;
  9191. }
  9192. return this._geometry.getVerticesData(kind);
  9193. };
  9194. Mesh.prototype.getVertexBuffer = function (kind) {
  9195. if (!this._geometry) {
  9196. return undefined;
  9197. }
  9198. return this._geometry.getVertexBuffer(kind);
  9199. };
  9200. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9201. if (!this._geometry) {
  9202. if (this._delayInfo) {
  9203. return this._delayInfo.indexOf(kind) !== -1;
  9204. }
  9205. return false;
  9206. }
  9207. return this._geometry.isVerticesDataPresent(kind);
  9208. };
  9209. Mesh.prototype.getVerticesDataKinds = function () {
  9210. if (!this._geometry) {
  9211. var result = [];
  9212. if (this._delayInfo) {
  9213. for (var kind in this._delayInfo) {
  9214. result.push(kind);
  9215. }
  9216. }
  9217. return result;
  9218. }
  9219. return this._geometry.getVerticesDataKinds();
  9220. };
  9221. Mesh.prototype.getTotalIndices = function () {
  9222. if (!this._geometry) {
  9223. return 0;
  9224. }
  9225. return this._geometry.getTotalIndices();
  9226. };
  9227. Mesh.prototype.getIndices = function () {
  9228. if (!this._geometry) {
  9229. return [];
  9230. }
  9231. return this._geometry.getIndices();
  9232. };
  9233. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9234. get: function () {
  9235. return this._masterMesh !== null && this._masterMesh !== undefined;
  9236. },
  9237. enumerable: true,
  9238. configurable: true
  9239. });
  9240. Mesh.prototype.isReady = function () {
  9241. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9242. return false;
  9243. }
  9244. return _super.prototype.isReady.call(this);
  9245. };
  9246. Mesh.prototype.isDisposed = function () {
  9247. return this._isDisposed;
  9248. };
  9249. // Methods
  9250. Mesh.prototype._preActivate = function () {
  9251. var sceneRenderId = this.getScene().getRenderId();
  9252. if (this._preActivateId == sceneRenderId) {
  9253. return;
  9254. }
  9255. this._preActivateId = sceneRenderId;
  9256. this._visibleInstances = null;
  9257. };
  9258. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9259. if (!this._visibleInstances) {
  9260. this._visibleInstances = {};
  9261. this._visibleInstances.defaultRenderId = renderId;
  9262. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9263. }
  9264. if (!this._visibleInstances[renderId]) {
  9265. this._visibleInstances[renderId] = new Array();
  9266. }
  9267. this._visibleInstances[renderId].push(instance);
  9268. };
  9269. Mesh.prototype.refreshBoundingInfo = function () {
  9270. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9271. if (data) {
  9272. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9273. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9274. }
  9275. if (this.subMeshes) {
  9276. for (var index = 0; index < this.subMeshes.length; index++) {
  9277. this.subMeshes[index].refreshBoundingInfo();
  9278. }
  9279. }
  9280. this._updateBoundingInfo();
  9281. };
  9282. Mesh.prototype._createGlobalSubMesh = function () {
  9283. var totalVertices = this.getTotalVertices();
  9284. if (!totalVertices || !this.getIndices()) {
  9285. return null;
  9286. }
  9287. this.releaseSubMeshes();
  9288. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9289. };
  9290. Mesh.prototype.subdivide = function (count) {
  9291. if (count < 1) {
  9292. return;
  9293. }
  9294. var totalIndices = this.getTotalIndices();
  9295. var subdivisionSize = (totalIndices / count) | 0;
  9296. var offset = 0;
  9297. while (subdivisionSize % 3 != 0) {
  9298. subdivisionSize++;
  9299. }
  9300. this.releaseSubMeshes();
  9301. for (var index = 0; index < count; index++) {
  9302. if (offset >= totalIndices) {
  9303. break;
  9304. }
  9305. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9306. offset += subdivisionSize;
  9307. }
  9308. this.synchronizeInstances();
  9309. };
  9310. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9311. if (kind instanceof Array) {
  9312. var temp = data;
  9313. data = kind;
  9314. kind = temp;
  9315. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9316. }
  9317. if (!this._geometry) {
  9318. var vertexData = new BABYLON.VertexData();
  9319. vertexData.set(data, kind);
  9320. var scene = this.getScene();
  9321. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9322. } else {
  9323. this._geometry.setVerticesData(kind, data, updatable, stride);
  9324. }
  9325. };
  9326. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9327. if (!this._geometry) {
  9328. return;
  9329. }
  9330. if (!makeItUnique) {
  9331. this._geometry.updateVerticesData(kind, data, updateExtends);
  9332. } else {
  9333. this.makeGeometryUnique();
  9334. this.updateVerticesData(kind, data, updateExtends, false);
  9335. }
  9336. };
  9337. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9338. if (!this._geometry) {
  9339. return;
  9340. }
  9341. if (!makeItUnique) {
  9342. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9343. } else {
  9344. this.makeGeometryUnique();
  9345. this.updateVerticesDataDirectly(kind, data, offset, false);
  9346. }
  9347. };
  9348. Mesh.prototype.makeGeometryUnique = function () {
  9349. if (!this._geometry) {
  9350. return;
  9351. }
  9352. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9353. geometry.applyToMesh(this);
  9354. };
  9355. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9356. if (!this._geometry) {
  9357. var vertexData = new BABYLON.VertexData();
  9358. vertexData.indices = indices;
  9359. var scene = this.getScene();
  9360. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9361. } else {
  9362. this._geometry.setIndices(indices, totalVertices);
  9363. }
  9364. };
  9365. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9366. var engine = this.getScene().getEngine();
  9367. // Wireframe
  9368. var indexToBind;
  9369. switch (fillMode) {
  9370. case BABYLON.Material.PointFillMode:
  9371. indexToBind = null;
  9372. break;
  9373. case BABYLON.Material.WireFrameFillMode:
  9374. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9375. break;
  9376. default:
  9377. case BABYLON.Material.TriangleFillMode:
  9378. indexToBind = this._geometry.getIndexBuffer();
  9379. break;
  9380. }
  9381. // VBOs
  9382. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9383. };
  9384. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9385. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9386. return;
  9387. }
  9388. var engine = this.getScene().getEngine();
  9389. switch (fillMode) {
  9390. case BABYLON.Material.PointFillMode:
  9391. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9392. break;
  9393. case BABYLON.Material.WireFrameFillMode:
  9394. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9395. break;
  9396. default:
  9397. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9398. }
  9399. };
  9400. Mesh.prototype.registerBeforeRender = function (func) {
  9401. this._onBeforeRenderCallbacks.push(func);
  9402. };
  9403. Mesh.prototype.unregisterBeforeRender = function (func) {
  9404. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9405. if (index > -1) {
  9406. this._onBeforeRenderCallbacks.splice(index, 1);
  9407. }
  9408. };
  9409. Mesh.prototype.registerAfterRender = function (func) {
  9410. this._onAfterRenderCallbacks.push(func);
  9411. };
  9412. Mesh.prototype.unregisterAfterRender = function (func) {
  9413. var index = this._onAfterRenderCallbacks.indexOf(func);
  9414. if (index > -1) {
  9415. this._onAfterRenderCallbacks.splice(index, 1);
  9416. }
  9417. };
  9418. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9419. var scene = this.getScene();
  9420. this._batchCache.mustReturn = false;
  9421. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9422. this._batchCache.visibleInstances[subMeshId] = null;
  9423. if (this._visibleInstances) {
  9424. var currentRenderId = scene.getRenderId();
  9425. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9426. var selfRenderId = this._renderId;
  9427. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9428. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9429. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9430. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9431. }
  9432. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9433. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9434. this._batchCache.mustReturn = true;
  9435. return this._batchCache;
  9436. }
  9437. if (currentRenderId !== selfRenderId) {
  9438. this._batchCache.renderSelf[subMeshId] = false;
  9439. }
  9440. }
  9441. this._renderIdForInstances[subMeshId] = currentRenderId;
  9442. }
  9443. return this._batchCache;
  9444. };
  9445. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9446. var visibleInstances = batch.visibleInstances[subMesh._id];
  9447. var matricesCount = visibleInstances.length + 1;
  9448. var bufferSize = matricesCount * 16 * 4;
  9449. while (this._instancesBufferSize < bufferSize) {
  9450. this._instancesBufferSize *= 2;
  9451. }
  9452. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9453. if (this._worldMatricesInstancesBuffer) {
  9454. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9455. }
  9456. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9457. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9458. }
  9459. var offset = 0;
  9460. var instancesCount = 0;
  9461. var world = this.getWorldMatrix();
  9462. if (batch.renderSelf[subMesh._id]) {
  9463. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9464. offset += 16;
  9465. instancesCount++;
  9466. }
  9467. if (visibleInstances) {
  9468. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9469. var instance = visibleInstances[instanceIndex];
  9470. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9471. offset += 16;
  9472. instancesCount++;
  9473. }
  9474. }
  9475. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9476. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9477. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9478. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9479. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9480. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9481. this._draw(subMesh, fillMode, instancesCount);
  9482. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9483. };
  9484. Mesh.prototype.render = function (subMesh) {
  9485. var scene = this.getScene();
  9486. // Managing instances
  9487. var batch = this._getInstancesRenderList(subMesh._id);
  9488. if (batch.mustReturn) {
  9489. return;
  9490. }
  9491. // Checking geometry state
  9492. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9493. return;
  9494. }
  9495. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9496. this._onBeforeRenderCallbacks[callbackIndex]();
  9497. }
  9498. var engine = scene.getEngine();
  9499. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9500. // Material
  9501. var effectiveMaterial = subMesh.getMaterial();
  9502. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9503. return;
  9504. }
  9505. // Outline - step 1
  9506. var savedDepthWrite = engine.getDepthWrite();
  9507. if (this.renderOutline) {
  9508. engine.setDepthWrite(false);
  9509. scene.getOutlineRenderer().render(subMesh, batch);
  9510. engine.setDepthWrite(savedDepthWrite);
  9511. }
  9512. effectiveMaterial._preBind();
  9513. var effect = effectiveMaterial.getEffect();
  9514. // Bind
  9515. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9516. this._bind(subMesh, effect, fillMode);
  9517. var world = this.getWorldMatrix();
  9518. effectiveMaterial.bind(world, this);
  9519. // Instances rendering
  9520. if (hardwareInstancedRendering) {
  9521. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9522. } else {
  9523. if (batch.renderSelf[subMesh._id]) {
  9524. // Draw
  9525. this._draw(subMesh, fillMode);
  9526. }
  9527. if (batch.visibleInstances[subMesh._id]) {
  9528. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9529. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9530. // World
  9531. world = instance.getWorldMatrix();
  9532. effectiveMaterial.bindOnlyWorldMatrix(world);
  9533. // Draw
  9534. this._draw(subMesh, fillMode);
  9535. }
  9536. }
  9537. }
  9538. // Unbind
  9539. effectiveMaterial.unbind();
  9540. // Outline - step 2
  9541. if (this.renderOutline && savedDepthWrite) {
  9542. engine.setDepthWrite(true);
  9543. engine.setColorWrite(false);
  9544. scene.getOutlineRenderer().render(subMesh, batch);
  9545. engine.setColorWrite(true);
  9546. }
  9547. // Overlay
  9548. if (this.renderOverlay) {
  9549. var currentMode = engine.getAlphaMode();
  9550. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9551. scene.getOutlineRenderer().render(subMesh, batch, true);
  9552. engine.setAlphaMode(currentMode);
  9553. }
  9554. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9555. this._onAfterRenderCallbacks[callbackIndex]();
  9556. }
  9557. };
  9558. Mesh.prototype.getEmittedParticleSystems = function () {
  9559. var results = new Array();
  9560. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9561. var particleSystem = this.getScene().particleSystems[index];
  9562. if (particleSystem.emitter === this) {
  9563. results.push(particleSystem);
  9564. }
  9565. }
  9566. return results;
  9567. };
  9568. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9569. var results = new Array();
  9570. var descendants = this.getDescendants();
  9571. descendants.push(this);
  9572. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9573. var particleSystem = this.getScene().particleSystems[index];
  9574. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9575. results.push(particleSystem);
  9576. }
  9577. }
  9578. return results;
  9579. };
  9580. Mesh.prototype.getChildren = function () {
  9581. var results = [];
  9582. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9583. var mesh = this.getScene().meshes[index];
  9584. if (mesh.parent == this) {
  9585. results.push(mesh);
  9586. }
  9587. }
  9588. return results;
  9589. };
  9590. Mesh.prototype._checkDelayState = function () {
  9591. var _this = this;
  9592. var that = this;
  9593. var scene = this.getScene();
  9594. if (this._geometry) {
  9595. this._geometry.load(scene);
  9596. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9597. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9598. scene._addPendingData(that);
  9599. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9600. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9601. if (data instanceof ArrayBuffer) {
  9602. _this._delayLoadingFunction(data, _this);
  9603. } else {
  9604. _this._delayLoadingFunction(JSON.parse(data), _this);
  9605. }
  9606. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9607. scene._removePendingData(_this);
  9608. }, function () {
  9609. }, scene.database, getBinaryData);
  9610. }
  9611. };
  9612. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9613. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9614. return false;
  9615. }
  9616. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9617. return false;
  9618. }
  9619. this._checkDelayState();
  9620. return true;
  9621. };
  9622. Mesh.prototype.setMaterialByID = function (id) {
  9623. var materials = this.getScene().materials;
  9624. for (var index = 0; index < materials.length; index++) {
  9625. if (materials[index].id == id) {
  9626. this.material = materials[index];
  9627. return;
  9628. }
  9629. }
  9630. // Multi
  9631. var multiMaterials = this.getScene().multiMaterials;
  9632. for (index = 0; index < multiMaterials.length; index++) {
  9633. if (multiMaterials[index].id == id) {
  9634. this.material = multiMaterials[index];
  9635. return;
  9636. }
  9637. }
  9638. };
  9639. Mesh.prototype.getAnimatables = function () {
  9640. var results = [];
  9641. if (this.material) {
  9642. results.push(this.material);
  9643. }
  9644. if (this.skeleton) {
  9645. results.push(this.skeleton);
  9646. }
  9647. return results;
  9648. };
  9649. // Geometry
  9650. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9651. // Position
  9652. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9653. return;
  9654. }
  9655. this._resetPointsArrayCache();
  9656. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9657. var temp = [];
  9658. for (var index = 0; index < data.length; index += 3) {
  9659. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9660. }
  9661. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9662. // Normals
  9663. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9664. return;
  9665. }
  9666. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9667. for (index = 0; index < data.length; index += 3) {
  9668. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9669. }
  9670. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9671. };
  9672. // Cache
  9673. Mesh.prototype._resetPointsArrayCache = function () {
  9674. this._positions = null;
  9675. };
  9676. Mesh.prototype._generatePointsArray = function () {
  9677. if (this._positions)
  9678. return true;
  9679. this._positions = [];
  9680. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9681. if (!data) {
  9682. return false;
  9683. }
  9684. for (var index = 0; index < data.length; index += 3) {
  9685. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9686. }
  9687. return true;
  9688. };
  9689. // Clone
  9690. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9691. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9692. };
  9693. // Dispose
  9694. Mesh.prototype.dispose = function (doNotRecurse) {
  9695. if (this._geometry) {
  9696. this._geometry.releaseForMesh(this, true);
  9697. }
  9698. // Instances
  9699. if (this._worldMatricesInstancesBuffer) {
  9700. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9701. this._worldMatricesInstancesBuffer = null;
  9702. }
  9703. while (this.instances.length) {
  9704. this.instances[0].dispose();
  9705. }
  9706. _super.prototype.dispose.call(this, doNotRecurse);
  9707. };
  9708. // Geometric tools
  9709. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9710. var _this = this;
  9711. var scene = this.getScene();
  9712. var onload = function (img) {
  9713. // Getting height map data
  9714. var canvas = document.createElement("canvas");
  9715. var context = canvas.getContext("2d");
  9716. var heightMapWidth = img.width;
  9717. var heightMapHeight = img.height;
  9718. canvas.width = heightMapWidth;
  9719. canvas.height = heightMapHeight;
  9720. context.drawImage(img, 0, 0);
  9721. // Create VertexData from map data
  9722. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9723. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9724. };
  9725. BABYLON.Tools.LoadImage(url, onload, function () {
  9726. }, scene.database);
  9727. };
  9728. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9730. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9731. return;
  9732. }
  9733. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9734. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9735. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9736. var position = BABYLON.Vector3.Zero();
  9737. var normal = BABYLON.Vector3.Zero();
  9738. var uv = BABYLON.Vector2.Zero();
  9739. for (var index = 0; index < positions.length; index += 3) {
  9740. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9741. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9742. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9743. // Compute height
  9744. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9745. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9746. var pos = (u + v * heightMapWidth) * 4;
  9747. var r = buffer[pos] / 255.0;
  9748. var g = buffer[pos + 1] / 255.0;
  9749. var b = buffer[pos + 2] / 255.0;
  9750. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9751. normal.normalize();
  9752. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9753. position = position.add(normal);
  9754. position.toArray(positions, index);
  9755. }
  9756. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9757. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9758. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9759. };
  9760. Mesh.prototype.convertToFlatShadedMesh = function () {
  9761. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9762. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9763. var kinds = this.getVerticesDataKinds();
  9764. var vbs = [];
  9765. var data = [];
  9766. var newdata = [];
  9767. var updatableNormals = false;
  9768. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9769. var kind = kinds[kindIndex];
  9770. var vertexBuffer = this.getVertexBuffer(kind);
  9771. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9772. updatableNormals = vertexBuffer.isUpdatable();
  9773. kinds.splice(kindIndex, 1);
  9774. kindIndex--;
  9775. continue;
  9776. }
  9777. vbs[kind] = vertexBuffer;
  9778. data[kind] = vbs[kind].getData();
  9779. newdata[kind] = [];
  9780. }
  9781. // Save previous submeshes
  9782. var previousSubmeshes = this.subMeshes.slice(0);
  9783. var indices = this.getIndices();
  9784. var totalIndices = this.getTotalIndices();
  9785. for (index = 0; index < totalIndices; index++) {
  9786. var vertexIndex = indices[index];
  9787. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9788. kind = kinds[kindIndex];
  9789. var stride = vbs[kind].getStrideSize();
  9790. for (var offset = 0; offset < stride; offset++) {
  9791. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9792. }
  9793. }
  9794. }
  9795. // Updating faces & normal
  9796. var normals = [];
  9797. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9798. for (var index = 0; index < totalIndices; index += 3) {
  9799. indices[index] = index;
  9800. indices[index + 1] = index + 1;
  9801. indices[index + 2] = index + 2;
  9802. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9803. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9804. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9805. var p1p2 = p1.subtract(p2);
  9806. var p3p2 = p3.subtract(p2);
  9807. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9808. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9809. normals.push(normal.x);
  9810. normals.push(normal.y);
  9811. normals.push(normal.z);
  9812. }
  9813. }
  9814. this.setIndices(indices);
  9815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9816. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9817. kind = kinds[kindIndex];
  9818. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9819. }
  9820. // Updating submeshes
  9821. this.releaseSubMeshes();
  9822. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9823. var previousOne = previousSubmeshes[submeshIndex];
  9824. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9825. }
  9826. this.synchronizeInstances();
  9827. };
  9828. // Instances
  9829. Mesh.prototype.createInstance = function (name) {
  9830. return new BABYLON.InstancedMesh(name, this);
  9831. };
  9832. Mesh.prototype.synchronizeInstances = function () {
  9833. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9834. var instance = this.instances[instanceIndex];
  9835. instance._syncSubMeshes();
  9836. }
  9837. };
  9838. // Statics
  9839. Mesh.CreateBox = function (name, size, scene, updatable) {
  9840. var box = new BABYLON.Mesh(name, scene);
  9841. var vertexData = BABYLON.VertexData.CreateBox(size);
  9842. vertexData.applyToMesh(box, updatable);
  9843. return box;
  9844. };
  9845. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9846. var sphere = new BABYLON.Mesh(name, scene);
  9847. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9848. vertexData.applyToMesh(sphere, updatable);
  9849. return sphere;
  9850. };
  9851. // Cylinder and cone (Code inspired by SharpDX.org)
  9852. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9853. // subdivisions is a new parameter, we need to support old signature
  9854. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9855. if (scene !== undefined) {
  9856. updatable = scene;
  9857. }
  9858. scene = subdivisions;
  9859. subdivisions = 1;
  9860. }
  9861. var cylinder = new BABYLON.Mesh(name, scene);
  9862. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9863. vertexData.applyToMesh(cylinder, updatable);
  9864. return cylinder;
  9865. };
  9866. // Torus (Code from SharpDX.org)
  9867. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9868. var torus = new BABYLON.Mesh(name, scene);
  9869. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9870. vertexData.applyToMesh(torus, updatable);
  9871. return torus;
  9872. };
  9873. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9874. var torusKnot = new BABYLON.Mesh(name, scene);
  9875. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9876. vertexData.applyToMesh(torusKnot, updatable);
  9877. return torusKnot;
  9878. };
  9879. // Lines
  9880. Mesh.CreateLines = function (name, points, scene, updatable) {
  9881. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9882. var vertexData = BABYLON.VertexData.CreateLines(points);
  9883. vertexData.applyToMesh(lines, updatable);
  9884. return lines;
  9885. };
  9886. // Plane & ground
  9887. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9888. var plane = new BABYLON.Mesh(name, scene);
  9889. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9890. vertexData.applyToMesh(plane, updatable);
  9891. return plane;
  9892. };
  9893. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9894. var ground = new BABYLON.GroundMesh(name, scene);
  9895. ground._setReady(false);
  9896. ground._subdivisions = subdivisions;
  9897. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9898. vertexData.applyToMesh(ground, updatable);
  9899. ground._setReady(true);
  9900. return ground;
  9901. };
  9902. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9903. var tiledGround = new BABYLON.Mesh(name, scene);
  9904. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9905. vertexData.applyToMesh(tiledGround, updatable);
  9906. return tiledGround;
  9907. };
  9908. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9909. var ground = new BABYLON.GroundMesh(name, scene);
  9910. ground._subdivisions = subdivisions;
  9911. ground._setReady(false);
  9912. var onload = function (img) {
  9913. // Getting height map data
  9914. var canvas = document.createElement("canvas");
  9915. var context = canvas.getContext("2d");
  9916. var heightMapWidth = img.width;
  9917. var heightMapHeight = img.height;
  9918. canvas.width = heightMapWidth;
  9919. canvas.height = heightMapHeight;
  9920. context.drawImage(img, 0, 0);
  9921. // Create VertexData from map data
  9922. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9923. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9924. vertexData.applyToMesh(ground, updatable);
  9925. ground._setReady(true);
  9926. };
  9927. BABYLON.Tools.LoadImage(url, onload, function () {
  9928. }, scene.database);
  9929. return ground;
  9930. };
  9931. // Tools
  9932. Mesh.MinMax = function (meshes) {
  9933. var minVector = null;
  9934. var maxVector = null;
  9935. for (var i in meshes) {
  9936. var mesh = meshes[i];
  9937. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9938. if (!minVector) {
  9939. minVector = boundingBox.minimumWorld;
  9940. maxVector = boundingBox.maximumWorld;
  9941. continue;
  9942. }
  9943. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9944. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9945. }
  9946. return {
  9947. min: minVector,
  9948. max: maxVector
  9949. };
  9950. };
  9951. Mesh.Center = function (meshesOrMinMaxVector) {
  9952. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9953. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9954. };
  9955. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  9956. if (typeof disposeSource === "undefined") { disposeSource = true; }
  9957. var source = meshes[0];
  9958. var material = source.material;
  9959. var scene = source.getScene();
  9960. if (!allow32BitsIndices) {
  9961. var totalVertices = 0;
  9962. for (var index = 0; index < meshes.length; index++) {
  9963. totalVertices += meshes[index].getTotalVertices();
  9964. if (totalVertices > 65536) {
  9965. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  9966. return null;
  9967. }
  9968. }
  9969. }
  9970. // Merge
  9971. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  9972. vertexData.transform(source.getWorldMatrix());
  9973. for (index = 1; index < meshes.length; index++) {
  9974. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  9975. otherVertexData.transform(meshes[index].getWorldMatrix());
  9976. vertexData.merge(otherVertexData);
  9977. }
  9978. var newMesh = new Mesh(source.name + "_merged", scene);
  9979. vertexData.applyToMesh(newMesh);
  9980. // Setting properties
  9981. newMesh.material = material;
  9982. newMesh.checkCollisions = source.checkCollisions;
  9983. // Cleaning
  9984. if (disposeSource) {
  9985. for (index = 0; index < meshes.length; index++) {
  9986. meshes[index].dispose();
  9987. }
  9988. }
  9989. return newMesh;
  9990. };
  9991. return Mesh;
  9992. })(BABYLON.AbstractMesh);
  9993. BABYLON.Mesh = Mesh;
  9994. })(BABYLON || (BABYLON = {}));
  9995. //# sourceMappingURL=babylon.mesh.js.map
  9996. var BABYLON;
  9997. (function (BABYLON) {
  9998. var GroundMesh = (function (_super) {
  9999. __extends(GroundMesh, _super);
  10000. function GroundMesh(name, scene) {
  10001. _super.call(this, name, scene);
  10002. this.generateOctree = false;
  10003. this._worldInverse = new BABYLON.Matrix();
  10004. }
  10005. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10006. get: function () {
  10007. return this._subdivisions;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. GroundMesh.prototype.optimize = function (chunksCount) {
  10013. this.subdivide(this._subdivisions);
  10014. this.createOrUpdateSubmeshesOctree(32);
  10015. };
  10016. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10017. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10018. this.getWorldMatrix().invertToRef(this._worldInverse);
  10019. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10020. var pickInfo = this.intersects(ray);
  10021. if (pickInfo.hit) {
  10022. return pickInfo.pickedPoint.y;
  10023. }
  10024. return 0;
  10025. };
  10026. return GroundMesh;
  10027. })(BABYLON.Mesh);
  10028. BABYLON.GroundMesh = GroundMesh;
  10029. })(BABYLON || (BABYLON = {}));
  10030. //# sourceMappingURL=babylon.groundMesh.js.map
  10031. var BABYLON;
  10032. (function (BABYLON) {
  10033. var InstancedMesh = (function (_super) {
  10034. __extends(InstancedMesh, _super);
  10035. function InstancedMesh(name, source) {
  10036. _super.call(this, name, source.getScene());
  10037. source.instances.push(this);
  10038. this._sourceMesh = source;
  10039. this.position.copyFrom(source.position);
  10040. this.rotation.copyFrom(source.rotation);
  10041. this.scaling.copyFrom(source.scaling);
  10042. if (source.rotationQuaternion) {
  10043. this.rotationQuaternion = source.rotationQuaternion.clone();
  10044. }
  10045. this.infiniteDistance = source.infiniteDistance;
  10046. this.setPivotMatrix(source.getPivotMatrix());
  10047. this.refreshBoundingInfo();
  10048. this._syncSubMeshes();
  10049. }
  10050. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10051. // Methods
  10052. get: function () {
  10053. return this._sourceMesh.receiveShadows;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(InstancedMesh.prototype, "material", {
  10059. get: function () {
  10060. return this._sourceMesh.material;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10066. get: function () {
  10067. return this._sourceMesh.visibility;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10073. get: function () {
  10074. return this._sourceMesh.skeleton;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. InstancedMesh.prototype.getTotalVertices = function () {
  10080. return this._sourceMesh.getTotalVertices();
  10081. };
  10082. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10083. get: function () {
  10084. return this._sourceMesh;
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. InstancedMesh.prototype.getVerticesData = function (kind) {
  10090. return this._sourceMesh.getVerticesData(kind);
  10091. };
  10092. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10093. return this._sourceMesh.isVerticesDataPresent(kind);
  10094. };
  10095. InstancedMesh.prototype.getIndices = function () {
  10096. return this._sourceMesh.getIndices();
  10097. };
  10098. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10099. get: function () {
  10100. return this._sourceMesh._positions;
  10101. },
  10102. enumerable: true,
  10103. configurable: true
  10104. });
  10105. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10106. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10107. if (data) {
  10108. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10109. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10110. }
  10111. this._updateBoundingInfo();
  10112. };
  10113. InstancedMesh.prototype._preActivate = function () {
  10114. if (this._currentLOD) {
  10115. this._currentLOD._preActivate();
  10116. }
  10117. };
  10118. InstancedMesh.prototype._activate = function (renderId) {
  10119. if (this._currentLOD) {
  10120. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10121. }
  10122. };
  10123. InstancedMesh.prototype.getLOD = function (camera) {
  10124. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10125. return this._currentLOD;
  10126. };
  10127. InstancedMesh.prototype._syncSubMeshes = function () {
  10128. this.releaseSubMeshes();
  10129. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10130. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10131. }
  10132. };
  10133. InstancedMesh.prototype._generatePointsArray = function () {
  10134. return this._sourceMesh._generatePointsArray();
  10135. };
  10136. // Clone
  10137. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10138. var result = this._sourceMesh.createInstance(name);
  10139. // Deep copy
  10140. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10141. // Bounding info
  10142. this.refreshBoundingInfo();
  10143. // Parent
  10144. if (newParent) {
  10145. result.parent = newParent;
  10146. }
  10147. if (!doNotCloneChildren) {
  10148. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10149. var mesh = this.getScene().meshes[index];
  10150. if (mesh.parent == this) {
  10151. mesh.clone(mesh.name, result);
  10152. }
  10153. }
  10154. }
  10155. result.computeWorldMatrix(true);
  10156. return result;
  10157. };
  10158. // Dispoe
  10159. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10160. // Remove from mesh
  10161. var index = this._sourceMesh.instances.indexOf(this);
  10162. this._sourceMesh.instances.splice(index, 1);
  10163. _super.prototype.dispose.call(this, doNotRecurse);
  10164. };
  10165. return InstancedMesh;
  10166. })(BABYLON.AbstractMesh);
  10167. BABYLON.InstancedMesh = InstancedMesh;
  10168. })(BABYLON || (BABYLON = {}));
  10169. //# sourceMappingURL=babylon.instancedMesh.js.map
  10170. var BABYLON;
  10171. (function (BABYLON) {
  10172. var SubMesh = (function () {
  10173. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10174. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10175. this.materialIndex = materialIndex;
  10176. this.verticesStart = verticesStart;
  10177. this.verticesCount = verticesCount;
  10178. this.indexStart = indexStart;
  10179. this.indexCount = indexCount;
  10180. this._renderId = 0;
  10181. this._mesh = mesh;
  10182. this._renderingMesh = renderingMesh || mesh;
  10183. mesh.subMeshes.push(this);
  10184. this._id = mesh.subMeshes.length - 1;
  10185. if (createBoundingBox) {
  10186. this.refreshBoundingInfo();
  10187. }
  10188. }
  10189. SubMesh.prototype.getBoundingInfo = function () {
  10190. return this._boundingInfo;
  10191. };
  10192. SubMesh.prototype.getMesh = function () {
  10193. return this._mesh;
  10194. };
  10195. SubMesh.prototype.getRenderingMesh = function () {
  10196. return this._renderingMesh;
  10197. };
  10198. SubMesh.prototype.getMaterial = function () {
  10199. var rootMaterial = this._renderingMesh.material;
  10200. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10201. var multiMaterial = rootMaterial;
  10202. return multiMaterial.getSubMaterial(this.materialIndex);
  10203. }
  10204. if (!rootMaterial) {
  10205. return this._mesh.getScene().defaultMaterial;
  10206. }
  10207. return rootMaterial;
  10208. };
  10209. // Methods
  10210. SubMesh.prototype.refreshBoundingInfo = function () {
  10211. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10212. if (!data) {
  10213. this._boundingInfo = this._mesh._boundingInfo;
  10214. return;
  10215. }
  10216. var indices = this._renderingMesh.getIndices();
  10217. var extend;
  10218. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10219. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10220. } else {
  10221. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10222. }
  10223. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10224. };
  10225. SubMesh.prototype._checkCollision = function (collider) {
  10226. return this._boundingInfo._checkCollision(collider);
  10227. };
  10228. SubMesh.prototype.updateBoundingInfo = function (world) {
  10229. if (!this._boundingInfo) {
  10230. this.refreshBoundingInfo();
  10231. }
  10232. this._boundingInfo._update(world);
  10233. };
  10234. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10235. return this._boundingInfo.isInFrustum(frustumPlanes);
  10236. };
  10237. SubMesh.prototype.render = function () {
  10238. this._renderingMesh.render(this);
  10239. };
  10240. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10241. if (!this._linesIndexBuffer) {
  10242. var linesIndices = [];
  10243. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10244. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10245. }
  10246. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10247. this.linesIndexCount = linesIndices.length;
  10248. }
  10249. return this._linesIndexBuffer;
  10250. };
  10251. SubMesh.prototype.canIntersects = function (ray) {
  10252. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10253. };
  10254. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10255. var intersectInfo = null;
  10256. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10257. var p0 = positions[indices[index]];
  10258. var p1 = positions[indices[index + 1]];
  10259. var p2 = positions[indices[index + 2]];
  10260. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10261. if (currentIntersectInfo) {
  10262. if (currentIntersectInfo.distance < 0) {
  10263. continue;
  10264. }
  10265. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10266. intersectInfo = currentIntersectInfo;
  10267. intersectInfo.faceId = index / 3;
  10268. if (fastCheck) {
  10269. break;
  10270. }
  10271. }
  10272. }
  10273. }
  10274. return intersectInfo;
  10275. };
  10276. // Clone
  10277. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10278. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10279. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10280. return result;
  10281. };
  10282. // Dispose
  10283. SubMesh.prototype.dispose = function () {
  10284. if (this._linesIndexBuffer) {
  10285. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10286. this._linesIndexBuffer = null;
  10287. }
  10288. // Remove from mesh
  10289. var index = this._mesh.subMeshes.indexOf(this);
  10290. this._mesh.subMeshes.splice(index, 1);
  10291. };
  10292. // Statics
  10293. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10294. var minVertexIndex = Number.MAX_VALUE;
  10295. var maxVertexIndex = -Number.MAX_VALUE;
  10296. renderingMesh = renderingMesh || mesh;
  10297. var indices = renderingMesh.getIndices();
  10298. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10299. var vertexIndex = indices[index];
  10300. if (vertexIndex < minVertexIndex)
  10301. minVertexIndex = vertexIndex;
  10302. if (vertexIndex > maxVertexIndex)
  10303. maxVertexIndex = vertexIndex;
  10304. }
  10305. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10306. };
  10307. return SubMesh;
  10308. })();
  10309. BABYLON.SubMesh = SubMesh;
  10310. })(BABYLON || (BABYLON = {}));
  10311. //# sourceMappingURL=babylon.subMesh.js.map
  10312. var BABYLON;
  10313. (function (BABYLON) {
  10314. var BaseTexture = (function () {
  10315. function BaseTexture(scene) {
  10316. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10317. this.hasAlpha = false;
  10318. this.getAlphaFromRGB = false;
  10319. this.level = 1;
  10320. this.isCube = false;
  10321. this.isRenderTarget = false;
  10322. this.animations = new Array();
  10323. this.coordinatesIndex = 0;
  10324. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10325. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10326. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10327. this.anisotropicFilteringLevel = 4;
  10328. this._scene = scene;
  10329. this._scene.textures.push(this);
  10330. }
  10331. BaseTexture.prototype.getScene = function () {
  10332. return this._scene;
  10333. };
  10334. BaseTexture.prototype.getTextureMatrix = function () {
  10335. return null;
  10336. };
  10337. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10338. return null;
  10339. };
  10340. BaseTexture.prototype.getInternalTexture = function () {
  10341. return this._texture;
  10342. };
  10343. BaseTexture.prototype.isReady = function () {
  10344. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10345. return true;
  10346. }
  10347. if (this._texture) {
  10348. return this._texture.isReady;
  10349. }
  10350. return false;
  10351. };
  10352. BaseTexture.prototype.getSize = function () {
  10353. if (this._texture._width) {
  10354. return { width: this._texture._width, height: this._texture._height };
  10355. }
  10356. if (this._texture._size) {
  10357. return { width: this._texture._size, height: this._texture._size };
  10358. }
  10359. return { width: 0, height: 0 };
  10360. };
  10361. BaseTexture.prototype.getBaseSize = function () {
  10362. if (!this.isReady())
  10363. return { width: 0, height: 0 };
  10364. if (this._texture._size) {
  10365. return { width: this._texture._size, height: this._texture._size };
  10366. }
  10367. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10368. };
  10369. BaseTexture.prototype.scale = function (ratio) {
  10370. };
  10371. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10372. get: function () {
  10373. return false;
  10374. },
  10375. enumerable: true,
  10376. configurable: true
  10377. });
  10378. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10379. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10380. for (var index = 0; index < texturesCache.length; index++) {
  10381. var texturesCacheEntry = texturesCache[index];
  10382. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10383. texturesCache.splice(index, 1);
  10384. return;
  10385. }
  10386. }
  10387. };
  10388. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  10389. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10390. for (var index = 0; index < texturesCache.length; index++) {
  10391. var texturesCacheEntry = texturesCache[index];
  10392. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10393. texturesCacheEntry.references++;
  10394. return texturesCacheEntry;
  10395. }
  10396. }
  10397. return null;
  10398. };
  10399. BaseTexture.prototype.delayLoad = function () {
  10400. };
  10401. BaseTexture.prototype.releaseInternalTexture = function () {
  10402. if (!this._texture) {
  10403. return;
  10404. }
  10405. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10406. this._texture.references--;
  10407. // Final reference ?
  10408. if (this._texture.references === 0) {
  10409. var index = texturesCache.indexOf(this._texture);
  10410. texturesCache.splice(index, 1);
  10411. this._scene.getEngine()._releaseTexture(this._texture);
  10412. delete this._texture;
  10413. }
  10414. };
  10415. BaseTexture.prototype.clone = function () {
  10416. return null;
  10417. };
  10418. BaseTexture.prototype.dispose = function () {
  10419. // Remove from scene
  10420. var index = this._scene.textures.indexOf(this);
  10421. if (index >= 0) {
  10422. this._scene.textures.splice(index, 1);
  10423. }
  10424. if (this._texture === undefined) {
  10425. return;
  10426. }
  10427. this.releaseInternalTexture();
  10428. // Callback
  10429. if (this.onDispose) {
  10430. this.onDispose();
  10431. }
  10432. };
  10433. return BaseTexture;
  10434. })();
  10435. BABYLON.BaseTexture = BaseTexture;
  10436. })(BABYLON || (BABYLON = {}));
  10437. //# sourceMappingURL=babylon.baseTexture.js.map
  10438. var BABYLON;
  10439. (function (BABYLON) {
  10440. var RenderingGroup = (function () {
  10441. function RenderingGroup(index, scene) {
  10442. this.index = index;
  10443. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10444. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10445. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10446. this._scene = scene;
  10447. }
  10448. RenderingGroup.prototype.render = function (customRenderFunction) {
  10449. if (customRenderFunction) {
  10450. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10451. return true;
  10452. }
  10453. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10454. return false;
  10455. }
  10456. var engine = this._scene.getEngine();
  10457. // Opaque
  10458. var subIndex;
  10459. var submesh;
  10460. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10461. submesh = this._opaqueSubMeshes.data[subIndex];
  10462. submesh.render();
  10463. }
  10464. // Alpha test
  10465. engine.setAlphaTesting(true);
  10466. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10467. submesh = this._alphaTestSubMeshes.data[subIndex];
  10468. submesh.render();
  10469. }
  10470. engine.setAlphaTesting(false);
  10471. // Transparent
  10472. if (this._transparentSubMeshes.length) {
  10473. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10474. submesh = this._transparentSubMeshes.data[subIndex];
  10475. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10476. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10477. }
  10478. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10479. sortedArray.sort(function (a, b) {
  10480. // Alpha index first
  10481. if (a._alphaIndex > b._alphaIndex) {
  10482. return 1;
  10483. }
  10484. if (a._alphaIndex < b._alphaIndex) {
  10485. return -1;
  10486. }
  10487. // Then distance to camera
  10488. if (a._distanceToCamera < b._distanceToCamera) {
  10489. return 1;
  10490. }
  10491. if (a._distanceToCamera > b._distanceToCamera) {
  10492. return -1;
  10493. }
  10494. return 0;
  10495. });
  10496. // Rendering
  10497. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10498. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10499. submesh = sortedArray[subIndex];
  10500. submesh.render();
  10501. }
  10502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10503. }
  10504. return true;
  10505. };
  10506. RenderingGroup.prototype.prepare = function () {
  10507. this._opaqueSubMeshes.reset();
  10508. this._transparentSubMeshes.reset();
  10509. this._alphaTestSubMeshes.reset();
  10510. };
  10511. RenderingGroup.prototype.dispatch = function (subMesh) {
  10512. var material = subMesh.getMaterial();
  10513. var mesh = subMesh.getMesh();
  10514. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10515. this._transparentSubMeshes.push(subMesh);
  10516. } else if (material.needAlphaTesting()) {
  10517. this._alphaTestSubMeshes.push(subMesh);
  10518. } else {
  10519. this._opaqueSubMeshes.push(subMesh); // Opaque
  10520. }
  10521. };
  10522. return RenderingGroup;
  10523. })();
  10524. BABYLON.RenderingGroup = RenderingGroup;
  10525. })(BABYLON || (BABYLON = {}));
  10526. //# sourceMappingURL=babylon.renderingGroup.js.map
  10527. var BABYLON;
  10528. (function (BABYLON) {
  10529. var RenderingManager = (function () {
  10530. function RenderingManager(scene) {
  10531. this._renderingGroups = new Array();
  10532. this._scene = scene;
  10533. }
  10534. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10535. if (this._scene._activeParticleSystems.length === 0) {
  10536. return;
  10537. }
  10538. // Particles
  10539. var beforeParticlesDate = BABYLON.Tools.Now;
  10540. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10541. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10542. if (particleSystem.renderingGroupId !== index) {
  10543. continue;
  10544. }
  10545. this._clearDepthBuffer();
  10546. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10547. this._scene._activeParticles += particleSystem.render();
  10548. }
  10549. }
  10550. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10551. };
  10552. RenderingManager.prototype._renderSprites = function (index) {
  10553. if (this._scene.spriteManagers.length === 0) {
  10554. return;
  10555. }
  10556. // Sprites
  10557. var beforeSpritessDate = BABYLON.Tools.Now;
  10558. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10559. var spriteManager = this._scene.spriteManagers[id];
  10560. if (spriteManager.renderingGroupId === index) {
  10561. this._clearDepthBuffer();
  10562. spriteManager.render();
  10563. }
  10564. }
  10565. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10566. };
  10567. RenderingManager.prototype._clearDepthBuffer = function () {
  10568. if (this._depthBufferAlreadyCleaned) {
  10569. return;
  10570. }
  10571. this._scene.getEngine().clear(0, false, true);
  10572. this._depthBufferAlreadyCleaned = true;
  10573. };
  10574. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10575. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10576. this._depthBufferAlreadyCleaned = false;
  10577. var renderingGroup = this._renderingGroups[index];
  10578. if (renderingGroup) {
  10579. this._clearDepthBuffer();
  10580. if (!renderingGroup.render(customRenderFunction)) {
  10581. this._renderingGroups.splice(index, 1);
  10582. }
  10583. }
  10584. this._renderSprites(index);
  10585. if (renderParticles) {
  10586. this._renderParticles(index, activeMeshes);
  10587. }
  10588. }
  10589. };
  10590. RenderingManager.prototype.reset = function () {
  10591. for (var index in this._renderingGroups) {
  10592. var renderingGroup = this._renderingGroups[index];
  10593. renderingGroup.prepare();
  10594. }
  10595. };
  10596. RenderingManager.prototype.dispatch = function (subMesh) {
  10597. var mesh = subMesh.getMesh();
  10598. var renderingGroupId = mesh.renderingGroupId || 0;
  10599. if (!this._renderingGroups[renderingGroupId]) {
  10600. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10601. }
  10602. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10603. };
  10604. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10605. return RenderingManager;
  10606. })();
  10607. BABYLON.RenderingManager = RenderingManager;
  10608. })(BABYLON || (BABYLON = {}));
  10609. //# sourceMappingURL=babylon.renderingManager.js.map
  10610. var BABYLON;
  10611. (function (BABYLON) {
  10612. var Texture = (function (_super) {
  10613. __extends(Texture, _super);
  10614. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10615. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10616. if (typeof onLoad === "undefined") { onLoad = null; }
  10617. if (typeof onError === "undefined") { onError = null; }
  10618. if (typeof buffer === "undefined") { buffer = null; }
  10619. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10620. _super.call(this, scene);
  10621. this.uOffset = 0;
  10622. this.vOffset = 0;
  10623. this.uScale = 1.0;
  10624. this.vScale = 1.0;
  10625. this.uAng = 0;
  10626. this.vAng = 0;
  10627. this.wAng = 0;
  10628. this.name = url;
  10629. this.url = url;
  10630. this._noMipmap = noMipmap;
  10631. this._invertY = invertY;
  10632. this._samplingMode = samplingMode;
  10633. this._buffer = buffer;
  10634. this._deleteBuffer = deleteBuffer;
  10635. if (!url) {
  10636. return;
  10637. }
  10638. this._texture = this._getFromCache(url, noMipmap);
  10639. if (!this._texture) {
  10640. if (!scene.useDelayedTextureLoading) {
  10641. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10642. if (deleteBuffer) {
  10643. delete this._buffer;
  10644. }
  10645. } else {
  10646. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10647. }
  10648. }
  10649. }
  10650. Texture.prototype.delayLoad = function () {
  10651. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10652. return;
  10653. }
  10654. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10655. this._texture = this._getFromCache(this.url, this._noMipmap);
  10656. if (!this._texture) {
  10657. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10658. if (this._deleteBuffer) {
  10659. delete this._buffer;
  10660. }
  10661. }
  10662. };
  10663. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10664. x -= this.uOffset + 0.5;
  10665. y -= this.vOffset + 0.5;
  10666. z -= 0.5;
  10667. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10668. t.x *= this.uScale;
  10669. t.y *= this.vScale;
  10670. t.x += 0.5;
  10671. t.y += 0.5;
  10672. t.z += 0.5;
  10673. };
  10674. Texture.prototype.getTextureMatrix = function () {
  10675. 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) {
  10676. return this._cachedTextureMatrix;
  10677. }
  10678. this._cachedUOffset = this.uOffset;
  10679. this._cachedVOffset = this.vOffset;
  10680. this._cachedUScale = this.uScale;
  10681. this._cachedVScale = this.vScale;
  10682. this._cachedUAng = this.uAng;
  10683. this._cachedVAng = this.vAng;
  10684. this._cachedWAng = this.wAng;
  10685. if (!this._cachedTextureMatrix) {
  10686. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10687. this._rowGenerationMatrix = new BABYLON.Matrix();
  10688. this._t0 = BABYLON.Vector3.Zero();
  10689. this._t1 = BABYLON.Vector3.Zero();
  10690. this._t2 = BABYLON.Vector3.Zero();
  10691. }
  10692. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10693. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10694. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10695. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10696. this._t1.subtractInPlace(this._t0);
  10697. this._t2.subtractInPlace(this._t0);
  10698. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10699. this._cachedTextureMatrix.m[0] = this._t1.x;
  10700. this._cachedTextureMatrix.m[1] = this._t1.y;
  10701. this._cachedTextureMatrix.m[2] = this._t1.z;
  10702. this._cachedTextureMatrix.m[4] = this._t2.x;
  10703. this._cachedTextureMatrix.m[5] = this._t2.y;
  10704. this._cachedTextureMatrix.m[6] = this._t2.z;
  10705. this._cachedTextureMatrix.m[8] = this._t0.x;
  10706. this._cachedTextureMatrix.m[9] = this._t0.y;
  10707. this._cachedTextureMatrix.m[10] = this._t0.z;
  10708. return this._cachedTextureMatrix;
  10709. };
  10710. Texture.prototype.getReflectionTextureMatrix = function () {
  10711. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10712. return this._cachedTextureMatrix;
  10713. }
  10714. if (!this._cachedTextureMatrix) {
  10715. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10716. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10717. }
  10718. this._cachedCoordinatesMode = this.coordinatesMode;
  10719. switch (this.coordinatesMode) {
  10720. case BABYLON.Texture.SPHERICAL_MODE:
  10721. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10722. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10723. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10724. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10725. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10726. break;
  10727. case BABYLON.Texture.PLANAR_MODE:
  10728. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10729. this._cachedTextureMatrix[0] = this.uScale;
  10730. this._cachedTextureMatrix[5] = this.vScale;
  10731. this._cachedTextureMatrix[12] = this.uOffset;
  10732. this._cachedTextureMatrix[13] = this.vOffset;
  10733. break;
  10734. case BABYLON.Texture.PROJECTION_MODE:
  10735. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10736. this._projectionModeMatrix.m[0] = 0.5;
  10737. this._projectionModeMatrix.m[5] = -0.5;
  10738. this._projectionModeMatrix.m[10] = 0.0;
  10739. this._projectionModeMatrix.m[12] = 0.5;
  10740. this._projectionModeMatrix.m[13] = 0.5;
  10741. this._projectionModeMatrix.m[14] = 1.0;
  10742. this._projectionModeMatrix.m[15] = 1.0;
  10743. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10744. break;
  10745. default:
  10746. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10747. break;
  10748. }
  10749. return this._cachedTextureMatrix;
  10750. };
  10751. Texture.prototype.clone = function () {
  10752. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10753. // Base texture
  10754. newTexture.hasAlpha = this.hasAlpha;
  10755. newTexture.level = this.level;
  10756. newTexture.wrapU = this.wrapU;
  10757. newTexture.wrapV = this.wrapV;
  10758. newTexture.coordinatesIndex = this.coordinatesIndex;
  10759. newTexture.coordinatesMode = this.coordinatesMode;
  10760. // Texture
  10761. newTexture.uOffset = this.uOffset;
  10762. newTexture.vOffset = this.vOffset;
  10763. newTexture.uScale = this.uScale;
  10764. newTexture.vScale = this.vScale;
  10765. newTexture.uAng = this.uAng;
  10766. newTexture.vAng = this.vAng;
  10767. newTexture.wAng = this.wAng;
  10768. return newTexture;
  10769. };
  10770. // Statics
  10771. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10772. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10773. if (typeof onLoad === "undefined") { onLoad = null; }
  10774. if (typeof onError === "undefined") { onError = null; }
  10775. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10776. };
  10777. Texture.NEAREST_SAMPLINGMODE = 1;
  10778. Texture.BILINEAR_SAMPLINGMODE = 2;
  10779. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10780. Texture.EXPLICIT_MODE = 0;
  10781. Texture.SPHERICAL_MODE = 1;
  10782. Texture.PLANAR_MODE = 2;
  10783. Texture.CUBIC_MODE = 3;
  10784. Texture.PROJECTION_MODE = 4;
  10785. Texture.SKYBOX_MODE = 5;
  10786. Texture.CLAMP_ADDRESSMODE = 0;
  10787. Texture.WRAP_ADDRESSMODE = 1;
  10788. Texture.MIRROR_ADDRESSMODE = 2;
  10789. return Texture;
  10790. })(BABYLON.BaseTexture);
  10791. BABYLON.Texture = Texture;
  10792. })(BABYLON || (BABYLON = {}));
  10793. //# sourceMappingURL=babylon.texture.js.map
  10794. var BABYLON;
  10795. (function (BABYLON) {
  10796. var CubeTexture = (function (_super) {
  10797. __extends(CubeTexture, _super);
  10798. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10799. _super.call(this, scene);
  10800. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10801. this.name = rootUrl;
  10802. this.url = rootUrl;
  10803. this._noMipmap = noMipmap;
  10804. this.hasAlpha = false;
  10805. this._texture = this._getFromCache(rootUrl, noMipmap);
  10806. if (!extensions) {
  10807. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10808. }
  10809. this._extensions = extensions;
  10810. if (!this._texture) {
  10811. if (!scene.useDelayedTextureLoading) {
  10812. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10813. } else {
  10814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10815. }
  10816. }
  10817. this.isCube = true;
  10818. this._textureMatrix = BABYLON.Matrix.Identity();
  10819. }
  10820. CubeTexture.prototype.clone = function () {
  10821. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10822. // Base texture
  10823. newTexture.level = this.level;
  10824. newTexture.wrapU = this.wrapU;
  10825. newTexture.wrapV = this.wrapV;
  10826. newTexture.coordinatesIndex = this.coordinatesIndex;
  10827. newTexture.coordinatesMode = this.coordinatesMode;
  10828. return newTexture;
  10829. };
  10830. // Methods
  10831. CubeTexture.prototype.delayLoad = function () {
  10832. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10833. return;
  10834. }
  10835. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10836. this._texture = this._getFromCache(this.url, this._noMipmap);
  10837. if (!this._texture) {
  10838. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10839. }
  10840. };
  10841. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10842. return this._textureMatrix;
  10843. };
  10844. return CubeTexture;
  10845. })(BABYLON.BaseTexture);
  10846. BABYLON.CubeTexture = CubeTexture;
  10847. })(BABYLON || (BABYLON = {}));
  10848. //# sourceMappingURL=babylon.cubeTexture.js.map
  10849. var BABYLON;
  10850. (function (BABYLON) {
  10851. var RenderTargetTexture = (function (_super) {
  10852. __extends(RenderTargetTexture, _super);
  10853. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10854. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10855. _super.call(this, null, scene, !generateMipMaps);
  10856. this.renderList = new Array();
  10857. this.renderParticles = true;
  10858. this.renderSprites = false;
  10859. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10860. this._currentRefreshId = -1;
  10861. this._refreshRate = 1;
  10862. this.name = name;
  10863. this.isRenderTarget = true;
  10864. this._size = size;
  10865. this._generateMipMaps = generateMipMaps;
  10866. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10867. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10868. // Rendering groups
  10869. this._renderingManager = new BABYLON.RenderingManager(scene);
  10870. }
  10871. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10872. this._currentRefreshId = -1;
  10873. };
  10874. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10875. get: function () {
  10876. return this._refreshRate;
  10877. },
  10878. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10879. set: function (value) {
  10880. this._refreshRate = value;
  10881. this.resetRefreshCounter();
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. RenderTargetTexture.prototype._shouldRender = function () {
  10887. if (this._currentRefreshId === -1) {
  10888. this._currentRefreshId = 1;
  10889. return true;
  10890. }
  10891. if (this.refreshRate == this._currentRefreshId) {
  10892. this._currentRefreshId = 1;
  10893. return true;
  10894. }
  10895. this._currentRefreshId++;
  10896. return false;
  10897. };
  10898. RenderTargetTexture.prototype.isReady = function () {
  10899. if (!this.getScene().renderTargetsEnabled) {
  10900. return false;
  10901. }
  10902. return _super.prototype.isReady.call(this);
  10903. };
  10904. RenderTargetTexture.prototype.getRenderSize = function () {
  10905. return this._size;
  10906. };
  10907. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10908. get: function () {
  10909. return true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. RenderTargetTexture.prototype.scale = function (ratio) {
  10915. var newSize = this._size * ratio;
  10916. this.resize(newSize, this._generateMipMaps);
  10917. };
  10918. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10919. this.releaseInternalTexture();
  10920. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10921. };
  10922. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10923. var scene = this.getScene();
  10924. var engine = scene.getEngine();
  10925. if (this._waitingRenderList) {
  10926. this.renderList = [];
  10927. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10928. var id = this._waitingRenderList[index];
  10929. this.renderList.push(scene.getMeshByID(id));
  10930. }
  10931. delete this._waitingRenderList;
  10932. }
  10933. if (!this.renderList) {
  10934. return;
  10935. }
  10936. // Bind
  10937. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10938. engine.bindFramebuffer(this._texture);
  10939. }
  10940. // Clear
  10941. engine.clear(scene.clearColor, true, true);
  10942. this._renderingManager.reset();
  10943. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10944. var mesh = this.renderList[meshIndex];
  10945. if (mesh) {
  10946. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10947. // Reset _currentRefreshId
  10948. this.resetRefreshCounter();
  10949. continue;
  10950. }
  10951. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10952. mesh._activate(scene.getRenderId());
  10953. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10954. var subMesh = mesh.subMeshes[subIndex];
  10955. scene._activeVertices += subMesh.indexCount;
  10956. this._renderingManager.dispatch(subMesh);
  10957. }
  10958. }
  10959. }
  10960. }
  10961. if (!this._doNotChangeAspectRatio) {
  10962. scene.updateTransformMatrix(true);
  10963. }
  10964. if (this.onBeforeRender) {
  10965. this.onBeforeRender();
  10966. }
  10967. // Render
  10968. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10969. if (useCameraPostProcess) {
  10970. scene.postProcessManager._finalizeFrame(false, this._texture);
  10971. }
  10972. if (this.onAfterRender) {
  10973. this.onAfterRender();
  10974. }
  10975. // Unbind
  10976. engine.unBindFramebuffer(this._texture);
  10977. if (!this._doNotChangeAspectRatio) {
  10978. scene.updateTransformMatrix(true);
  10979. }
  10980. };
  10981. RenderTargetTexture.prototype.clone = function () {
  10982. var textureSize = this.getSize();
  10983. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10984. // Base texture
  10985. newTexture.hasAlpha = this.hasAlpha;
  10986. newTexture.level = this.level;
  10987. // RenderTarget Texture
  10988. newTexture.coordinatesMode = this.coordinatesMode;
  10989. newTexture.renderList = this.renderList.slice(0);
  10990. return newTexture;
  10991. };
  10992. return RenderTargetTexture;
  10993. })(BABYLON.Texture);
  10994. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10995. })(BABYLON || (BABYLON = {}));
  10996. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  10997. var BABYLON;
  10998. (function (BABYLON) {
  10999. var ProceduralTexture = (function (_super) {
  11000. __extends(ProceduralTexture, _super);
  11001. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11002. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11003. _super.call(this, null, scene, !generateMipMaps);
  11004. this._currentRefreshId = -1;
  11005. this._refreshRate = 1;
  11006. this._vertexDeclaration = [2];
  11007. this._vertexStrideSize = 2 * 4;
  11008. this._uniforms = new Array();
  11009. this._samplers = new Array();
  11010. this._textures = new Array();
  11011. this._floats = new Array();
  11012. this._floatsArrays = {};
  11013. this._colors3 = new Array();
  11014. this._colors4 = new Array();
  11015. this._vectors2 = new Array();
  11016. this._vectors3 = new Array();
  11017. this._matrices = new Array();
  11018. this._fallbackTextureUsed = false;
  11019. scene._proceduralTextures.push(this);
  11020. this.name = name;
  11021. this.isRenderTarget = true;
  11022. this._size = size;
  11023. this._generateMipMaps = generateMipMaps;
  11024. this.setFragment(fragment);
  11025. this._fallbackTexture = fallbackTexture;
  11026. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11027. // VBO
  11028. var vertices = [];
  11029. vertices.push(1, 1);
  11030. vertices.push(-1, 1);
  11031. vertices.push(-1, -1);
  11032. vertices.push(1, -1);
  11033. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11034. // Indices
  11035. var indices = [];
  11036. indices.push(0);
  11037. indices.push(1);
  11038. indices.push(2);
  11039. indices.push(0);
  11040. indices.push(2);
  11041. indices.push(3);
  11042. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11043. }
  11044. ProceduralTexture.prototype.reset = function () {
  11045. if (this._effect === undefined) {
  11046. return;
  11047. }
  11048. var engine = this.getScene().getEngine();
  11049. engine._releaseEffect(this._effect);
  11050. };
  11051. ProceduralTexture.prototype.isReady = function () {
  11052. var _this = this;
  11053. var engine = this.getScene().getEngine();
  11054. var shaders;
  11055. if (!this._fragment) {
  11056. return false;
  11057. }
  11058. if (this._fallbackTextureUsed) {
  11059. return true;
  11060. }
  11061. if (this._fragment.fragmentElement !== undefined) {
  11062. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11063. } else {
  11064. shaders = { vertex: "procedural", fragment: this._fragment };
  11065. }
  11066. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11067. _this.releaseInternalTexture();
  11068. if (_this._fallbackTexture) {
  11069. _this._texture = _this._fallbackTexture._texture;
  11070. _this._texture.references++;
  11071. }
  11072. _this._fallbackTextureUsed = true;
  11073. });
  11074. return this._effect.isReady();
  11075. };
  11076. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11077. this._currentRefreshId = -1;
  11078. };
  11079. ProceduralTexture.prototype.setFragment = function (fragment) {
  11080. this._fragment = fragment;
  11081. };
  11082. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11083. get: function () {
  11084. return this._refreshRate;
  11085. },
  11086. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11087. set: function (value) {
  11088. this._refreshRate = value;
  11089. this.resetRefreshCounter();
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. ProceduralTexture.prototype._shouldRender = function () {
  11095. if (!this.isReady() || !this._texture) {
  11096. return false;
  11097. }
  11098. if (this._fallbackTextureUsed) {
  11099. return false;
  11100. }
  11101. if (this._currentRefreshId === -1) {
  11102. this._currentRefreshId = 1;
  11103. return true;
  11104. }
  11105. if (this.refreshRate === this._currentRefreshId) {
  11106. this._currentRefreshId = 1;
  11107. return true;
  11108. }
  11109. this._currentRefreshId++;
  11110. return false;
  11111. };
  11112. ProceduralTexture.prototype.getRenderSize = function () {
  11113. return this._size;
  11114. };
  11115. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11116. if (this._fallbackTextureUsed) {
  11117. return;
  11118. }
  11119. this.releaseInternalTexture();
  11120. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11121. };
  11122. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11123. if (this._uniforms.indexOf(uniformName) === -1) {
  11124. this._uniforms.push(uniformName);
  11125. }
  11126. };
  11127. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11128. if (this._samplers.indexOf(name) === -1) {
  11129. this._samplers.push(name);
  11130. }
  11131. this._textures[name] = texture;
  11132. return this;
  11133. };
  11134. ProceduralTexture.prototype.setFloat = function (name, value) {
  11135. this._checkUniform(name);
  11136. this._floats[name] = value;
  11137. return this;
  11138. };
  11139. ProceduralTexture.prototype.setFloats = function (name, value) {
  11140. this._checkUniform(name);
  11141. this._floatsArrays[name] = value;
  11142. return this;
  11143. };
  11144. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11145. this._checkUniform(name);
  11146. this._colors3[name] = value;
  11147. return this;
  11148. };
  11149. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11150. this._checkUniform(name);
  11151. this._colors4[name] = value;
  11152. return this;
  11153. };
  11154. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11155. this._checkUniform(name);
  11156. this._vectors2[name] = value;
  11157. return this;
  11158. };
  11159. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11160. this._checkUniform(name);
  11161. this._vectors3[name] = value;
  11162. return this;
  11163. };
  11164. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11165. this._checkUniform(name);
  11166. this._matrices[name] = value;
  11167. return this;
  11168. };
  11169. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11170. var scene = this.getScene();
  11171. var engine = scene.getEngine();
  11172. engine.bindFramebuffer(this._texture);
  11173. // Clear
  11174. engine.clear(scene.clearColor, true, true);
  11175. // Render
  11176. engine.enableEffect(this._effect);
  11177. engine.setState(false);
  11178. for (var name in this._textures) {
  11179. this._effect.setTexture(name, this._textures[name]);
  11180. }
  11181. for (name in this._floats) {
  11182. this._effect.setFloat(name, this._floats[name]);
  11183. }
  11184. for (name in this._floatsArrays) {
  11185. this._effect.setArray(name, this._floatsArrays[name]);
  11186. }
  11187. for (name in this._colors3) {
  11188. this._effect.setColor3(name, this._colors3[name]);
  11189. }
  11190. for (name in this._colors4) {
  11191. var color = this._colors4[name];
  11192. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11193. }
  11194. for (name in this._vectors2) {
  11195. this._effect.setVector2(name, this._vectors2[name]);
  11196. }
  11197. for (name in this._vectors3) {
  11198. this._effect.setVector3(name, this._vectors3[name]);
  11199. }
  11200. for (name in this._matrices) {
  11201. this._effect.setMatrix(name, this._matrices[name]);
  11202. }
  11203. // VBOs
  11204. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11205. // Draw order
  11206. engine.draw(true, 0, 6);
  11207. // Unbind
  11208. engine.unBindFramebuffer(this._texture);
  11209. };
  11210. ProceduralTexture.prototype.clone = function () {
  11211. var textureSize = this.getSize();
  11212. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11213. // Base texture
  11214. newTexture.hasAlpha = this.hasAlpha;
  11215. newTexture.level = this.level;
  11216. // RenderTarget Texture
  11217. newTexture.coordinatesMode = this.coordinatesMode;
  11218. return newTexture;
  11219. };
  11220. ProceduralTexture.prototype.dispose = function () {
  11221. var index = this.getScene()._proceduralTextures.indexOf(this);
  11222. if (index >= 0) {
  11223. this.getScene()._proceduralTextures.splice(index, 1);
  11224. }
  11225. _super.prototype.dispose.call(this);
  11226. };
  11227. return ProceduralTexture;
  11228. })(BABYLON.Texture);
  11229. BABYLON.ProceduralTexture = ProceduralTexture;
  11230. })(BABYLON || (BABYLON = {}));
  11231. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11232. var BABYLON;
  11233. (function (BABYLON) {
  11234. var WoodProceduralTexture = (function (_super) {
  11235. __extends(WoodProceduralTexture, _super);
  11236. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11237. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11238. this._ampScale = 100.0;
  11239. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11240. this.updateShaderUniforms();
  11241. this.refreshRate = 0;
  11242. }
  11243. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11244. this.setFloat("ampScale", this._ampScale);
  11245. this.setColor3("woodColor", this._woodColor);
  11246. };
  11247. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11248. get: function () {
  11249. return this._ampScale;
  11250. },
  11251. set: function (value) {
  11252. this._ampScale = value;
  11253. this.updateShaderUniforms();
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11259. get: function () {
  11260. return this._woodColor;
  11261. },
  11262. set: function (value) {
  11263. this._woodColor = value;
  11264. this.updateShaderUniforms();
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. return WoodProceduralTexture;
  11270. })(BABYLON.ProceduralTexture);
  11271. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11272. var FireProceduralTexture = (function (_super) {
  11273. __extends(FireProceduralTexture, _super);
  11274. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11275. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11276. this._time = 0.0;
  11277. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11278. this._shift = 1.6;
  11279. this._autoGenerateTime = true;
  11280. this._alphaThreshold = 0.5;
  11281. this._fireColors = FireProceduralTexture.RedFireColors;
  11282. this.updateShaderUniforms();
  11283. this.refreshRate = 1;
  11284. }
  11285. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11286. this.setFloat("time", this._time);
  11287. this.setVector2("speed", this._speed);
  11288. this.setFloat("shift", this._shift);
  11289. this.setColor3("c1", this._fireColors[0]);
  11290. this.setColor3("c2", this._fireColors[1]);
  11291. this.setColor3("c3", this._fireColors[2]);
  11292. this.setColor3("c4", this._fireColors[3]);
  11293. this.setColor3("c5", this._fireColors[4]);
  11294. this.setColor3("c6", this._fireColors[5]);
  11295. this.setFloat("alphaThreshold", this._alphaThreshold);
  11296. };
  11297. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11298. if (this._autoGenerateTime) {
  11299. this._time += this.getScene().getAnimationRatio() * 0.03;
  11300. this.updateShaderUniforms();
  11301. }
  11302. _super.prototype.render.call(this, useCameraPostProcess);
  11303. };
  11304. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11305. get: function () {
  11306. return [
  11307. new BABYLON.Color3(0.5, 0.0, 1.0),
  11308. new BABYLON.Color3(0.9, 0.0, 1.0),
  11309. new BABYLON.Color3(0.2, 0.0, 1.0),
  11310. new BABYLON.Color3(1.0, 0.9, 1.0),
  11311. new BABYLON.Color3(0.1, 0.1, 1.0),
  11312. new BABYLON.Color3(0.9, 0.9, 1.0)
  11313. ];
  11314. },
  11315. enumerable: true,
  11316. configurable: true
  11317. });
  11318. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11319. get: function () {
  11320. return [
  11321. new BABYLON.Color3(0.5, 1.0, 0.0),
  11322. new BABYLON.Color3(0.5, 1.0, 0.0),
  11323. new BABYLON.Color3(0.3, 0.4, 0.0),
  11324. new BABYLON.Color3(0.5, 1.0, 0.0),
  11325. new BABYLON.Color3(0.2, 0.0, 0.0),
  11326. new BABYLON.Color3(0.5, 1.0, 0.0)
  11327. ];
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11333. get: function () {
  11334. return [
  11335. new BABYLON.Color3(0.5, 0.0, 0.1),
  11336. new BABYLON.Color3(0.9, 0.0, 0.0),
  11337. new BABYLON.Color3(0.2, 0.0, 0.0),
  11338. new BABYLON.Color3(1.0, 0.9, 0.0),
  11339. new BABYLON.Color3(0.1, 0.1, 0.1),
  11340. new BABYLON.Color3(0.9, 0.9, 0.9)
  11341. ];
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11347. get: function () {
  11348. return [
  11349. new BABYLON.Color3(0.1, 0.0, 0.5),
  11350. new BABYLON.Color3(0.0, 0.0, 0.5),
  11351. new BABYLON.Color3(0.1, 0.0, 0.2),
  11352. new BABYLON.Color3(0.0, 0.0, 1.0),
  11353. new BABYLON.Color3(0.1, 0.2, 0.3),
  11354. new BABYLON.Color3(0.0, 0.2, 0.9)
  11355. ];
  11356. },
  11357. enumerable: true,
  11358. configurable: true
  11359. });
  11360. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11361. get: function () {
  11362. return this._fireColors;
  11363. },
  11364. set: function (value) {
  11365. this._fireColors = value;
  11366. this.updateShaderUniforms();
  11367. },
  11368. enumerable: true,
  11369. configurable: true
  11370. });
  11371. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11372. get: function () {
  11373. return this._time;
  11374. },
  11375. set: function (value) {
  11376. this._time = value;
  11377. this.updateShaderUniforms();
  11378. },
  11379. enumerable: true,
  11380. configurable: true
  11381. });
  11382. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11383. get: function () {
  11384. return this._speed;
  11385. },
  11386. set: function (value) {
  11387. this._speed = value;
  11388. this.updateShaderUniforms();
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11394. get: function () {
  11395. return this._shift;
  11396. },
  11397. set: function (value) {
  11398. this._shift = value;
  11399. this.updateShaderUniforms();
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11405. get: function () {
  11406. return this._alphaThreshold;
  11407. },
  11408. set: function (value) {
  11409. this._alphaThreshold = value;
  11410. this.updateShaderUniforms();
  11411. },
  11412. enumerable: true,
  11413. configurable: true
  11414. });
  11415. return FireProceduralTexture;
  11416. })(BABYLON.ProceduralTexture);
  11417. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11418. var CloudProceduralTexture = (function (_super) {
  11419. __extends(CloudProceduralTexture, _super);
  11420. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11421. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11422. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11423. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11424. this.updateShaderUniforms();
  11425. this.refreshRate = 0;
  11426. }
  11427. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11428. this.setColor3("skyColor", this._skyColor);
  11429. this.setColor3("cloudColor", this._cloudColor);
  11430. };
  11431. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11432. get: function () {
  11433. return this._skyColor;
  11434. },
  11435. set: function (value) {
  11436. this._skyColor = value;
  11437. this.updateShaderUniforms();
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11443. get: function () {
  11444. return this._cloudColor;
  11445. },
  11446. set: function (value) {
  11447. this._cloudColor = value;
  11448. this.updateShaderUniforms();
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. return CloudProceduralTexture;
  11454. })(BABYLON.ProceduralTexture);
  11455. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11456. var GrassProceduralTexture = (function (_super) {
  11457. __extends(GrassProceduralTexture, _super);
  11458. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11459. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11460. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11461. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11462. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11463. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11464. this._grassColors = [
  11465. new BABYLON.Color3(0.29, 0.38, 0.02),
  11466. new BABYLON.Color3(0.36, 0.49, 0.09),
  11467. new BABYLON.Color3(0.51, 0.6, 0.28)
  11468. ];
  11469. this.updateShaderUniforms();
  11470. this.refreshRate = 0;
  11471. }
  11472. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11473. this.setColor3("herb1Color", this._grassColors[0]);
  11474. this.setColor3("herb2Color", this._grassColors[1]);
  11475. this.setColor3("herb3Color", this._grassColors[2]);
  11476. this.setColor3("groundColor", this._groundColor);
  11477. };
  11478. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11479. get: function () {
  11480. return this._grassColors;
  11481. },
  11482. set: function (value) {
  11483. this._grassColors = value;
  11484. this.updateShaderUniforms();
  11485. },
  11486. enumerable: true,
  11487. configurable: true
  11488. });
  11489. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11490. get: function () {
  11491. return this._groundColor;
  11492. },
  11493. set: function (value) {
  11494. this.groundColor = value;
  11495. this.updateShaderUniforms();
  11496. },
  11497. enumerable: true,
  11498. configurable: true
  11499. });
  11500. return GrassProceduralTexture;
  11501. })(BABYLON.ProceduralTexture);
  11502. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11503. var RoadProceduralTexture = (function (_super) {
  11504. __extends(RoadProceduralTexture, _super);
  11505. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11506. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11507. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11508. this.updateShaderUniforms();
  11509. this.refreshRate = 0;
  11510. }
  11511. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11512. this.setColor3("roadColor", this._roadColor);
  11513. };
  11514. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11515. get: function () {
  11516. return this._roadColor;
  11517. },
  11518. set: function (value) {
  11519. this._roadColor = value;
  11520. this.updateShaderUniforms();
  11521. },
  11522. enumerable: true,
  11523. configurable: true
  11524. });
  11525. return RoadProceduralTexture;
  11526. })(BABYLON.ProceduralTexture);
  11527. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11528. var BrickProceduralTexture = (function (_super) {
  11529. __extends(BrickProceduralTexture, _super);
  11530. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11531. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11532. this._numberOfBricksHeight = 15;
  11533. this._numberOfBricksWidth = 5;
  11534. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11535. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11536. this.updateShaderUniforms();
  11537. this.refreshRate = 0;
  11538. }
  11539. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11540. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11541. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11542. this.setColor3("brickColor", this._brickColor);
  11543. this.setColor3("jointColor", this._jointColor);
  11544. };
  11545. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11546. get: function () {
  11547. return this._numberOfBricksHeight;
  11548. },
  11549. enumerable: true,
  11550. configurable: true
  11551. });
  11552. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11553. set: function (value) {
  11554. this._numberOfBricksHeight = value;
  11555. this.updateShaderUniforms();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11561. get: function () {
  11562. return this._numberOfBricksWidth;
  11563. },
  11564. set: function (value) {
  11565. this._numberOfBricksHeight = value;
  11566. this.updateShaderUniforms();
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11572. get: function () {
  11573. return this._jointColor;
  11574. },
  11575. set: function (value) {
  11576. this._jointColor = value;
  11577. this.updateShaderUniforms();
  11578. },
  11579. enumerable: true,
  11580. configurable: true
  11581. });
  11582. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11583. get: function () {
  11584. return this._brickColor;
  11585. },
  11586. set: function (value) {
  11587. this._brickColor = value;
  11588. this.updateShaderUniforms();
  11589. },
  11590. enumerable: true,
  11591. configurable: true
  11592. });
  11593. return BrickProceduralTexture;
  11594. })(BABYLON.ProceduralTexture);
  11595. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11596. var MarbleProceduralTexture = (function (_super) {
  11597. __extends(MarbleProceduralTexture, _super);
  11598. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11599. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11600. this._numberOfTilesHeight = 3;
  11601. this._numberOfTilesWidth = 3;
  11602. this._amplitude = 9.0;
  11603. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11604. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11605. this.updateShaderUniforms();
  11606. this.refreshRate = 0;
  11607. }
  11608. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11609. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11610. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11611. this.setFloat("amplitude", this._amplitude);
  11612. this.setColor3("marbleColor", this._marbleColor);
  11613. this.setColor3("jointColor", this._jointColor);
  11614. };
  11615. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11616. get: function () {
  11617. return this._numberOfTilesHeight;
  11618. },
  11619. set: function (value) {
  11620. this._numberOfTilesHeight = value;
  11621. this.updateShaderUniforms();
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11627. get: function () {
  11628. return this._numberOfTilesWidth;
  11629. },
  11630. set: function (value) {
  11631. this._numberOfTilesWidth = value;
  11632. this.updateShaderUniforms();
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11638. get: function () {
  11639. return this._jointColor;
  11640. },
  11641. set: function (value) {
  11642. this._jointColor = value;
  11643. this.updateShaderUniforms();
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11649. get: function () {
  11650. return this._marbleColor;
  11651. },
  11652. set: function (value) {
  11653. this._marbleColor = value;
  11654. this.updateShaderUniforms();
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. return MarbleProceduralTexture;
  11660. })(BABYLON.ProceduralTexture);
  11661. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11662. })(BABYLON || (BABYLON = {}));
  11663. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11664. var BABYLON;
  11665. (function (BABYLON) {
  11666. var CustomProceduralTexture = (function (_super) {
  11667. __extends(CustomProceduralTexture, _super);
  11668. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11669. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11670. this._animate = true;
  11671. this._time = 0;
  11672. this._texturePath = texturePath;
  11673. //Try to load json
  11674. this.loadJson(texturePath);
  11675. this.refreshRate = 1;
  11676. }
  11677. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11678. var _this = this;
  11679. var that = this;
  11680. function noConfigFile() {
  11681. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11682. try {
  11683. that.setFragment(that._texturePath);
  11684. } catch (ex) {
  11685. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11686. }
  11687. }
  11688. var configFileUrl = jsonUrl + "/config.json";
  11689. var xhr = new XMLHttpRequest();
  11690. xhr.open("GET", configFileUrl, true);
  11691. xhr.addEventListener("load", function () {
  11692. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11693. try {
  11694. _this._config = JSON.parse(xhr.response);
  11695. _this.updateShaderUniforms();
  11696. _this.updateTextures();
  11697. _this.setFragment(_this._texturePath + "/custom");
  11698. _this._animate = _this._config.animate;
  11699. _this.refreshRate = _this._config.refreshrate;
  11700. } catch (ex) {
  11701. noConfigFile();
  11702. }
  11703. } else {
  11704. noConfigFile();
  11705. }
  11706. }, false);
  11707. xhr.addEventListener("error", function (event) {
  11708. noConfigFile();
  11709. }, false);
  11710. try {
  11711. xhr.send();
  11712. } catch (ex) {
  11713. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11714. }
  11715. };
  11716. CustomProceduralTexture.prototype.isReady = function () {
  11717. if (!_super.prototype.isReady.call(this)) {
  11718. return false;
  11719. }
  11720. for (var name in this._textures) {
  11721. var texture = this._textures[name];
  11722. if (!texture.isReady()) {
  11723. return false;
  11724. }
  11725. }
  11726. return true;
  11727. };
  11728. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11729. if (this._animate) {
  11730. this._time += this.getScene().getAnimationRatio() * 0.03;
  11731. this.updateShaderUniforms();
  11732. }
  11733. _super.prototype.render.call(this, useCameraPostProcess);
  11734. };
  11735. CustomProceduralTexture.prototype.updateTextures = function () {
  11736. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11737. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11738. }
  11739. };
  11740. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11741. if (this._config) {
  11742. for (var j = 0; j < this._config.uniforms.length; j++) {
  11743. var uniform = this._config.uniforms[j];
  11744. switch (uniform.type) {
  11745. case "float":
  11746. this.setFloat(uniform.name, uniform.value);
  11747. break;
  11748. case "color3":
  11749. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11750. break;
  11751. case "color4":
  11752. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11753. break;
  11754. case "vector2":
  11755. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11756. break;
  11757. case "vector3":
  11758. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11759. break;
  11760. }
  11761. }
  11762. }
  11763. this.setFloat("time", this._time);
  11764. };
  11765. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11766. get: function () {
  11767. return this._animate;
  11768. },
  11769. set: function (value) {
  11770. this._animate = value;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. return CustomProceduralTexture;
  11776. })(BABYLON.ProceduralTexture);
  11777. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11778. })(BABYLON || (BABYLON = {}));
  11779. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11780. var BABYLON;
  11781. (function (BABYLON) {
  11782. var MirrorTexture = (function (_super) {
  11783. __extends(MirrorTexture, _super);
  11784. function MirrorTexture(name, size, scene, generateMipMaps) {
  11785. var _this = this;
  11786. _super.call(this, name, size, scene, generateMipMaps, true);
  11787. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11788. this._transformMatrix = BABYLON.Matrix.Zero();
  11789. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11790. this.onBeforeRender = function () {
  11791. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11792. _this._savedViewMatrix = scene.getViewMatrix();
  11793. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11794. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11795. scene.clipPlane = _this.mirrorPlane;
  11796. scene.getEngine().cullBackFaces = false;
  11797. };
  11798. this.onAfterRender = function () {
  11799. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11800. scene.getEngine().cullBackFaces = true;
  11801. delete scene.clipPlane;
  11802. };
  11803. }
  11804. MirrorTexture.prototype.clone = function () {
  11805. var textureSize = this.getSize();
  11806. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11807. // Base texture
  11808. newTexture.hasAlpha = this.hasAlpha;
  11809. newTexture.level = this.level;
  11810. // Mirror Texture
  11811. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11812. newTexture.renderList = this.renderList.slice(0);
  11813. return newTexture;
  11814. };
  11815. return MirrorTexture;
  11816. })(BABYLON.RenderTargetTexture);
  11817. BABYLON.MirrorTexture = MirrorTexture;
  11818. })(BABYLON || (BABYLON = {}));
  11819. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11820. var BABYLON;
  11821. (function (BABYLON) {
  11822. var DynamicTexture = (function (_super) {
  11823. __extends(DynamicTexture, _super);
  11824. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11825. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11826. _super.call(this, null, scene, !generateMipMaps);
  11827. this.name = name;
  11828. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11829. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11830. this._generateMipMaps = generateMipMaps;
  11831. if (options.getContext) {
  11832. this._canvas = options;
  11833. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11834. } else {
  11835. this._canvas = document.createElement("canvas");
  11836. if (options.width) {
  11837. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11838. } else {
  11839. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11840. }
  11841. }
  11842. var textureSize = this.getSize();
  11843. this._canvas.width = textureSize.width;
  11844. this._canvas.height = textureSize.height;
  11845. this._context = this._canvas.getContext("2d");
  11846. }
  11847. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11848. get: function () {
  11849. return true;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. DynamicTexture.prototype.scale = function (ratio) {
  11855. var textureSize = this.getSize();
  11856. textureSize.width *= ratio;
  11857. textureSize.height *= ratio;
  11858. this._canvas.width = textureSize.width;
  11859. this._canvas.height = textureSize.height;
  11860. this.releaseInternalTexture();
  11861. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11862. };
  11863. DynamicTexture.prototype.getContext = function () {
  11864. return this._context;
  11865. };
  11866. DynamicTexture.prototype.update = function (invertY) {
  11867. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11868. };
  11869. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11870. var size = this.getSize();
  11871. if (clearColor) {
  11872. this._context.fillStyle = clearColor;
  11873. this._context.fillRect(0, 0, size.width, size.height);
  11874. }
  11875. this._context.font = font;
  11876. if (x === null) {
  11877. var textSize = this._context.measureText(text);
  11878. x = (size.width - textSize.width) / 2;
  11879. }
  11880. this._context.fillStyle = color;
  11881. this._context.fillText(text, x, y);
  11882. this.update(invertY);
  11883. };
  11884. DynamicTexture.prototype.clone = function () {
  11885. var textureSize = this.getSize();
  11886. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11887. // Base texture
  11888. newTexture.hasAlpha = this.hasAlpha;
  11889. newTexture.level = this.level;
  11890. // Dynamic Texture
  11891. newTexture.wrapU = this.wrapU;
  11892. newTexture.wrapV = this.wrapV;
  11893. return newTexture;
  11894. };
  11895. return DynamicTexture;
  11896. })(BABYLON.Texture);
  11897. BABYLON.DynamicTexture = DynamicTexture;
  11898. })(BABYLON || (BABYLON = {}));
  11899. //# sourceMappingURL=babylon.dynamicTexture.js.map
  11900. var BABYLON;
  11901. (function (BABYLON) {
  11902. var VideoTexture = (function (_super) {
  11903. __extends(VideoTexture, _super);
  11904. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  11905. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11906. var _this = this;
  11907. _super.call(this, null, scene, !generateMipMaps, invertY);
  11908. this._autoLaunch = true;
  11909. this.name = name;
  11910. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11911. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11912. var requiredWidth = size.width || size;
  11913. var requiredHeight = size.height || size;
  11914. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  11915. var textureSize = this.getSize();
  11916. this.video = document.createElement("video");
  11917. this.video.width = textureSize.width;
  11918. this.video.height = textureSize.height;
  11919. this.video.autoplay = false;
  11920. this.video.loop = true;
  11921. this.video.addEventListener("canplaythrough", function () {
  11922. if (_this._texture) {
  11923. _this._texture.isReady = true;
  11924. }
  11925. });
  11926. urls.forEach(function (url) {
  11927. var source = document.createElement("source");
  11928. source.src = url;
  11929. _this.video.appendChild(source);
  11930. });
  11931. this._lastUpdate = BABYLON.Tools.Now;
  11932. }
  11933. VideoTexture.prototype.update = function () {
  11934. if (this._autoLaunch) {
  11935. this._autoLaunch = false;
  11936. this.video.play();
  11937. }
  11938. var now = BABYLON.Tools.Now;
  11939. if (now - this._lastUpdate < 15) {
  11940. return false;
  11941. }
  11942. this._lastUpdate = now;
  11943. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11944. return true;
  11945. };
  11946. return VideoTexture;
  11947. })(BABYLON.Texture);
  11948. BABYLON.VideoTexture = VideoTexture;
  11949. })(BABYLON || (BABYLON = {}));
  11950. //# sourceMappingURL=babylon.videoTexture.js.map
  11951. var BABYLON;
  11952. (function (BABYLON) {
  11953. var EffectFallbacks = (function () {
  11954. function EffectFallbacks() {
  11955. this._defines = {};
  11956. this._currentRank = 32;
  11957. this._maxRank = -1;
  11958. }
  11959. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11960. if (!this._defines[rank]) {
  11961. if (rank < this._currentRank) {
  11962. this._currentRank = rank;
  11963. }
  11964. if (rank > this._maxRank) {
  11965. this._maxRank = rank;
  11966. }
  11967. this._defines[rank] = new Array();
  11968. }
  11969. this._defines[rank].push(define);
  11970. };
  11971. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11972. get: function () {
  11973. return this._currentRank <= this._maxRank;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11979. var currentFallbacks = this._defines[this._currentRank];
  11980. for (var index = 0; index < currentFallbacks.length; index++) {
  11981. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11982. }
  11983. this._currentRank++;
  11984. return currentDefines;
  11985. };
  11986. return EffectFallbacks;
  11987. })();
  11988. BABYLON.EffectFallbacks = EffectFallbacks;
  11989. var Effect = (function () {
  11990. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11991. var _this = this;
  11992. this._isReady = false;
  11993. this._compilationError = "";
  11994. this._valueCache = [];
  11995. this._engine = engine;
  11996. this.name = baseName;
  11997. this.defines = defines;
  11998. this._uniformsNames = uniformsNames.concat(samplers);
  11999. this._samplers = samplers;
  12000. this._attributesNames = attributesNames;
  12001. this.onError = onError;
  12002. this.onCompiled = onCompiled;
  12003. var vertexSource;
  12004. var fragmentSource;
  12005. if (baseName.vertexElement) {
  12006. vertexSource = document.getElementById(baseName.vertexElement);
  12007. if (!vertexSource) {
  12008. vertexSource = baseName.vertexElement;
  12009. }
  12010. } else {
  12011. vertexSource = baseName.vertex || baseName;
  12012. }
  12013. if (baseName.fragmentElement) {
  12014. fragmentSource = document.getElementById(baseName.fragmentElement);
  12015. if (!fragmentSource) {
  12016. fragmentSource = baseName.fragmentElement;
  12017. }
  12018. } else {
  12019. fragmentSource = baseName.fragment || baseName;
  12020. }
  12021. this._loadVertexShader(vertexSource, function (vertexCode) {
  12022. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12023. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12024. });
  12025. });
  12026. }
  12027. // Properties
  12028. Effect.prototype.isReady = function () {
  12029. return this._isReady;
  12030. };
  12031. Effect.prototype.getProgram = function () {
  12032. return this._program;
  12033. };
  12034. Effect.prototype.getAttributesNames = function () {
  12035. return this._attributesNames;
  12036. };
  12037. Effect.prototype.getAttributeLocation = function (index) {
  12038. return this._attributes[index];
  12039. };
  12040. Effect.prototype.getAttributeLocationByName = function (name) {
  12041. var index = this._attributesNames.indexOf(name);
  12042. return this._attributes[index];
  12043. };
  12044. Effect.prototype.getAttributesCount = function () {
  12045. return this._attributes.length;
  12046. };
  12047. Effect.prototype.getUniformIndex = function (uniformName) {
  12048. return this._uniformsNames.indexOf(uniformName);
  12049. };
  12050. Effect.prototype.getUniform = function (uniformName) {
  12051. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12052. };
  12053. Effect.prototype.getSamplers = function () {
  12054. return this._samplers;
  12055. };
  12056. Effect.prototype.getCompilationError = function () {
  12057. return this._compilationError;
  12058. };
  12059. // Methods
  12060. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12061. // DOM element ?
  12062. if (vertex instanceof HTMLElement) {
  12063. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12064. callback(vertexCode);
  12065. return;
  12066. }
  12067. // Is in local store ?
  12068. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12069. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12070. return;
  12071. }
  12072. var vertexShaderUrl;
  12073. if (vertex[0] === ".") {
  12074. vertexShaderUrl = vertex;
  12075. } else {
  12076. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12077. }
  12078. // Vertex shader
  12079. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12080. };
  12081. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12082. // DOM element ?
  12083. if (fragment instanceof HTMLElement) {
  12084. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12085. callback(fragmentCode);
  12086. return;
  12087. }
  12088. // Is in local store ?
  12089. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12090. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12091. return;
  12092. }
  12093. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12094. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12095. return;
  12096. }
  12097. var fragmentShaderUrl;
  12098. if (fragment[0] === ".") {
  12099. fragmentShaderUrl = fragment;
  12100. } else {
  12101. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12102. }
  12103. // Fragment shader
  12104. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12105. };
  12106. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12107. try {
  12108. var engine = this._engine;
  12109. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12110. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12111. this._attributes = engine.getAttributes(this._program, attributesNames);
  12112. for (var index = 0; index < this._samplers.length; index++) {
  12113. var sampler = this.getUniform(this._samplers[index]);
  12114. if (sampler == null) {
  12115. this._samplers.splice(index, 1);
  12116. index--;
  12117. }
  12118. }
  12119. engine.bindSamplers(this);
  12120. this._isReady = true;
  12121. if (this.onCompiled) {
  12122. this.onCompiled(this);
  12123. }
  12124. } catch (e) {
  12125. // Is it a problem with precision?
  12126. if (e.message.indexOf("highp") !== -1) {
  12127. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12128. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12129. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12130. return;
  12131. }
  12132. // Let's go through fallbacks then
  12133. if (fallbacks && fallbacks.isMoreFallbacks) {
  12134. defines = fallbacks.reduce(defines);
  12135. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12136. } else {
  12137. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12138. BABYLON.Tools.Error("Defines: " + defines);
  12139. BABYLON.Tools.Error("Error: " + e.message);
  12140. this._compilationError = e.message;
  12141. if (this.onError) {
  12142. this.onError(this, this._compilationError);
  12143. }
  12144. }
  12145. }
  12146. };
  12147. Effect.prototype._bindTexture = function (channel, texture) {
  12148. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12149. };
  12150. Effect.prototype.setTexture = function (channel, texture) {
  12151. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12152. };
  12153. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12154. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12155. };
  12156. //public _cacheMatrix(uniformName, matrix) {
  12157. // if (!this._valueCache[uniformName]) {
  12158. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12159. // }
  12160. // for (var index = 0; index < 16; index++) {
  12161. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12162. // }
  12163. //};
  12164. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12165. if (!this._valueCache[uniformName]) {
  12166. this._valueCache[uniformName] = [x, y];
  12167. return;
  12168. }
  12169. this._valueCache[uniformName][0] = x;
  12170. this._valueCache[uniformName][1] = y;
  12171. };
  12172. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12173. if (!this._valueCache[uniformName]) {
  12174. this._valueCache[uniformName] = [x, y, z];
  12175. return;
  12176. }
  12177. this._valueCache[uniformName][0] = x;
  12178. this._valueCache[uniformName][1] = y;
  12179. this._valueCache[uniformName][2] = z;
  12180. };
  12181. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12182. if (!this._valueCache[uniformName]) {
  12183. this._valueCache[uniformName] = [x, y, z, w];
  12184. return;
  12185. }
  12186. this._valueCache[uniformName][0] = x;
  12187. this._valueCache[uniformName][1] = y;
  12188. this._valueCache[uniformName][2] = z;
  12189. this._valueCache[uniformName][3] = w;
  12190. };
  12191. Effect.prototype.setArray = function (uniformName, array) {
  12192. this._engine.setArray(this.getUniform(uniformName), array);
  12193. return this;
  12194. };
  12195. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12196. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12197. return this;
  12198. };
  12199. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12200. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12201. // return;
  12202. //this._cacheMatrix(uniformName, matrix);
  12203. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12204. return this;
  12205. };
  12206. Effect.prototype.setFloat = function (uniformName, value) {
  12207. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12208. return this;
  12209. this._valueCache[uniformName] = value;
  12210. this._engine.setFloat(this.getUniform(uniformName), value);
  12211. return this;
  12212. };
  12213. Effect.prototype.setBool = function (uniformName, bool) {
  12214. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12215. return this;
  12216. this._valueCache[uniformName] = bool;
  12217. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12218. return this;
  12219. };
  12220. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12221. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12222. return this;
  12223. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12224. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12225. return this;
  12226. };
  12227. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12228. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12229. return this;
  12230. this._cacheFloat2(uniformName, x, y);
  12231. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12232. return this;
  12233. };
  12234. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12235. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12236. return this;
  12237. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12238. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12239. return this;
  12240. };
  12241. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12242. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12243. return this;
  12244. this._cacheFloat3(uniformName, x, y, z);
  12245. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12246. return this;
  12247. };
  12248. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12249. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12250. return this;
  12251. this._cacheFloat4(uniformName, x, y, z, w);
  12252. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12253. return this;
  12254. };
  12255. Effect.prototype.setColor3 = function (uniformName, color3) {
  12256. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12257. return this;
  12258. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12259. this._engine.setColor3(this.getUniform(uniformName), color3);
  12260. return this;
  12261. };
  12262. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12263. 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)
  12264. return this;
  12265. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12266. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12267. return this;
  12268. };
  12269. 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}",
  12270. 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}",
  12271. 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}",
  12272. 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}",
  12273. 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}",
  12274. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12275. 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}",
  12276. 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}",
  12277. 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}",
  12278. 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}",
  12279. 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}",
  12280. 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}",
  12281. 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}",
  12282. 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}",
  12283. 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}",
  12284. 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}",
  12285. 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}",
  12286. 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}",
  12287. 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}",
  12288. 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}",
  12289. 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}",
  12290. 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}",
  12291. 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}",
  12292. 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}",
  12293. 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}",
  12294. 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}",
  12295. 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}",
  12296. 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}",
  12297. 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}",
  12298. 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}",
  12299. 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}",
  12300. 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}",
  12301. 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}",
  12302. 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}",
  12303. 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}",
  12304. 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}",
  12305. 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}",
  12306. };
  12307. return Effect;
  12308. })();
  12309. BABYLON.Effect = Effect;
  12310. })(BABYLON || (BABYLON = {}));
  12311. //# sourceMappingURL=babylon.effect.js.map
  12312. var BABYLON;
  12313. (function (BABYLON) {
  12314. var Material = (function () {
  12315. function Material(name, scene, doNotAdd) {
  12316. this.name = name;
  12317. this.checkReadyOnEveryCall = true;
  12318. this.checkReadyOnlyOnce = false;
  12319. this.state = "";
  12320. this.alpha = 1.0;
  12321. this.backFaceCulling = true;
  12322. this._wasPreviouslyReady = false;
  12323. this._fillMode = Material.TriangleFillMode;
  12324. this.pointSize = 1.0;
  12325. this.id = name;
  12326. this._scene = scene;
  12327. if (!doNotAdd) {
  12328. scene.materials.push(this);
  12329. }
  12330. }
  12331. Object.defineProperty(Material, "TriangleFillMode", {
  12332. get: function () {
  12333. return Material._TriangleFillMode;
  12334. },
  12335. enumerable: true,
  12336. configurable: true
  12337. });
  12338. Object.defineProperty(Material, "WireFrameFillMode", {
  12339. get: function () {
  12340. return Material._WireFrameFillMode;
  12341. },
  12342. enumerable: true,
  12343. configurable: true
  12344. });
  12345. Object.defineProperty(Material, "PointFillMode", {
  12346. get: function () {
  12347. return Material._PointFillMode;
  12348. },
  12349. enumerable: true,
  12350. configurable: true
  12351. });
  12352. Object.defineProperty(Material.prototype, "wireframe", {
  12353. get: function () {
  12354. return this._fillMode === Material.WireFrameFillMode;
  12355. },
  12356. set: function (value) {
  12357. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12358. },
  12359. enumerable: true,
  12360. configurable: true
  12361. });
  12362. Object.defineProperty(Material.prototype, "pointsCloud", {
  12363. get: function () {
  12364. return this._fillMode === Material.PointFillMode;
  12365. },
  12366. set: function (value) {
  12367. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12368. },
  12369. enumerable: true,
  12370. configurable: true
  12371. });
  12372. Object.defineProperty(Material.prototype, "fillMode", {
  12373. get: function () {
  12374. return this._fillMode;
  12375. },
  12376. set: function (value) {
  12377. this._fillMode = value;
  12378. },
  12379. enumerable: true,
  12380. configurable: true
  12381. });
  12382. Material.prototype.isReady = function (mesh, useInstances) {
  12383. return true;
  12384. };
  12385. Material.prototype.getEffect = function () {
  12386. return this._effect;
  12387. };
  12388. Material.prototype.getScene = function () {
  12389. return this._scene;
  12390. };
  12391. Material.prototype.needAlphaBlending = function () {
  12392. return (this.alpha < 1.0);
  12393. };
  12394. Material.prototype.needAlphaTesting = function () {
  12395. return false;
  12396. };
  12397. Material.prototype.getAlphaTestTexture = function () {
  12398. return null;
  12399. };
  12400. Material.prototype.trackCreation = function (onCompiled, onError) {
  12401. };
  12402. Material.prototype._preBind = function () {
  12403. var engine = this._scene.getEngine();
  12404. engine.enableEffect(this._effect);
  12405. engine.setState(this.backFaceCulling);
  12406. };
  12407. Material.prototype.bind = function (world, mesh) {
  12408. this._scene._cachedMaterial = this;
  12409. if (this.onBind) {
  12410. this.onBind(this);
  12411. }
  12412. };
  12413. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12414. };
  12415. Material.prototype.unbind = function () {
  12416. };
  12417. Material.prototype.dispose = function (forceDisposeEffect) {
  12418. // Remove from scene
  12419. var index = this._scene.materials.indexOf(this);
  12420. this._scene.materials.splice(index, 1);
  12421. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12422. if (forceDisposeEffect && this._effect) {
  12423. this._scene.getEngine()._releaseEffect(this._effect);
  12424. this._effect = null;
  12425. }
  12426. // Callback
  12427. if (this.onDispose) {
  12428. this.onDispose();
  12429. }
  12430. };
  12431. Material._TriangleFillMode = 0;
  12432. Material._WireFrameFillMode = 1;
  12433. Material._PointFillMode = 2;
  12434. return Material;
  12435. })();
  12436. BABYLON.Material = Material;
  12437. })(BABYLON || (BABYLON = {}));
  12438. //# sourceMappingURL=babylon.material.js.map
  12439. var BABYLON;
  12440. (function (BABYLON) {
  12441. var maxSimultaneousLights = 4;
  12442. var FresnelParameters = (function () {
  12443. function FresnelParameters() {
  12444. this.isEnabled = true;
  12445. this.leftColor = BABYLON.Color3.White();
  12446. this.rightColor = BABYLON.Color3.Black();
  12447. this.bias = 0;
  12448. this.power = 1;
  12449. }
  12450. return FresnelParameters;
  12451. })();
  12452. BABYLON.FresnelParameters = FresnelParameters;
  12453. var StandardMaterial = (function (_super) {
  12454. __extends(StandardMaterial, _super);
  12455. function StandardMaterial(name, scene) {
  12456. var _this = this;
  12457. _super.call(this, name, scene);
  12458. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12459. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12460. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12461. this.specularPower = 64;
  12462. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12463. this.useAlphaFromDiffuseTexture = false;
  12464. this.useSpecularOverAlpha = true;
  12465. this.fogEnabled = true;
  12466. this._cachedDefines = null;
  12467. this._renderTargets = new BABYLON.SmartArray(16);
  12468. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12469. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12470. this._scaledDiffuse = new BABYLON.Color3();
  12471. this._scaledSpecular = new BABYLON.Color3();
  12472. this.getRenderTargetTextures = function () {
  12473. _this._renderTargets.reset();
  12474. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12475. _this._renderTargets.push(_this.reflectionTexture);
  12476. }
  12477. return _this._renderTargets;
  12478. };
  12479. }
  12480. StandardMaterial.prototype.needAlphaBlending = function () {
  12481. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12482. };
  12483. StandardMaterial.prototype.needAlphaTesting = function () {
  12484. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12485. };
  12486. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12487. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12488. };
  12489. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12490. return this.diffuseTexture;
  12491. };
  12492. // Methods
  12493. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12494. if (this.checkReadyOnlyOnce) {
  12495. if (this._wasPreviouslyReady) {
  12496. return true;
  12497. }
  12498. }
  12499. var scene = this.getScene();
  12500. if (!this.checkReadyOnEveryCall) {
  12501. if (this._renderId === scene.getRenderId()) {
  12502. return true;
  12503. }
  12504. }
  12505. var engine = scene.getEngine();
  12506. var defines = [];
  12507. var fallbacks = new BABYLON.EffectFallbacks();
  12508. // Textures
  12509. if (scene.texturesEnabled) {
  12510. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12511. if (!this.diffuseTexture.isReady()) {
  12512. return false;
  12513. } else {
  12514. defines.push("#define DIFFUSE");
  12515. }
  12516. }
  12517. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12518. if (!this.ambientTexture.isReady()) {
  12519. return false;
  12520. } else {
  12521. defines.push("#define AMBIENT");
  12522. }
  12523. }
  12524. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12525. if (!this.opacityTexture.isReady()) {
  12526. return false;
  12527. } else {
  12528. defines.push("#define OPACITY");
  12529. if (this.opacityTexture.getAlphaFromRGB) {
  12530. defines.push("#define OPACITYRGB");
  12531. }
  12532. }
  12533. }
  12534. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12535. if (!this.reflectionTexture.isReady()) {
  12536. return false;
  12537. } else {
  12538. defines.push("#define REFLECTION");
  12539. fallbacks.addFallback(0, "REFLECTION");
  12540. }
  12541. }
  12542. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12543. if (!this.emissiveTexture.isReady()) {
  12544. return false;
  12545. } else {
  12546. defines.push("#define EMISSIVE");
  12547. }
  12548. }
  12549. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12550. if (!this.specularTexture.isReady()) {
  12551. return false;
  12552. } else {
  12553. defines.push("#define SPECULAR");
  12554. fallbacks.addFallback(0, "SPECULAR");
  12555. }
  12556. }
  12557. }
  12558. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12559. if (!this.bumpTexture.isReady()) {
  12560. return false;
  12561. } else {
  12562. defines.push("#define BUMP");
  12563. fallbacks.addFallback(0, "BUMP");
  12564. }
  12565. }
  12566. // Effect
  12567. if (this.useSpecularOverAlpha) {
  12568. defines.push("#define SPECULAROVERALPHA");
  12569. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12570. }
  12571. if (scene.clipPlane) {
  12572. defines.push("#define CLIPPLANE");
  12573. }
  12574. if (engine.getAlphaTesting()) {
  12575. defines.push("#define ALPHATEST");
  12576. }
  12577. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12578. defines.push("#define ALPHAFROMDIFFUSE");
  12579. }
  12580. // Point size
  12581. if (this.pointsCloud || scene.forcePointsCloud) {
  12582. defines.push("#define POINTSIZE");
  12583. }
  12584. // Fog
  12585. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12586. defines.push("#define FOG");
  12587. fallbacks.addFallback(1, "FOG");
  12588. }
  12589. var shadowsActivated = false;
  12590. var lightIndex = 0;
  12591. if (scene.lightsEnabled) {
  12592. for (var index = 0; index < scene.lights.length; index++) {
  12593. var light = scene.lights[index];
  12594. if (!light.isEnabled()) {
  12595. continue;
  12596. }
  12597. // Excluded check
  12598. if (light._excludedMeshesIds.length > 0) {
  12599. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12600. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12601. if (excludedMesh) {
  12602. light.excludedMeshes.push(excludedMesh);
  12603. }
  12604. }
  12605. light._excludedMeshesIds = [];
  12606. }
  12607. // Included check
  12608. if (light._includedOnlyMeshesIds.length > 0) {
  12609. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12610. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12611. if (includedOnlyMesh) {
  12612. light.includedOnlyMeshes.push(includedOnlyMesh);
  12613. }
  12614. }
  12615. light._includedOnlyMeshesIds = [];
  12616. }
  12617. if (!light.canAffectMesh(mesh)) {
  12618. continue;
  12619. }
  12620. defines.push("#define LIGHT" + lightIndex);
  12621. if (lightIndex > 0) {
  12622. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12623. }
  12624. var type;
  12625. if (light instanceof BABYLON.SpotLight) {
  12626. type = "#define SPOTLIGHT" + lightIndex;
  12627. } else if (light instanceof BABYLON.HemisphericLight) {
  12628. type = "#define HEMILIGHT" + lightIndex;
  12629. } else {
  12630. type = "#define POINTDIRLIGHT" + lightIndex;
  12631. }
  12632. defines.push(type);
  12633. if (lightIndex > 0) {
  12634. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12635. }
  12636. // Shadows
  12637. if (scene.shadowsEnabled) {
  12638. var shadowGenerator = light.getShadowGenerator();
  12639. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12640. defines.push("#define SHADOW" + lightIndex);
  12641. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12642. if (!shadowsActivated) {
  12643. defines.push("#define SHADOWS");
  12644. shadowsActivated = true;
  12645. }
  12646. if (shadowGenerator.useVarianceShadowMap) {
  12647. defines.push("#define SHADOWVSM" + lightIndex);
  12648. if (lightIndex > 0) {
  12649. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12650. }
  12651. }
  12652. if (shadowGenerator.usePoissonSampling) {
  12653. defines.push("#define SHADOWPCF" + lightIndex);
  12654. if (lightIndex > 0) {
  12655. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12656. }
  12657. }
  12658. }
  12659. }
  12660. lightIndex++;
  12661. if (lightIndex === maxSimultaneousLights)
  12662. break;
  12663. }
  12664. }
  12665. if (StandardMaterial.FresnelEnabled) {
  12666. // Fresnel
  12667. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12668. var fresnelRank = 1;
  12669. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12670. defines.push("#define DIFFUSEFRESNEL");
  12671. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12672. fresnelRank++;
  12673. }
  12674. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12675. defines.push("#define OPACITYFRESNEL");
  12676. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12677. fresnelRank++;
  12678. }
  12679. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12680. defines.push("#define REFLECTIONFRESNEL");
  12681. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12682. fresnelRank++;
  12683. }
  12684. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12685. defines.push("#define EMISSIVEFRESNEL");
  12686. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12687. fresnelRank++;
  12688. }
  12689. defines.push("#define FRESNEL");
  12690. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12691. }
  12692. }
  12693. // Attribs
  12694. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12695. if (mesh) {
  12696. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12697. attribs.push(BABYLON.VertexBuffer.UVKind);
  12698. defines.push("#define UV1");
  12699. }
  12700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12701. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12702. defines.push("#define UV2");
  12703. }
  12704. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12705. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12706. defines.push("#define VERTEXCOLOR");
  12707. if (mesh.hasVertexAlpha) {
  12708. defines.push("#define VERTEXALPHA");
  12709. }
  12710. }
  12711. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12714. defines.push("#define BONES");
  12715. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12716. defines.push("#define BONES4");
  12717. fallbacks.addFallback(0, "BONES4");
  12718. }
  12719. // Instances
  12720. if (useInstances) {
  12721. defines.push("#define INSTANCES");
  12722. attribs.push("world0");
  12723. attribs.push("world1");
  12724. attribs.push("world2");
  12725. attribs.push("world3");
  12726. }
  12727. }
  12728. // Get correct effect
  12729. var join = defines.join("\n");
  12730. if (this._cachedDefines !== join) {
  12731. this._cachedDefines = join;
  12732. scene.resetCachedMaterial();
  12733. // Legacy browser patch
  12734. var shaderName = "default";
  12735. if (!scene.getEngine().getCaps().standardDerivatives) {
  12736. shaderName = "legacydefault";
  12737. }
  12738. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12739. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12740. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12741. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12742. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12743. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12744. "vFogInfos", "vFogColor", "pointSize",
  12745. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12746. "mBones",
  12747. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12748. "darkness0", "darkness1", "darkness2", "darkness3",
  12749. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12750. ], [
  12751. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12752. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12753. ], join, fallbacks, this.onCompiled, this.onError);
  12754. }
  12755. if (!this._effect.isReady()) {
  12756. return false;
  12757. }
  12758. this._renderId = scene.getRenderId();
  12759. this._wasPreviouslyReady = true;
  12760. return true;
  12761. };
  12762. StandardMaterial.prototype.unbind = function () {
  12763. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12764. this._effect.setTexture("reflection2DSampler", null);
  12765. }
  12766. };
  12767. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12768. this._effect.setMatrix("world", world);
  12769. };
  12770. StandardMaterial.prototype.bind = function (world, mesh) {
  12771. var scene = this.getScene();
  12772. // Matrices
  12773. this.bindOnlyWorldMatrix(world);
  12774. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12775. // Bones
  12776. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12777. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12778. }
  12779. if (scene.getCachedMaterial() !== this) {
  12780. if (StandardMaterial.FresnelEnabled) {
  12781. // Fresnel
  12782. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12783. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12784. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12785. }
  12786. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12787. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12788. }
  12789. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12790. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12791. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12792. }
  12793. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12794. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12795. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12796. }
  12797. }
  12798. // Textures
  12799. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12800. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12801. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12802. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12803. }
  12804. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12805. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12806. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12807. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12808. }
  12809. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12810. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12811. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12812. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12813. }
  12814. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12815. if (this.reflectionTexture.isCube) {
  12816. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12817. } else {
  12818. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12819. }
  12820. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12821. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12822. }
  12823. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12824. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12825. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12826. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12827. }
  12828. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12829. this._effect.setTexture("specularSampler", this.specularTexture);
  12830. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12831. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12832. }
  12833. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12834. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12835. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12836. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12837. }
  12838. // Clip plane
  12839. if (scene.clipPlane) {
  12840. var clipPlane = scene.clipPlane;
  12841. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12842. }
  12843. // Point size
  12844. if (this.pointsCloud) {
  12845. this._effect.setFloat("pointSize", this.pointSize);
  12846. }
  12847. // Colors
  12848. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12849. // Scaling down color according to emissive
  12850. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12851. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12852. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12853. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12854. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12855. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12856. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12857. }
  12858. // Scaling down color according to emissive
  12859. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12860. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12861. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12862. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12863. if (scene.lightsEnabled) {
  12864. var lightIndex = 0;
  12865. for (var index = 0; index < scene.lights.length; index++) {
  12866. var light = scene.lights[index];
  12867. if (!light.isEnabled()) {
  12868. continue;
  12869. }
  12870. if (!light.canAffectMesh(mesh)) {
  12871. continue;
  12872. }
  12873. if (light instanceof BABYLON.PointLight) {
  12874. // Point Light
  12875. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12876. } else if (light instanceof BABYLON.DirectionalLight) {
  12877. // Directional Light
  12878. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12879. } else if (light instanceof BABYLON.SpotLight) {
  12880. // Spot Light
  12881. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12882. } else if (light instanceof BABYLON.HemisphericLight) {
  12883. // Hemispheric Light
  12884. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12885. }
  12886. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12887. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12888. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12889. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12890. // Shadows
  12891. if (scene.shadowsEnabled) {
  12892. var shadowGenerator = light.getShadowGenerator();
  12893. if (mesh.receiveShadows && shadowGenerator) {
  12894. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  12895. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  12896. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  12897. }
  12898. }
  12899. lightIndex++;
  12900. if (lightIndex === maxSimultaneousLights)
  12901. break;
  12902. }
  12903. }
  12904. // View
  12905. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  12906. this._effect.setMatrix("view", scene.getViewMatrix());
  12907. }
  12908. // Fog
  12909. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  12910. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  12911. this._effect.setColor3("vFogColor", scene.fogColor);
  12912. }
  12913. _super.prototype.bind.call(this, world, mesh);
  12914. };
  12915. StandardMaterial.prototype.getAnimatables = function () {
  12916. var results = [];
  12917. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  12918. results.push(this.diffuseTexture);
  12919. }
  12920. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  12921. results.push(this.ambientTexture);
  12922. }
  12923. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  12924. results.push(this.opacityTexture);
  12925. }
  12926. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  12927. results.push(this.reflectionTexture);
  12928. }
  12929. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  12930. results.push(this.emissiveTexture);
  12931. }
  12932. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  12933. results.push(this.specularTexture);
  12934. }
  12935. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  12936. results.push(this.bumpTexture);
  12937. }
  12938. return results;
  12939. };
  12940. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  12941. if (this.diffuseTexture) {
  12942. this.diffuseTexture.dispose();
  12943. }
  12944. if (this.ambientTexture) {
  12945. this.ambientTexture.dispose();
  12946. }
  12947. if (this.opacityTexture) {
  12948. this.opacityTexture.dispose();
  12949. }
  12950. if (this.reflectionTexture) {
  12951. this.reflectionTexture.dispose();
  12952. }
  12953. if (this.emissiveTexture) {
  12954. this.emissiveTexture.dispose();
  12955. }
  12956. if (this.specularTexture) {
  12957. this.specularTexture.dispose();
  12958. }
  12959. if (this.bumpTexture) {
  12960. this.bumpTexture.dispose();
  12961. }
  12962. _super.prototype.dispose.call(this, forceDisposeEffect);
  12963. };
  12964. StandardMaterial.prototype.clone = function (name) {
  12965. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  12966. // Base material
  12967. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  12968. newStandardMaterial.alpha = this.alpha;
  12969. newStandardMaterial.fillMode = this.fillMode;
  12970. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  12971. // Standard material
  12972. if (this.diffuseTexture && this.diffuseTexture.clone) {
  12973. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  12974. }
  12975. if (this.ambientTexture && this.ambientTexture.clone) {
  12976. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  12977. }
  12978. if (this.opacityTexture && this.opacityTexture.clone) {
  12979. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  12980. }
  12981. if (this.reflectionTexture && this.reflectionTexture.clone) {
  12982. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  12983. }
  12984. if (this.emissiveTexture && this.emissiveTexture.clone) {
  12985. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  12986. }
  12987. if (this.specularTexture && this.specularTexture.clone) {
  12988. newStandardMaterial.specularTexture = this.specularTexture.clone();
  12989. }
  12990. if (this.bumpTexture && this.bumpTexture.clone) {
  12991. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  12992. }
  12993. newStandardMaterial.ambientColor = this.ambientColor.clone();
  12994. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  12995. newStandardMaterial.specularColor = this.specularColor.clone();
  12996. newStandardMaterial.specularPower = this.specularPower;
  12997. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  12998. return newStandardMaterial;
  12999. };
  13000. StandardMaterial.DiffuseTextureEnabled = true;
  13001. StandardMaterial.AmbientTextureEnabled = true;
  13002. StandardMaterial.OpacityTextureEnabled = true;
  13003. StandardMaterial.ReflectionTextureEnabled = true;
  13004. StandardMaterial.EmissiveTextureEnabled = true;
  13005. StandardMaterial.SpecularTextureEnabled = true;
  13006. StandardMaterial.BumpTextureEnabled = true;
  13007. StandardMaterial.FresnelEnabled = true;
  13008. return StandardMaterial;
  13009. })(BABYLON.Material);
  13010. BABYLON.StandardMaterial = StandardMaterial;
  13011. })(BABYLON || (BABYLON = {}));
  13012. //# sourceMappingURL=babylon.standardMaterial.js.map
  13013. var BABYLON;
  13014. (function (BABYLON) {
  13015. var MultiMaterial = (function (_super) {
  13016. __extends(MultiMaterial, _super);
  13017. function MultiMaterial(name, scene) {
  13018. _super.call(this, name, scene, true);
  13019. this.subMaterials = new Array();
  13020. scene.multiMaterials.push(this);
  13021. }
  13022. // Properties
  13023. MultiMaterial.prototype.getSubMaterial = function (index) {
  13024. if (index < 0 || index >= this.subMaterials.length) {
  13025. return this.getScene().defaultMaterial;
  13026. }
  13027. return this.subMaterials[index];
  13028. };
  13029. // Methods
  13030. MultiMaterial.prototype.isReady = function (mesh) {
  13031. for (var index = 0; index < this.subMaterials.length; index++) {
  13032. var subMaterial = this.subMaterials[index];
  13033. if (subMaterial) {
  13034. if (!this.subMaterials[index].isReady(mesh)) {
  13035. return false;
  13036. }
  13037. }
  13038. }
  13039. return true;
  13040. };
  13041. return MultiMaterial;
  13042. })(BABYLON.Material);
  13043. BABYLON.MultiMaterial = MultiMaterial;
  13044. })(BABYLON || (BABYLON = {}));
  13045. //# sourceMappingURL=babylon.multiMaterial.js.map
  13046. var BABYLON;
  13047. (function (BABYLON) {
  13048. var Database = (function () {
  13049. function Database(urlToScene, callbackManifestChecked) {
  13050. // Handling various flavors of prefixed version of IndexedDB
  13051. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13052. this.callbackManifestChecked = callbackManifestChecked;
  13053. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13054. this.db = null;
  13055. this.enableSceneOffline = false;
  13056. this.enableTexturesOffline = false;
  13057. this.manifestVersionFound = 0;
  13058. this.mustUpdateRessources = false;
  13059. this.hasReachedQuota = false;
  13060. this.checkManifestFile();
  13061. }
  13062. Database.prototype.checkManifestFile = function () {
  13063. var _this = this;
  13064. function noManifestFile() {
  13065. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13066. that.enableSceneOffline = false;
  13067. that.enableTexturesOffline = false;
  13068. that.callbackManifestChecked(false);
  13069. }
  13070. var that = this;
  13071. var manifestURL = this.currentSceneUrl + ".manifest";
  13072. var xhr = new XMLHttpRequest();
  13073. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13074. xhr.open("GET", manifestURLTimeStamped, true);
  13075. xhr.addEventListener("load", function () {
  13076. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13077. try {
  13078. var manifestFile = JSON.parse(xhr.response);
  13079. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13080. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13081. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13082. _this.manifestVersionFound = manifestFile.version;
  13083. }
  13084. if (_this.callbackManifestChecked) {
  13085. _this.callbackManifestChecked(true);
  13086. }
  13087. } catch (ex) {
  13088. noManifestFile();
  13089. }
  13090. } else {
  13091. noManifestFile();
  13092. }
  13093. }, false);
  13094. xhr.addEventListener("error", function (event) {
  13095. noManifestFile();
  13096. }, false);
  13097. try {
  13098. xhr.send();
  13099. } catch (ex) {
  13100. BABYLON.Tools.Error("Error on XHR send request.");
  13101. that.callbackManifestChecked(false);
  13102. }
  13103. };
  13104. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13105. var _this = this;
  13106. function handleError() {
  13107. that.isSupported = false;
  13108. if (errorCallback)
  13109. errorCallback();
  13110. }
  13111. var that = this;
  13112. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13113. // Your browser doesn't support IndexedDB
  13114. this.isSupported = false;
  13115. if (errorCallback)
  13116. errorCallback();
  13117. } else {
  13118. // If the DB hasn't been opened or created yet
  13119. if (!this.db) {
  13120. this.hasReachedQuota = false;
  13121. this.isSupported = true;
  13122. var request = this.idbFactory.open("babylonjs", 1);
  13123. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13124. request.onerror = function (event) {
  13125. handleError();
  13126. };
  13127. // executes when a version change transaction cannot complete due to other active transactions
  13128. request.onblocked = function (event) {
  13129. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13130. handleError();
  13131. };
  13132. // DB has been opened successfully
  13133. request.onsuccess = function (event) {
  13134. _this.db = request.result;
  13135. successCallback();
  13136. };
  13137. // Initialization of the DB. Creating Scenes & Textures stores
  13138. request.onupgradeneeded = function (event) {
  13139. _this.db = (event.target).result;
  13140. try {
  13141. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13142. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13143. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13144. } catch (ex) {
  13145. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13146. handleError();
  13147. }
  13148. };
  13149. } else {
  13150. if (successCallback)
  13151. successCallback();
  13152. }
  13153. }
  13154. };
  13155. Database.prototype.loadImageFromDB = function (url, image) {
  13156. var _this = this;
  13157. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13158. var saveAndLoadImage = function () {
  13159. if (!_this.hasReachedQuota && _this.db !== null) {
  13160. // the texture is not yet in the DB, let's try to save it
  13161. _this._saveImageIntoDBAsync(completeURL, image);
  13162. } else {
  13163. image.src = url;
  13164. }
  13165. };
  13166. if (!this.mustUpdateRessources) {
  13167. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13168. } else {
  13169. saveAndLoadImage();
  13170. }
  13171. };
  13172. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13173. if (this.isSupported && this.db !== null) {
  13174. var texture;
  13175. var transaction = this.db.transaction(["textures"]);
  13176. transaction.onabort = function (event) {
  13177. image.src = url;
  13178. };
  13179. transaction.oncomplete = function (event) {
  13180. var blobTextureURL;
  13181. if (texture) {
  13182. var URL = window.URL || window.webkitURL;
  13183. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13184. image.onerror = function () {
  13185. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13186. image.src = url;
  13187. };
  13188. image.src = blobTextureURL;
  13189. } else {
  13190. notInDBCallback();
  13191. }
  13192. };
  13193. var getRequest = transaction.objectStore("textures").get(url);
  13194. getRequest.onsuccess = function (event) {
  13195. texture = (event.target).result;
  13196. };
  13197. getRequest.onerror = function (event) {
  13198. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13199. image.src = url;
  13200. };
  13201. } else {
  13202. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13203. image.src = url;
  13204. }
  13205. };
  13206. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13207. var _this = this;
  13208. if (this.isSupported) {
  13209. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13210. var generateBlobUrl = function () {
  13211. var blobTextureURL;
  13212. if (blob) {
  13213. var URL = window.URL || window.webkitURL;
  13214. try {
  13215. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13216. } catch (ex) {
  13217. blobTextureURL = URL.createObjectURL(blob);
  13218. }
  13219. }
  13220. image.src = blobTextureURL;
  13221. };
  13222. if (BABYLON.Database.isUASupportingBlobStorage) {
  13223. var xhr = new XMLHttpRequest(), blob;
  13224. xhr.open("GET", url, true);
  13225. xhr.responseType = "blob";
  13226. xhr.addEventListener("load", function () {
  13227. if (xhr.status === 200) {
  13228. // Blob as response (XHR2)
  13229. blob = xhr.response;
  13230. var transaction = _this.db.transaction(["textures"], "readwrite");
  13231. // the transaction could abort because of a QuotaExceededError error
  13232. transaction.onabort = function (event) {
  13233. try {
  13234. if (event.srcElement.error.name === "QuotaExceededError") {
  13235. this.hasReachedQuota = true;
  13236. }
  13237. } catch (ex) {
  13238. }
  13239. generateBlobUrl();
  13240. };
  13241. transaction.oncomplete = function (event) {
  13242. generateBlobUrl();
  13243. };
  13244. var newTexture = { textureUrl: url, data: blob };
  13245. try {
  13246. // Put the blob into the dabase
  13247. var addRequest = transaction.objectStore("textures").put(newTexture);
  13248. addRequest.onsuccess = function (event) {
  13249. };
  13250. addRequest.onerror = function (event) {
  13251. generateBlobUrl();
  13252. };
  13253. } catch (ex) {
  13254. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13255. if (ex.code === 25) {
  13256. BABYLON.Database.isUASupportingBlobStorage = false;
  13257. }
  13258. image.src = url;
  13259. }
  13260. } else {
  13261. image.src = url;
  13262. }
  13263. }, false);
  13264. xhr.addEventListener("error", function (event) {
  13265. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13266. image.src = url;
  13267. }, false);
  13268. xhr.send();
  13269. } else {
  13270. image.src = url;
  13271. }
  13272. } else {
  13273. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13274. image.src = url;
  13275. }
  13276. };
  13277. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13278. var _this = this;
  13279. var updateVersion = function (event) {
  13280. // the version is not yet in the DB or we need to update it
  13281. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13282. };
  13283. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13284. };
  13285. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13286. var _this = this;
  13287. if (this.isSupported) {
  13288. var version;
  13289. try {
  13290. var transaction = this.db.transaction(["versions"]);
  13291. transaction.oncomplete = function (event) {
  13292. if (version) {
  13293. // If the version in the JSON file is > than the version in DB
  13294. if (_this.manifestVersionFound > version.data) {
  13295. _this.mustUpdateRessources = true;
  13296. updateInDBCallback();
  13297. } else {
  13298. callback(version.data);
  13299. }
  13300. } else {
  13301. _this.mustUpdateRessources = true;
  13302. updateInDBCallback();
  13303. }
  13304. };
  13305. transaction.onabort = function (event) {
  13306. callback(-1);
  13307. };
  13308. var getRequest = transaction.objectStore("versions").get(url);
  13309. getRequest.onsuccess = function (event) {
  13310. version = (event.target).result;
  13311. };
  13312. getRequest.onerror = function (event) {
  13313. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13314. callback(-1);
  13315. };
  13316. } catch (ex) {
  13317. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13318. callback(-1);
  13319. }
  13320. } else {
  13321. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13322. callback(-1);
  13323. }
  13324. };
  13325. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13326. var _this = this;
  13327. if (this.isSupported && !this.hasReachedQuota) {
  13328. try {
  13329. // Open a transaction to the database
  13330. var transaction = this.db.transaction(["versions"], "readwrite");
  13331. // the transaction could abort because of a QuotaExceededError error
  13332. transaction.onabort = function (event) {
  13333. try {
  13334. if (event.srcElement.error.name === "QuotaExceededError") {
  13335. _this.hasReachedQuota = true;
  13336. }
  13337. } catch (ex) {
  13338. }
  13339. callback(-1);
  13340. };
  13341. transaction.oncomplete = function (event) {
  13342. callback(_this.manifestVersionFound);
  13343. };
  13344. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13345. // Put the scene into the database
  13346. var addRequest = transaction.objectStore("versions").put(newVersion);
  13347. addRequest.onsuccess = function (event) {
  13348. };
  13349. addRequest.onerror = function (event) {
  13350. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13351. };
  13352. } catch (ex) {
  13353. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13354. callback(-1);
  13355. }
  13356. } else {
  13357. callback(-1);
  13358. }
  13359. };
  13360. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13361. var _this = this;
  13362. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13363. var saveAndLoadFile = function (event) {
  13364. // the scene is not yet in the DB, let's try to save it
  13365. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13366. };
  13367. this._checkVersionFromDB(completeUrl, function (version) {
  13368. if (version !== -1) {
  13369. if (!_this.mustUpdateRessources) {
  13370. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13371. } else {
  13372. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13373. }
  13374. } else {
  13375. errorCallback();
  13376. }
  13377. });
  13378. };
  13379. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13380. if (this.isSupported) {
  13381. var targetStore;
  13382. if (url.indexOf(".babylon") !== -1) {
  13383. targetStore = "scenes";
  13384. } else {
  13385. targetStore = "textures";
  13386. }
  13387. var file;
  13388. var transaction = this.db.transaction([targetStore]);
  13389. transaction.oncomplete = function (event) {
  13390. if (file) {
  13391. callback(file.data);
  13392. } else {
  13393. notInDBCallback();
  13394. }
  13395. };
  13396. transaction.onabort = function (event) {
  13397. notInDBCallback();
  13398. };
  13399. var getRequest = transaction.objectStore(targetStore).get(url);
  13400. getRequest.onsuccess = function (event) {
  13401. file = (event.target).result;
  13402. };
  13403. getRequest.onerror = function (event) {
  13404. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13405. notInDBCallback();
  13406. };
  13407. } else {
  13408. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13409. callback();
  13410. }
  13411. };
  13412. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13413. var _this = this;
  13414. if (this.isSupported) {
  13415. var targetStore;
  13416. if (url.indexOf(".babylon") !== -1) {
  13417. targetStore = "scenes";
  13418. } else {
  13419. targetStore = "textures";
  13420. }
  13421. // Create XHR
  13422. var xhr = new XMLHttpRequest(), fileData;
  13423. xhr.open("GET", url, true);
  13424. if (useArrayBuffer) {
  13425. xhr.responseType = "arraybuffer";
  13426. }
  13427. xhr.onprogress = progressCallback;
  13428. xhr.addEventListener("load", function () {
  13429. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13430. // Blob as response (XHR2)
  13431. //fileData = xhr.responseText;
  13432. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13433. if (!_this.hasReachedQuota) {
  13434. // Open a transaction to the database
  13435. var transaction = _this.db.transaction([targetStore], "readwrite");
  13436. // the transaction could abort because of a QuotaExceededError error
  13437. transaction.onabort = function (event) {
  13438. try {
  13439. if (event.srcElement.error.name === "QuotaExceededError") {
  13440. this.hasReachedQuota = true;
  13441. }
  13442. } catch (ex) {
  13443. }
  13444. callback(fileData);
  13445. };
  13446. transaction.oncomplete = function (event) {
  13447. callback(fileData);
  13448. };
  13449. var newFile;
  13450. if (targetStore === "scenes") {
  13451. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13452. } else {
  13453. newFile = { textureUrl: url, data: fileData };
  13454. }
  13455. try {
  13456. // Put the scene into the database
  13457. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13458. addRequest.onsuccess = function (event) {
  13459. };
  13460. addRequest.onerror = function (event) {
  13461. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13462. };
  13463. } catch (ex) {
  13464. callback(fileData);
  13465. }
  13466. } else {
  13467. callback(fileData);
  13468. }
  13469. } else {
  13470. callback();
  13471. }
  13472. }, false);
  13473. xhr.addEventListener("error", function (event) {
  13474. BABYLON.Tools.Error("error on XHR request.");
  13475. callback();
  13476. }, false);
  13477. xhr.send();
  13478. } else {
  13479. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13480. callback();
  13481. }
  13482. };
  13483. Database.isUASupportingBlobStorage = true;
  13484. Database.parseURL = function (url) {
  13485. var a = document.createElement('a');
  13486. a.href = url;
  13487. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13488. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13489. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13490. return absLocation;
  13491. };
  13492. Database.ReturnFullUrlLocation = function (url) {
  13493. if (url.indexOf("http:/") === -1) {
  13494. return (BABYLON.Database.parseURL(window.location.href) + url);
  13495. } else {
  13496. return url;
  13497. }
  13498. };
  13499. return Database;
  13500. })();
  13501. BABYLON.Database = Database;
  13502. })(BABYLON || (BABYLON = {}));
  13503. //# sourceMappingURL=babylon.database.js.map
  13504. var BABYLON;
  13505. (function (BABYLON) {
  13506. var SpriteManager = (function () {
  13507. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13508. this.name = name;
  13509. this.cellSize = cellSize;
  13510. this.sprites = new Array();
  13511. this.renderingGroupId = 0;
  13512. this.fogEnabled = true;
  13513. this._vertexDeclaration = [3, 4, 4, 4];
  13514. this._vertexStrideSize = 15 * 4;
  13515. this._capacity = capacity;
  13516. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13517. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13518. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13519. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13520. this._scene = scene;
  13521. this._scene.spriteManagers.push(this);
  13522. // VBO
  13523. this._vertexDeclaration = [3, 4, 4, 4];
  13524. this._vertexStrideSize = 15 * 4;
  13525. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13526. var indices = [];
  13527. var index = 0;
  13528. for (var count = 0; count < capacity; count++) {
  13529. indices.push(index);
  13530. indices.push(index + 1);
  13531. indices.push(index + 2);
  13532. indices.push(index);
  13533. indices.push(index + 2);
  13534. indices.push(index + 3);
  13535. index += 4;
  13536. }
  13537. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13538. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13539. // Effects
  13540. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13541. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13542. }
  13543. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13544. var arrayOffset = index * 15;
  13545. if (offsetX == 0)
  13546. offsetX = this._epsilon;
  13547. else if (offsetX == 1)
  13548. offsetX = 1 - this._epsilon;
  13549. if (offsetY == 0)
  13550. offsetY = this._epsilon;
  13551. else if (offsetY == 1)
  13552. offsetY = 1 - this._epsilon;
  13553. this._vertices[arrayOffset] = sprite.position.x;
  13554. this._vertices[arrayOffset + 1] = sprite.position.y;
  13555. this._vertices[arrayOffset + 2] = sprite.position.z;
  13556. this._vertices[arrayOffset + 3] = sprite.angle;
  13557. this._vertices[arrayOffset + 4] = sprite.size;
  13558. this._vertices[arrayOffset + 5] = offsetX;
  13559. this._vertices[arrayOffset + 6] = offsetY;
  13560. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13561. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13562. var offset = (sprite.cellIndex / rowSize) >> 0;
  13563. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13564. this._vertices[arrayOffset + 10] = offset;
  13565. // Color
  13566. this._vertices[arrayOffset + 11] = sprite.color.r;
  13567. this._vertices[arrayOffset + 12] = sprite.color.g;
  13568. this._vertices[arrayOffset + 13] = sprite.color.b;
  13569. this._vertices[arrayOffset + 14] = sprite.color.a;
  13570. };
  13571. SpriteManager.prototype.render = function () {
  13572. // Check
  13573. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13574. return;
  13575. var engine = this._scene.getEngine();
  13576. var baseSize = this._spriteTexture.getBaseSize();
  13577. // Sprites
  13578. var deltaTime = engine.getDeltaTime();
  13579. var max = Math.min(this._capacity, this.sprites.length);
  13580. var rowSize = baseSize.width / this.cellSize;
  13581. var offset = 0;
  13582. for (var index = 0; index < max; index++) {
  13583. var sprite = this.sprites[index];
  13584. if (!sprite) {
  13585. continue;
  13586. }
  13587. sprite._animate(deltaTime);
  13588. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13589. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13590. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13591. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13592. }
  13593. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13594. // Render
  13595. var effect = this._effectBase;
  13596. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13597. effect = this._effectFog;
  13598. }
  13599. engine.enableEffect(effect);
  13600. var viewMatrix = this._scene.getViewMatrix();
  13601. effect.setTexture("diffuseSampler", this._spriteTexture);
  13602. effect.setMatrix("view", viewMatrix);
  13603. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13604. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13605. // Fog
  13606. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13607. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13608. effect.setColor3("vFogColor", this._scene.fogColor);
  13609. }
  13610. // VBOs
  13611. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13612. // Draw order
  13613. effect.setBool("alphaTest", true);
  13614. engine.setColorWrite(false);
  13615. engine.draw(true, 0, max * 6);
  13616. engine.setColorWrite(true);
  13617. effect.setBool("alphaTest", false);
  13618. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13619. engine.draw(true, 0, max * 6);
  13620. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13621. };
  13622. SpriteManager.prototype.dispose = function () {
  13623. if (this._vertexBuffer) {
  13624. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13625. this._vertexBuffer = null;
  13626. }
  13627. if (this._indexBuffer) {
  13628. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13629. this._indexBuffer = null;
  13630. }
  13631. if (this._spriteTexture) {
  13632. this._spriteTexture.dispose();
  13633. this._spriteTexture = null;
  13634. }
  13635. // Remove from scene
  13636. var index = this._scene.spriteManagers.indexOf(this);
  13637. this._scene.spriteManagers.splice(index, 1);
  13638. // Callback
  13639. if (this.onDispose) {
  13640. this.onDispose();
  13641. }
  13642. };
  13643. return SpriteManager;
  13644. })();
  13645. BABYLON.SpriteManager = SpriteManager;
  13646. })(BABYLON || (BABYLON = {}));
  13647. //# sourceMappingURL=babylon.spriteManager.js.map
  13648. var BABYLON;
  13649. (function (BABYLON) {
  13650. var Sprite = (function () {
  13651. function Sprite(name, manager) {
  13652. this.name = name;
  13653. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13654. this.size = 1.0;
  13655. this.angle = 0;
  13656. this.cellIndex = 0;
  13657. this.invertU = 0;
  13658. this.invertV = 0;
  13659. this.animations = new Array();
  13660. this._animationStarted = false;
  13661. this._loopAnimation = false;
  13662. this._fromIndex = 0;
  13663. this._toIndex = 0;
  13664. this._delay = 0;
  13665. this._direction = 1;
  13666. this._frameCount = 0;
  13667. this._time = 0;
  13668. this._manager = manager;
  13669. this._manager.sprites.push(this);
  13670. this.position = BABYLON.Vector3.Zero();
  13671. }
  13672. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13673. this._fromIndex = from;
  13674. this._toIndex = to;
  13675. this._loopAnimation = loop;
  13676. this._delay = delay;
  13677. this._animationStarted = true;
  13678. this._direction = from < to ? 1 : -1;
  13679. this.cellIndex = from;
  13680. this._time = 0;
  13681. };
  13682. Sprite.prototype.stopAnimation = function () {
  13683. this._animationStarted = false;
  13684. };
  13685. Sprite.prototype._animate = function (deltaTime) {
  13686. if (!this._animationStarted)
  13687. return;
  13688. this._time += deltaTime;
  13689. if (this._time > this._delay) {
  13690. this._time = this._time % this._delay;
  13691. this.cellIndex += this._direction;
  13692. if (this.cellIndex == this._toIndex) {
  13693. if (this._loopAnimation) {
  13694. this.cellIndex = this._fromIndex;
  13695. } else {
  13696. this._animationStarted = false;
  13697. if (this.disposeWhenFinishedAnimating) {
  13698. this.dispose();
  13699. }
  13700. }
  13701. }
  13702. }
  13703. };
  13704. Sprite.prototype.dispose = function () {
  13705. for (var i = 0; i < this._manager.sprites.length; i++) {
  13706. if (this._manager.sprites[i] == this) {
  13707. this._manager.sprites.splice(i, 1);
  13708. }
  13709. }
  13710. };
  13711. return Sprite;
  13712. })();
  13713. BABYLON.Sprite = Sprite;
  13714. })(BABYLON || (BABYLON = {}));
  13715. //# sourceMappingURL=babylon.sprite.js.map
  13716. var BABYLON;
  13717. (function (BABYLON) {
  13718. var Layer = (function () {
  13719. function Layer(name, imgUrl, scene, isBackground, color) {
  13720. this.name = name;
  13721. this._vertexDeclaration = [2];
  13722. this._vertexStrideSize = 2 * 4;
  13723. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13724. this.isBackground = isBackground === undefined ? true : isBackground;
  13725. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13726. this._scene = scene;
  13727. this._scene.layers.push(this);
  13728. // VBO
  13729. var vertices = [];
  13730. vertices.push(1, 1);
  13731. vertices.push(-1, 1);
  13732. vertices.push(-1, -1);
  13733. vertices.push(1, -1);
  13734. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13735. // Indices
  13736. var indices = [];
  13737. indices.push(0);
  13738. indices.push(1);
  13739. indices.push(2);
  13740. indices.push(0);
  13741. indices.push(2);
  13742. indices.push(3);
  13743. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13744. // Effects
  13745. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13746. }
  13747. Layer.prototype.render = function () {
  13748. // Check
  13749. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13750. return;
  13751. var engine = this._scene.getEngine();
  13752. // Render
  13753. engine.enableEffect(this._effect);
  13754. engine.setState(false);
  13755. // Texture
  13756. this._effect.setTexture("textureSampler", this.texture);
  13757. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13758. // Color
  13759. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13760. // VBOs
  13761. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13762. // Draw order
  13763. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13764. engine.draw(true, 0, 6);
  13765. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13766. };
  13767. Layer.prototype.dispose = function () {
  13768. if (this._vertexBuffer) {
  13769. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13770. this._vertexBuffer = null;
  13771. }
  13772. if (this._indexBuffer) {
  13773. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13774. this._indexBuffer = null;
  13775. }
  13776. if (this.texture) {
  13777. this.texture.dispose();
  13778. this.texture = null;
  13779. }
  13780. // Remove from scene
  13781. var index = this._scene.layers.indexOf(this);
  13782. this._scene.layers.splice(index, 1);
  13783. // Callback
  13784. if (this.onDispose) {
  13785. this.onDispose();
  13786. }
  13787. };
  13788. return Layer;
  13789. })();
  13790. BABYLON.Layer = Layer;
  13791. })(BABYLON || (BABYLON = {}));
  13792. //# sourceMappingURL=babylon.layer.js.map
  13793. var BABYLON;
  13794. (function (BABYLON) {
  13795. var Particle = (function () {
  13796. function Particle() {
  13797. this.position = BABYLON.Vector3.Zero();
  13798. this.direction = BABYLON.Vector3.Zero();
  13799. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13800. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13801. this.lifeTime = 1.0;
  13802. this.age = 0;
  13803. this.size = 0;
  13804. this.angle = 0;
  13805. this.angularSpeed = 0;
  13806. }
  13807. return Particle;
  13808. })();
  13809. BABYLON.Particle = Particle;
  13810. })(BABYLON || (BABYLON = {}));
  13811. //# sourceMappingURL=babylon.particle.js.map
  13812. var BABYLON;
  13813. (function (BABYLON) {
  13814. var randomNumber = function (min, max) {
  13815. if (min === max) {
  13816. return (min);
  13817. }
  13818. var random = Math.random();
  13819. return ((random * (max - min)) + min);
  13820. };
  13821. var ParticleSystem = (function () {
  13822. function ParticleSystem(name, capacity, scene, customEffect) {
  13823. var _this = this;
  13824. this.name = name;
  13825. this.renderingGroupId = 0;
  13826. this.emitter = null;
  13827. this.emitRate = 10;
  13828. this.manualEmitCount = -1;
  13829. this.updateSpeed = 0.01;
  13830. this.targetStopDuration = 0;
  13831. this.disposeOnStop = false;
  13832. this.minEmitPower = 1;
  13833. this.maxEmitPower = 1;
  13834. this.minLifeTime = 1;
  13835. this.maxLifeTime = 1;
  13836. this.minSize = 1;
  13837. this.maxSize = 1;
  13838. this.minAngularSpeed = 0;
  13839. this.maxAngularSpeed = 0;
  13840. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13841. this.forceDepthWrite = false;
  13842. this.gravity = BABYLON.Vector3.Zero();
  13843. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13844. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13845. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13846. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13847. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13848. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13849. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13850. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13851. this.particles = new Array();
  13852. this._vertexDeclaration = [3, 4, 4];
  13853. this._vertexStrideSize = 11 * 4;
  13854. this._stockParticles = new Array();
  13855. this._newPartsExcess = 0;
  13856. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13857. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13858. this._scaledDirection = BABYLON.Vector3.Zero();
  13859. this._scaledGravity = BABYLON.Vector3.Zero();
  13860. this._currentRenderId = -1;
  13861. this._started = false;
  13862. this._stopped = false;
  13863. this._actualFrame = 0;
  13864. this.id = name;
  13865. this._capacity = capacity;
  13866. this._scene = scene;
  13867. this._customEffect = customEffect;
  13868. scene.particleSystems.push(this);
  13869. // VBO
  13870. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13871. var indices = [];
  13872. var index = 0;
  13873. for (var count = 0; count < capacity; count++) {
  13874. indices.push(index);
  13875. indices.push(index + 1);
  13876. indices.push(index + 2);
  13877. indices.push(index);
  13878. indices.push(index + 2);
  13879. indices.push(index + 3);
  13880. index += 4;
  13881. }
  13882. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13883. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13884. // Default behaviors
  13885. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13886. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13887. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13888. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13889. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13890. };
  13891. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13892. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  13893. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  13894. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  13895. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  13896. };
  13897. this.updateFunction = function (particles) {
  13898. for (var index = 0; index < particles.length; index++) {
  13899. var particle = particles[index];
  13900. particle.age += _this._scaledUpdateSpeed;
  13901. if (particle.age >= particle.lifeTime) {
  13902. particles.splice(index, 1);
  13903. _this._stockParticles.push(particle);
  13904. index--;
  13905. continue;
  13906. } else {
  13907. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  13908. particle.color.addInPlace(_this._scaledColorStep);
  13909. if (particle.color.a < 0)
  13910. particle.color.a = 0;
  13911. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  13912. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  13913. particle.position.addInPlace(_this._scaledDirection);
  13914. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  13915. particle.direction.addInPlace(_this._scaledGravity);
  13916. }
  13917. }
  13918. };
  13919. }
  13920. ParticleSystem.prototype.getCapacity = function () {
  13921. return this._capacity;
  13922. };
  13923. ParticleSystem.prototype.isAlive = function () {
  13924. return this._alive;
  13925. };
  13926. ParticleSystem.prototype.isStarted = function () {
  13927. return this._started;
  13928. };
  13929. ParticleSystem.prototype.start = function () {
  13930. this._started = true;
  13931. this._stopped = false;
  13932. this._actualFrame = 0;
  13933. };
  13934. ParticleSystem.prototype.stop = function () {
  13935. this._stopped = true;
  13936. };
  13937. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  13938. var offset = index * 11;
  13939. this._vertices[offset] = particle.position.x;
  13940. this._vertices[offset + 1] = particle.position.y;
  13941. this._vertices[offset + 2] = particle.position.z;
  13942. this._vertices[offset + 3] = particle.color.r;
  13943. this._vertices[offset + 4] = particle.color.g;
  13944. this._vertices[offset + 5] = particle.color.b;
  13945. this._vertices[offset + 6] = particle.color.a;
  13946. this._vertices[offset + 7] = particle.angle;
  13947. this._vertices[offset + 8] = particle.size;
  13948. this._vertices[offset + 9] = offsetX;
  13949. this._vertices[offset + 10] = offsetY;
  13950. };
  13951. ParticleSystem.prototype._update = function (newParticles) {
  13952. // Update current
  13953. this._alive = this.particles.length > 0;
  13954. this.updateFunction(this.particles);
  13955. // Add new ones
  13956. var worldMatrix;
  13957. if (this.emitter.position) {
  13958. worldMatrix = this.emitter.getWorldMatrix();
  13959. } else {
  13960. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  13961. }
  13962. for (var index = 0; index < newParticles; index++) {
  13963. if (this.particles.length === this._capacity) {
  13964. break;
  13965. }
  13966. if (this._stockParticles.length !== 0) {
  13967. var particle = this._stockParticles.pop();
  13968. particle.age = 0;
  13969. } else {
  13970. particle = new BABYLON.Particle();
  13971. }
  13972. this.particles.push(particle);
  13973. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  13974. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  13975. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  13976. particle.size = randomNumber(this.minSize, this.maxSize);
  13977. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  13978. this.startPositionFunction(worldMatrix, particle.position);
  13979. var step = randomNumber(0, 1.0);
  13980. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  13981. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  13982. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  13983. }
  13984. };
  13985. ParticleSystem.prototype._getEffect = function () {
  13986. if (this._customEffect) {
  13987. return this._customEffect;
  13988. }
  13989. ;
  13990. var defines = [];
  13991. if (this._scene.clipPlane) {
  13992. defines.push("#define CLIPPLANE");
  13993. }
  13994. // Effect
  13995. var join = defines.join("\n");
  13996. if (this._cachedDefines !== join) {
  13997. this._cachedDefines = join;
  13998. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  13999. }
  14000. return this._effect;
  14001. };
  14002. ParticleSystem.prototype.animate = function () {
  14003. if (!this._started)
  14004. return;
  14005. var effect = this._getEffect();
  14006. // Check
  14007. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14008. return;
  14009. if (this._currentRenderId === this._scene.getRenderId()) {
  14010. return;
  14011. }
  14012. this._currentRenderId = this._scene.getRenderId();
  14013. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14014. // determine the number of particles we need to create
  14015. var emitCout;
  14016. if (this.manualEmitCount > -1) {
  14017. emitCout = this.manualEmitCount;
  14018. this.manualEmitCount = 0;
  14019. } else {
  14020. emitCout = this.emitRate;
  14021. }
  14022. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14023. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14024. if (this._newPartsExcess > 1.0) {
  14025. newParticles += this._newPartsExcess >> 0;
  14026. this._newPartsExcess -= this._newPartsExcess >> 0;
  14027. }
  14028. this._alive = false;
  14029. if (!this._stopped) {
  14030. this._actualFrame += this._scaledUpdateSpeed;
  14031. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14032. this.stop();
  14033. } else {
  14034. newParticles = 0;
  14035. }
  14036. this._update(newParticles);
  14037. // Stopped?
  14038. if (this._stopped) {
  14039. if (!this._alive) {
  14040. this._started = false;
  14041. if (this.disposeOnStop) {
  14042. this._scene._toBeDisposed.push(this);
  14043. }
  14044. }
  14045. }
  14046. // Update VBO
  14047. var offset = 0;
  14048. for (var index = 0; index < this.particles.length; index++) {
  14049. var particle = this.particles[index];
  14050. this._appendParticleVertex(offset++, particle, 0, 0);
  14051. this._appendParticleVertex(offset++, particle, 1, 0);
  14052. this._appendParticleVertex(offset++, particle, 1, 1);
  14053. this._appendParticleVertex(offset++, particle, 0, 1);
  14054. }
  14055. var engine = this._scene.getEngine();
  14056. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14057. };
  14058. ParticleSystem.prototype.render = function () {
  14059. var effect = this._getEffect();
  14060. // Check
  14061. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14062. return 0;
  14063. var engine = this._scene.getEngine();
  14064. // Render
  14065. engine.enableEffect(effect);
  14066. engine.setState(false);
  14067. var viewMatrix = this._scene.getViewMatrix();
  14068. effect.setTexture("diffuseSampler", this.particleTexture);
  14069. effect.setMatrix("view", viewMatrix);
  14070. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14071. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14072. if (this._scene.clipPlane) {
  14073. var clipPlane = this._scene.clipPlane;
  14074. var invView = viewMatrix.clone();
  14075. invView.invert();
  14076. effect.setMatrix("invView", invView);
  14077. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14078. }
  14079. // VBOs
  14080. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14081. // Draw order
  14082. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14083. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14084. } else {
  14085. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14086. }
  14087. if (this.forceDepthWrite) {
  14088. engine.setDepthWrite(true);
  14089. }
  14090. engine.draw(true, 0, this.particles.length * 6);
  14091. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14092. return this.particles.length;
  14093. };
  14094. ParticleSystem.prototype.dispose = function () {
  14095. if (this._vertexBuffer) {
  14096. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14097. this._vertexBuffer = null;
  14098. }
  14099. if (this._indexBuffer) {
  14100. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14101. this._indexBuffer = null;
  14102. }
  14103. if (this.particleTexture) {
  14104. this.particleTexture.dispose();
  14105. this.particleTexture = null;
  14106. }
  14107. // Remove from scene
  14108. var index = this._scene.particleSystems.indexOf(this);
  14109. this._scene.particleSystems.splice(index, 1);
  14110. // Callback
  14111. if (this.onDispose) {
  14112. this.onDispose();
  14113. }
  14114. };
  14115. // Clone
  14116. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14117. var result = new ParticleSystem(name, this._capacity, this._scene);
  14118. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14119. if (newEmitter === undefined) {
  14120. newEmitter = this.emitter;
  14121. }
  14122. result.emitter = newEmitter;
  14123. if (this.particleTexture) {
  14124. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14125. }
  14126. result.start();
  14127. return result;
  14128. };
  14129. ParticleSystem.BLENDMODE_ONEONE = 0;
  14130. ParticleSystem.BLENDMODE_STANDARD = 1;
  14131. return ParticleSystem;
  14132. })();
  14133. BABYLON.ParticleSystem = ParticleSystem;
  14134. })(BABYLON || (BABYLON = {}));
  14135. //# sourceMappingURL=babylon.particleSystem.js.map
  14136. var BABYLON;
  14137. (function (BABYLON) {
  14138. var Animation = (function () {
  14139. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14140. this.name = name;
  14141. this.targetProperty = targetProperty;
  14142. this.framePerSecond = framePerSecond;
  14143. this.dataType = dataType;
  14144. this.loopMode = loopMode;
  14145. this._offsetsCache = {};
  14146. this._highLimitsCache = {};
  14147. this._stopped = false;
  14148. this.targetPropertyPath = targetProperty.split(".");
  14149. this.dataType = dataType;
  14150. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14151. }
  14152. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14153. var dataType = undefined;
  14154. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14155. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14156. } else if (from instanceof BABYLON.Quaternion) {
  14157. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14158. } else if (from instanceof BABYLON.Vector3) {
  14159. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14160. } else if (from instanceof BABYLON.Vector2) {
  14161. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14162. } else if (from instanceof BABYLON.Color3) {
  14163. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14164. }
  14165. if (dataType == undefined) {
  14166. return;
  14167. }
  14168. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14169. var keys = [];
  14170. keys.push({ frame: 0, value: from });
  14171. keys.push({ frame: totalFrame, value: to });
  14172. animation.setKeys(keys);
  14173. mesh.animations.push(animation);
  14174. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  14175. };
  14176. // Methods
  14177. Animation.prototype.isStopped = function () {
  14178. return this._stopped;
  14179. };
  14180. Animation.prototype.getKeys = function () {
  14181. return this._keys;
  14182. };
  14183. Animation.prototype.getEasingFunction = function () {
  14184. return this._easingFunction;
  14185. };
  14186. Animation.prototype.setEasingFunction = function (easingFunction) {
  14187. this._easingFunction = easingFunction;
  14188. };
  14189. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14190. return startValue + (endValue - startValue) * gradient;
  14191. };
  14192. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14193. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14194. };
  14195. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14196. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14197. };
  14198. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14199. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14200. };
  14201. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14202. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14203. };
  14204. Animation.prototype.clone = function () {
  14205. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14206. clone.setKeys(this._keys);
  14207. return clone;
  14208. };
  14209. Animation.prototype.setKeys = function (values) {
  14210. this._keys = values.slice(0);
  14211. this._offsetsCache = {};
  14212. this._highLimitsCache = {};
  14213. };
  14214. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14215. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14216. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14217. }
  14218. this.currentFrame = currentFrame;
  14219. for (var key = 0; key < this._keys.length; key++) {
  14220. // for each frame, we need the key just before the frame superior
  14221. if (this._keys[key + 1].frame >= currentFrame) {
  14222. var startValue = this._keys[key].value;
  14223. var endValue = this._keys[key + 1].value;
  14224. // gradient : percent of currentFrame between the frame inf and the frame sup
  14225. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14226. // check for easingFunction and correction of gradient
  14227. if (this._easingFunction != null) {
  14228. gradient = this._easingFunction.ease(gradient);
  14229. }
  14230. switch (this.dataType) {
  14231. case Animation.ANIMATIONTYPE_FLOAT:
  14232. switch (loopMode) {
  14233. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14234. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14235. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14236. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14237. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14238. }
  14239. break;
  14240. case Animation.ANIMATIONTYPE_QUATERNION:
  14241. var quaternion = null;
  14242. switch (loopMode) {
  14243. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14244. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14245. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14246. break;
  14247. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14248. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14249. break;
  14250. }
  14251. return quaternion;
  14252. case Animation.ANIMATIONTYPE_VECTOR3:
  14253. switch (loopMode) {
  14254. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14255. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14256. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14257. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14258. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14259. }
  14260. case Animation.ANIMATIONTYPE_VECTOR2:
  14261. switch (loopMode) {
  14262. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14263. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14264. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14265. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14266. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14267. }
  14268. case Animation.ANIMATIONTYPE_COLOR3:
  14269. switch (loopMode) {
  14270. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14271. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14272. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14273. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14274. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14275. }
  14276. case Animation.ANIMATIONTYPE_MATRIX:
  14277. switch (loopMode) {
  14278. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14279. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14280. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14281. return startValue;
  14282. }
  14283. default:
  14284. break;
  14285. }
  14286. break;
  14287. }
  14288. }
  14289. return this._keys[this._keys.length - 1].value;
  14290. };
  14291. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14292. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14293. this._stopped = true;
  14294. return false;
  14295. }
  14296. var returnValue = true;
  14297. // Adding a start key at frame 0 if missing
  14298. if (this._keys[0].frame != 0) {
  14299. var newKey = { frame: 0, value: this._keys[0].value };
  14300. this._keys.splice(0, 0, newKey);
  14301. }
  14302. // Check limits
  14303. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14304. from = this._keys[0].frame;
  14305. }
  14306. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14307. to = this._keys[this._keys.length - 1].frame;
  14308. }
  14309. // Compute ratio
  14310. var range = to - from;
  14311. var offsetValue;
  14312. // ratio represents the frame delta between from and to
  14313. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14314. if (ratio > range && !loop) {
  14315. returnValue = false;
  14316. highLimitValue = this._keys[this._keys.length - 1].value;
  14317. } else {
  14318. // Get max value if required
  14319. var highLimitValue = 0;
  14320. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  14321. var keyOffset = to.toString() + from.toString();
  14322. if (!this._offsetsCache[keyOffset]) {
  14323. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14324. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14325. switch (this.dataType) {
  14326. case Animation.ANIMATIONTYPE_FLOAT:
  14327. this._offsetsCache[keyOffset] = toValue - fromValue;
  14328. break;
  14329. case Animation.ANIMATIONTYPE_QUATERNION:
  14330. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14331. break;
  14332. case Animation.ANIMATIONTYPE_VECTOR3:
  14333. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14334. case Animation.ANIMATIONTYPE_VECTOR2:
  14335. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14336. case Animation.ANIMATIONTYPE_COLOR3:
  14337. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14338. default:
  14339. break;
  14340. }
  14341. this._highLimitsCache[keyOffset] = toValue;
  14342. }
  14343. highLimitValue = this._highLimitsCache[keyOffset];
  14344. offsetValue = this._offsetsCache[keyOffset];
  14345. }
  14346. }
  14347. if (offsetValue === undefined) {
  14348. switch (this.dataType) {
  14349. case Animation.ANIMATIONTYPE_FLOAT:
  14350. offsetValue = 0;
  14351. break;
  14352. case Animation.ANIMATIONTYPE_QUATERNION:
  14353. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14354. break;
  14355. case Animation.ANIMATIONTYPE_VECTOR3:
  14356. offsetValue = BABYLON.Vector3.Zero();
  14357. break;
  14358. case Animation.ANIMATIONTYPE_VECTOR2:
  14359. offsetValue = BABYLON.Vector2.Zero();
  14360. break;
  14361. case Animation.ANIMATIONTYPE_COLOR3:
  14362. offsetValue = BABYLON.Color3.Black();
  14363. }
  14364. }
  14365. // Compute value
  14366. var repeatCount = (ratio / range) >> 0;
  14367. var currentFrame = returnValue ? from + ratio % range : to;
  14368. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14369. // Set value
  14370. if (this.targetPropertyPath.length > 1) {
  14371. var property = this._target[this.targetPropertyPath[0]];
  14372. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14373. property = property[this.targetPropertyPath[index]];
  14374. }
  14375. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14376. } else {
  14377. this._target[this.targetPropertyPath[0]] = currentValue;
  14378. }
  14379. if (this._target.markAsDirty) {
  14380. this._target.markAsDirty(this.targetProperty);
  14381. }
  14382. if (!returnValue) {
  14383. this._stopped = true;
  14384. }
  14385. return returnValue;
  14386. };
  14387. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14388. get: function () {
  14389. return Animation._ANIMATIONTYPE_FLOAT;
  14390. },
  14391. enumerable: true,
  14392. configurable: true
  14393. });
  14394. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14395. get: function () {
  14396. return Animation._ANIMATIONTYPE_VECTOR3;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14402. get: function () {
  14403. return Animation._ANIMATIONTYPE_VECTOR2;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14409. get: function () {
  14410. return Animation._ANIMATIONTYPE_QUATERNION;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14416. get: function () {
  14417. return Animation._ANIMATIONTYPE_MATRIX;
  14418. },
  14419. enumerable: true,
  14420. configurable: true
  14421. });
  14422. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14423. get: function () {
  14424. return Animation._ANIMATIONTYPE_COLOR3;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14430. get: function () {
  14431. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14437. get: function () {
  14438. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14439. },
  14440. enumerable: true,
  14441. configurable: true
  14442. });
  14443. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14444. get: function () {
  14445. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. Animation._ANIMATIONTYPE_FLOAT = 0;
  14451. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14452. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14453. Animation._ANIMATIONTYPE_MATRIX = 3;
  14454. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14455. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14456. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14457. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14458. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14459. return Animation;
  14460. })();
  14461. BABYLON.Animation = Animation;
  14462. })(BABYLON || (BABYLON = {}));
  14463. //# sourceMappingURL=babylon.animation.js.map
  14464. var BABYLON;
  14465. (function (BABYLON) {
  14466. var Animatable = (function () {
  14467. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14468. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14469. if (typeof toFrame === "undefined") { toFrame = 100; }
  14470. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14471. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14472. this.target = target;
  14473. this.fromFrame = fromFrame;
  14474. this.toFrame = toFrame;
  14475. this.loopAnimation = loopAnimation;
  14476. this.speedRatio = speedRatio;
  14477. this.onAnimationEnd = onAnimationEnd;
  14478. this._animations = new Array();
  14479. this._paused = false;
  14480. this.animationStarted = false;
  14481. if (animations) {
  14482. this.appendAnimations(target, animations);
  14483. }
  14484. this._scene = scene;
  14485. scene._activeAnimatables.push(this);
  14486. }
  14487. // Methods
  14488. Animatable.prototype.appendAnimations = function (target, animations) {
  14489. for (var index = 0; index < animations.length; index++) {
  14490. var animation = animations[index];
  14491. animation._target = target;
  14492. this._animations.push(animation);
  14493. }
  14494. };
  14495. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14496. var animations = this._animations;
  14497. for (var index = 0; index < animations.length; index++) {
  14498. if (animations[index].targetProperty === property) {
  14499. return animations[index];
  14500. }
  14501. }
  14502. return null;
  14503. };
  14504. Animatable.prototype.pause = function () {
  14505. if (this._paused) {
  14506. return;
  14507. }
  14508. this._paused = true;
  14509. };
  14510. Animatable.prototype.restart = function () {
  14511. this._paused = false;
  14512. };
  14513. Animatable.prototype.stop = function () {
  14514. var index = this._scene._activeAnimatables.indexOf(this);
  14515. if (index > -1) {
  14516. this._scene._activeAnimatables.splice(index, 1);
  14517. }
  14518. if (this.onAnimationEnd) {
  14519. this.onAnimationEnd();
  14520. }
  14521. };
  14522. Animatable.prototype._animate = function (delay) {
  14523. if (this._paused) {
  14524. if (!this._pausedDelay) {
  14525. this._pausedDelay = delay;
  14526. }
  14527. return true;
  14528. }
  14529. if (!this._localDelayOffset) {
  14530. this._localDelayOffset = delay;
  14531. } else if (this._pausedDelay) {
  14532. this._localDelayOffset += delay - this._pausedDelay;
  14533. this._pausedDelay = null;
  14534. }
  14535. // Animating
  14536. var running = false;
  14537. var animations = this._animations;
  14538. for (var index = 0; index < animations.length; index++) {
  14539. var animation = animations[index];
  14540. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14541. running = running || isRunning;
  14542. }
  14543. if (!running && this.onAnimationEnd) {
  14544. this.onAnimationEnd();
  14545. }
  14546. return running;
  14547. };
  14548. return Animatable;
  14549. })();
  14550. BABYLON.Animatable = Animatable;
  14551. })(BABYLON || (BABYLON = {}));
  14552. //# sourceMappingURL=babylon.animatable.js.map
  14553. var BABYLON;
  14554. (function (BABYLON) {
  14555. var EasingFunction = (function () {
  14556. function EasingFunction() {
  14557. // Properties
  14558. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14559. }
  14560. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14561. get: function () {
  14562. return EasingFunction._EASINGMODE_EASEIN;
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14568. get: function () {
  14569. return EasingFunction._EASINGMODE_EASEOUT;
  14570. },
  14571. enumerable: true,
  14572. configurable: true
  14573. });
  14574. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14575. get: function () {
  14576. return EasingFunction._EASINGMODE_EASEINOUT;
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14582. var n = Math.min(Math.max(easingMode, 0), 2);
  14583. this._easingMode = n;
  14584. };
  14585. EasingFunction.prototype.getEasingMode = function () {
  14586. return this._easingMode;
  14587. };
  14588. EasingFunction.prototype.easeInCore = function (gradient) {
  14589. throw new Error('You must implement this method');
  14590. };
  14591. EasingFunction.prototype.ease = function (gradient) {
  14592. switch (this._easingMode) {
  14593. case EasingFunction.EASINGMODE_EASEIN:
  14594. return this.easeInCore(gradient);
  14595. case EasingFunction.EASINGMODE_EASEOUT:
  14596. return (1 - this.easeInCore(1 - gradient));
  14597. }
  14598. if (gradient >= 0.5) {
  14599. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14600. }
  14601. return (this.easeInCore(gradient * 2) * 0.5);
  14602. };
  14603. EasingFunction._EASINGMODE_EASEIN = 0;
  14604. EasingFunction._EASINGMODE_EASEOUT = 1;
  14605. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14606. return EasingFunction;
  14607. })();
  14608. BABYLON.EasingFunction = EasingFunction;
  14609. var CircleEase = (function (_super) {
  14610. __extends(CircleEase, _super);
  14611. function CircleEase() {
  14612. _super.apply(this, arguments);
  14613. }
  14614. CircleEase.prototype.easeInCore = function (gradient) {
  14615. gradient = Math.max(0, Math.min(1, gradient));
  14616. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14617. };
  14618. return CircleEase;
  14619. })(EasingFunction);
  14620. BABYLON.CircleEase = CircleEase;
  14621. var BackEase = (function (_super) {
  14622. __extends(BackEase, _super);
  14623. function BackEase(amplitude) {
  14624. if (typeof amplitude === "undefined") { amplitude = 1; }
  14625. _super.call(this);
  14626. this.amplitude = amplitude;
  14627. }
  14628. BackEase.prototype.easeInCore = function (gradient) {
  14629. var num = Math.max(0, this.amplitude);
  14630. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14631. };
  14632. return BackEase;
  14633. })(EasingFunction);
  14634. BABYLON.BackEase = BackEase;
  14635. var BounceEase = (function (_super) {
  14636. __extends(BounceEase, _super);
  14637. function BounceEase(bounces, bounciness) {
  14638. if (typeof bounces === "undefined") { bounces = 3; }
  14639. if (typeof bounciness === "undefined") { bounciness = 2; }
  14640. _super.call(this);
  14641. this.bounces = bounces;
  14642. this.bounciness = bounciness;
  14643. }
  14644. BounceEase.prototype.easeInCore = function (gradient) {
  14645. var y = Math.max(0.0, this.bounces);
  14646. var bounciness = this.bounciness;
  14647. if (bounciness <= 1.0) {
  14648. bounciness = 1.001;
  14649. }
  14650. var num9 = Math.pow(bounciness, y);
  14651. var num5 = 1.0 - bounciness;
  14652. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14653. var num15 = gradient * num4;
  14654. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14655. var num3 = Math.floor(num65);
  14656. var num13 = num3 + 1.0;
  14657. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14658. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14659. var num7 = (num8 + num12) * 0.5;
  14660. var num6 = gradient - num7;
  14661. var num2 = num7 - num8;
  14662. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14663. };
  14664. return BounceEase;
  14665. })(EasingFunction);
  14666. BABYLON.BounceEase = BounceEase;
  14667. var CubicEase = (function (_super) {
  14668. __extends(CubicEase, _super);
  14669. function CubicEase() {
  14670. _super.apply(this, arguments);
  14671. }
  14672. CubicEase.prototype.easeInCore = function (gradient) {
  14673. return (gradient * gradient * gradient);
  14674. };
  14675. return CubicEase;
  14676. })(EasingFunction);
  14677. BABYLON.CubicEase = CubicEase;
  14678. var ElasticEase = (function (_super) {
  14679. __extends(ElasticEase, _super);
  14680. function ElasticEase(oscillations, springiness) {
  14681. if (typeof oscillations === "undefined") { oscillations = 3; }
  14682. if (typeof springiness === "undefined") { springiness = 3; }
  14683. _super.call(this);
  14684. this.oscillations = oscillations;
  14685. this.springiness = springiness;
  14686. }
  14687. ElasticEase.prototype.easeInCore = function (gradient) {
  14688. var num2;
  14689. var num3 = Math.max(0.0, this.oscillations);
  14690. var num = Math.max(0.0, this.springiness);
  14691. if (num == 0) {
  14692. num2 = gradient;
  14693. } else {
  14694. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14695. }
  14696. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14697. };
  14698. return ElasticEase;
  14699. })(EasingFunction);
  14700. BABYLON.ElasticEase = ElasticEase;
  14701. var ExponentialEase = (function (_super) {
  14702. __extends(ExponentialEase, _super);
  14703. function ExponentialEase(exponent) {
  14704. if (typeof exponent === "undefined") { exponent = 2; }
  14705. _super.call(this);
  14706. this.exponent = exponent;
  14707. }
  14708. ExponentialEase.prototype.easeInCore = function (gradient) {
  14709. if (this.exponent <= 0) {
  14710. return gradient;
  14711. }
  14712. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14713. };
  14714. return ExponentialEase;
  14715. })(EasingFunction);
  14716. BABYLON.ExponentialEase = ExponentialEase;
  14717. var PowerEase = (function (_super) {
  14718. __extends(PowerEase, _super);
  14719. function PowerEase(power) {
  14720. if (typeof power === "undefined") { power = 2; }
  14721. _super.call(this);
  14722. this.power = power;
  14723. }
  14724. PowerEase.prototype.easeInCore = function (gradient) {
  14725. var y = Math.max(0.0, this.power);
  14726. return Math.pow(gradient, y);
  14727. };
  14728. return PowerEase;
  14729. })(EasingFunction);
  14730. BABYLON.PowerEase = PowerEase;
  14731. var QuadraticEase = (function (_super) {
  14732. __extends(QuadraticEase, _super);
  14733. function QuadraticEase() {
  14734. _super.apply(this, arguments);
  14735. }
  14736. QuadraticEase.prototype.easeInCore = function (gradient) {
  14737. return (gradient * gradient);
  14738. };
  14739. return QuadraticEase;
  14740. })(EasingFunction);
  14741. BABYLON.QuadraticEase = QuadraticEase;
  14742. var QuarticEase = (function (_super) {
  14743. __extends(QuarticEase, _super);
  14744. function QuarticEase() {
  14745. _super.apply(this, arguments);
  14746. }
  14747. QuarticEase.prototype.easeInCore = function (gradient) {
  14748. return (gradient * gradient * gradient * gradient);
  14749. };
  14750. return QuarticEase;
  14751. })(EasingFunction);
  14752. BABYLON.QuarticEase = QuarticEase;
  14753. var QuinticEase = (function (_super) {
  14754. __extends(QuinticEase, _super);
  14755. function QuinticEase() {
  14756. _super.apply(this, arguments);
  14757. }
  14758. QuinticEase.prototype.easeInCore = function (gradient) {
  14759. return (gradient * gradient * gradient * gradient * gradient);
  14760. };
  14761. return QuinticEase;
  14762. })(EasingFunction);
  14763. BABYLON.QuinticEase = QuinticEase;
  14764. var SineEase = (function (_super) {
  14765. __extends(SineEase, _super);
  14766. function SineEase() {
  14767. _super.apply(this, arguments);
  14768. }
  14769. SineEase.prototype.easeInCore = function (gradient) {
  14770. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14771. };
  14772. return SineEase;
  14773. })(EasingFunction);
  14774. BABYLON.SineEase = SineEase;
  14775. var BezierCurveEase = (function (_super) {
  14776. __extends(BezierCurveEase, _super);
  14777. function BezierCurveEase(x1, y1, x2, y2) {
  14778. if (typeof x1 === "undefined") { x1 = 0; }
  14779. if (typeof y1 === "undefined") { y1 = 0; }
  14780. if (typeof x2 === "undefined") { x2 = 1; }
  14781. if (typeof y2 === "undefined") { y2 = 1; }
  14782. _super.call(this);
  14783. this.x1 = x1;
  14784. this.y1 = y1;
  14785. this.x2 = x2;
  14786. this.y2 = y2;
  14787. }
  14788. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14789. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14790. };
  14791. return BezierCurveEase;
  14792. })(EasingFunction);
  14793. BABYLON.BezierCurveEase = BezierCurveEase;
  14794. })(BABYLON || (BABYLON = {}));
  14795. //# sourceMappingURL=babylon.easing.js.map
  14796. var BABYLON;
  14797. (function (BABYLON) {
  14798. var Octree = (function () {
  14799. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14800. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14801. this.maxDepth = maxDepth;
  14802. this.dynamicContent = new Array();
  14803. this._maxBlockCapacity = maxBlockCapacity || 64;
  14804. this._selectionContent = new BABYLON.SmartArray(1024);
  14805. this._creationFunc = creationFunc;
  14806. }
  14807. // Methods
  14808. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14809. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14810. };
  14811. Octree.prototype.addMesh = function (entry) {
  14812. for (var index = 0; index < this.blocks.length; index++) {
  14813. var block = this.blocks[index];
  14814. block.addEntry(entry);
  14815. }
  14816. };
  14817. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14818. this._selectionContent.reset();
  14819. for (var index = 0; index < this.blocks.length; index++) {
  14820. var block = this.blocks[index];
  14821. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14822. }
  14823. if (allowDuplicate) {
  14824. this._selectionContent.concat(this.dynamicContent);
  14825. } else {
  14826. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14827. }
  14828. return this._selectionContent;
  14829. };
  14830. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14831. this._selectionContent.reset();
  14832. for (var index = 0; index < this.blocks.length; index++) {
  14833. var block = this.blocks[index];
  14834. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14835. }
  14836. if (allowDuplicate) {
  14837. this._selectionContent.concat(this.dynamicContent);
  14838. } else {
  14839. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14840. }
  14841. return this._selectionContent;
  14842. };
  14843. Octree.prototype.intersectsRay = function (ray) {
  14844. this._selectionContent.reset();
  14845. for (var index = 0; index < this.blocks.length; index++) {
  14846. var block = this.blocks[index];
  14847. block.intersectsRay(ray, this._selectionContent);
  14848. }
  14849. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14850. return this._selectionContent;
  14851. };
  14852. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14853. target.blocks = new Array();
  14854. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14855. for (var x = 0; x < 2; x++) {
  14856. for (var y = 0; y < 2; y++) {
  14857. for (var z = 0; z < 2; z++) {
  14858. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14859. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14860. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14861. block.addEntries(entries);
  14862. target.blocks.push(block);
  14863. }
  14864. }
  14865. }
  14866. };
  14867. Octree.CreationFuncForMeshes = function (entry, block) {
  14868. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14869. block.entries.push(entry);
  14870. }
  14871. };
  14872. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14873. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14874. block.entries.push(entry);
  14875. }
  14876. };
  14877. return Octree;
  14878. })();
  14879. BABYLON.Octree = Octree;
  14880. })(BABYLON || (BABYLON = {}));
  14881. //# sourceMappingURL=babylon.octree.js.map
  14882. var BABYLON;
  14883. (function (BABYLON) {
  14884. var OctreeBlock = (function () {
  14885. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14886. this.entries = new Array();
  14887. this._boundingVectors = new Array();
  14888. this._capacity = capacity;
  14889. this._depth = depth;
  14890. this._maxDepth = maxDepth;
  14891. this._creationFunc = creationFunc;
  14892. this._minPoint = minPoint;
  14893. this._maxPoint = maxPoint;
  14894. this._boundingVectors.push(minPoint.clone());
  14895. this._boundingVectors.push(maxPoint.clone());
  14896. this._boundingVectors.push(minPoint.clone());
  14897. this._boundingVectors[2].x = maxPoint.x;
  14898. this._boundingVectors.push(minPoint.clone());
  14899. this._boundingVectors[3].y = maxPoint.y;
  14900. this._boundingVectors.push(minPoint.clone());
  14901. this._boundingVectors[4].z = maxPoint.z;
  14902. this._boundingVectors.push(maxPoint.clone());
  14903. this._boundingVectors[5].z = minPoint.z;
  14904. this._boundingVectors.push(maxPoint.clone());
  14905. this._boundingVectors[6].x = minPoint.x;
  14906. this._boundingVectors.push(maxPoint.clone());
  14907. this._boundingVectors[7].y = minPoint.y;
  14908. }
  14909. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  14910. // Property
  14911. get: function () {
  14912. return this._capacity;
  14913. },
  14914. enumerable: true,
  14915. configurable: true
  14916. });
  14917. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  14918. get: function () {
  14919. return this._minPoint;
  14920. },
  14921. enumerable: true,
  14922. configurable: true
  14923. });
  14924. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  14925. get: function () {
  14926. return this._maxPoint;
  14927. },
  14928. enumerable: true,
  14929. configurable: true
  14930. });
  14931. // Methods
  14932. OctreeBlock.prototype.addEntry = function (entry) {
  14933. if (this.blocks) {
  14934. for (var index = 0; index < this.blocks.length; index++) {
  14935. var block = this.blocks[index];
  14936. block.addEntry(entry);
  14937. }
  14938. return;
  14939. }
  14940. this._creationFunc(entry, this);
  14941. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  14942. this.createInnerBlocks();
  14943. }
  14944. };
  14945. OctreeBlock.prototype.addEntries = function (entries) {
  14946. for (var index = 0; index < entries.length; index++) {
  14947. var mesh = entries[index];
  14948. this.addEntry(mesh);
  14949. }
  14950. };
  14951. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  14952. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  14953. if (this.blocks) {
  14954. for (var index = 0; index < this.blocks.length; index++) {
  14955. var block = this.blocks[index];
  14956. block.select(frustumPlanes, selection, allowDuplicate);
  14957. }
  14958. return;
  14959. }
  14960. if (allowDuplicate) {
  14961. selection.concat(this.entries);
  14962. } else {
  14963. selection.concatWithNoDuplicate(this.entries);
  14964. }
  14965. }
  14966. };
  14967. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  14968. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  14969. if (this.blocks) {
  14970. for (var index = 0; index < this.blocks.length; index++) {
  14971. var block = this.blocks[index];
  14972. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  14973. }
  14974. return;
  14975. }
  14976. if (allowDuplicate) {
  14977. selection.concat(this.entries);
  14978. } else {
  14979. selection.concatWithNoDuplicate(this.entries);
  14980. }
  14981. }
  14982. };
  14983. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  14984. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  14985. if (this.blocks) {
  14986. for (var index = 0; index < this.blocks.length; index++) {
  14987. var block = this.blocks[index];
  14988. block.intersectsRay(ray, selection);
  14989. }
  14990. return;
  14991. }
  14992. selection.concatWithNoDuplicate(this.entries);
  14993. }
  14994. };
  14995. OctreeBlock.prototype.createInnerBlocks = function () {
  14996. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  14997. };
  14998. return OctreeBlock;
  14999. })();
  15000. BABYLON.OctreeBlock = OctreeBlock;
  15001. })(BABYLON || (BABYLON = {}));
  15002. //# sourceMappingURL=babylon.octreeBlock.js.map
  15003. var BABYLON;
  15004. (function (BABYLON) {
  15005. var Bone = (function () {
  15006. function Bone(name, skeleton, parentBone, matrix) {
  15007. this.name = name;
  15008. this.children = new Array();
  15009. this.animations = new Array();
  15010. this._worldTransform = new BABYLON.Matrix();
  15011. this._absoluteTransform = new BABYLON.Matrix();
  15012. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15013. this._skeleton = skeleton;
  15014. this._matrix = matrix;
  15015. this._baseMatrix = matrix;
  15016. skeleton.bones.push(this);
  15017. if (parentBone) {
  15018. this._parent = parentBone;
  15019. parentBone.children.push(this);
  15020. } else {
  15021. this._parent = null;
  15022. }
  15023. this._updateDifferenceMatrix();
  15024. }
  15025. // Members
  15026. Bone.prototype.getParent = function () {
  15027. return this._parent;
  15028. };
  15029. Bone.prototype.getLocalMatrix = function () {
  15030. return this._matrix;
  15031. };
  15032. Bone.prototype.getBaseMatrix = function () {
  15033. return this._baseMatrix;
  15034. };
  15035. Bone.prototype.getWorldMatrix = function () {
  15036. return this._worldTransform;
  15037. };
  15038. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15039. return this._invertedAbsoluteTransform;
  15040. };
  15041. Bone.prototype.getAbsoluteMatrix = function () {
  15042. var matrix = this._matrix.clone();
  15043. var parent = this._parent;
  15044. while (parent) {
  15045. matrix = matrix.multiply(parent.getLocalMatrix());
  15046. parent = parent.getParent();
  15047. }
  15048. return matrix;
  15049. };
  15050. // Methods
  15051. Bone.prototype.updateMatrix = function (matrix) {
  15052. this._matrix = matrix;
  15053. this._skeleton._markAsDirty();
  15054. this._updateDifferenceMatrix();
  15055. };
  15056. Bone.prototype._updateDifferenceMatrix = function () {
  15057. if (this._parent) {
  15058. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15059. } else {
  15060. this._absoluteTransform.copyFrom(this._matrix);
  15061. }
  15062. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15063. for (var index = 0; index < this.children.length; index++) {
  15064. this.children[index]._updateDifferenceMatrix();
  15065. }
  15066. };
  15067. Bone.prototype.markAsDirty = function () {
  15068. this._skeleton._markAsDirty();
  15069. };
  15070. return Bone;
  15071. })();
  15072. BABYLON.Bone = Bone;
  15073. })(BABYLON || (BABYLON = {}));
  15074. //# sourceMappingURL=babylon.bone.js.map
  15075. var BABYLON;
  15076. (function (BABYLON) {
  15077. var Skeleton = (function () {
  15078. function Skeleton(name, id, scene) {
  15079. this.name = name;
  15080. this.id = id;
  15081. this.bones = new Array();
  15082. this._isDirty = true;
  15083. this._identity = BABYLON.Matrix.Identity();
  15084. this.bones = [];
  15085. this._scene = scene;
  15086. scene.skeletons.push(this);
  15087. }
  15088. // Members
  15089. Skeleton.prototype.getTransformMatrices = function () {
  15090. return this._transformMatrices;
  15091. };
  15092. // Methods
  15093. Skeleton.prototype._markAsDirty = function () {
  15094. this._isDirty = true;
  15095. };
  15096. Skeleton.prototype.prepare = function () {
  15097. if (!this._isDirty) {
  15098. return;
  15099. }
  15100. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15101. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15102. }
  15103. for (var index = 0; index < this.bones.length; index++) {
  15104. var bone = this.bones[index];
  15105. var parentBone = bone.getParent();
  15106. if (parentBone) {
  15107. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15108. } else {
  15109. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15110. }
  15111. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15112. }
  15113. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15114. this._isDirty = false;
  15115. };
  15116. Skeleton.prototype.getAnimatables = function () {
  15117. if (!this._animatables || this._animatables.length != this.bones.length) {
  15118. this._animatables = [];
  15119. for (var index = 0; index < this.bones.length; index++) {
  15120. this._animatables.push(this.bones[index]);
  15121. }
  15122. }
  15123. return this._animatables;
  15124. };
  15125. Skeleton.prototype.clone = function (name, id) {
  15126. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15127. for (var index = 0; index < this.bones.length; index++) {
  15128. var source = this.bones[index];
  15129. var parentBone = null;
  15130. if (source.getParent()) {
  15131. var parentIndex = this.bones.indexOf(source.getParent());
  15132. parentBone = result.bones[parentIndex];
  15133. }
  15134. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15135. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15136. }
  15137. return result;
  15138. };
  15139. return Skeleton;
  15140. })();
  15141. BABYLON.Skeleton = Skeleton;
  15142. })(BABYLON || (BABYLON = {}));
  15143. //# sourceMappingURL=babylon.skeleton.js.map
  15144. var BABYLON;
  15145. (function (BABYLON) {
  15146. var PostProcess = (function () {
  15147. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15148. this.name = name;
  15149. this.width = -1;
  15150. this.height = -1;
  15151. this._reusable = false;
  15152. this._textures = new BABYLON.SmartArray(2);
  15153. this._currentRenderTextureInd = 0;
  15154. if (camera != null) {
  15155. this._camera = camera;
  15156. this._scene = camera.getScene();
  15157. camera.attachPostProcess(this);
  15158. this._engine = this._scene.getEngine();
  15159. } else {
  15160. this._engine = engine;
  15161. }
  15162. this._renderRatio = ratio;
  15163. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15164. this._reusable = reusable || false;
  15165. samplers = samplers || [];
  15166. samplers.push("textureSampler");
  15167. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15168. }
  15169. PostProcess.prototype.isReusable = function () {
  15170. return this._reusable;
  15171. };
  15172. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15173. camera = camera || this._camera;
  15174. var scene = camera.getScene();
  15175. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15176. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15177. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15178. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15179. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15180. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15181. if (this._textures.length > 0) {
  15182. for (var i = 0; i < this._textures.length; i++) {
  15183. this._engine._releaseTexture(this._textures.data[i]);
  15184. }
  15185. this._textures.reset();
  15186. }
  15187. this.width = desiredWidth;
  15188. this.height = desiredHeight;
  15189. 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 }));
  15190. if (this._reusable) {
  15191. 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 }));
  15192. }
  15193. if (this.onSizeChanged) {
  15194. this.onSizeChanged();
  15195. }
  15196. }
  15197. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15198. if (this.onActivate) {
  15199. this.onActivate(camera);
  15200. }
  15201. // Clear
  15202. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15203. if (this._reusable) {
  15204. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15205. }
  15206. };
  15207. PostProcess.prototype.apply = function () {
  15208. // Check
  15209. if (!this._effect.isReady())
  15210. return null;
  15211. // States
  15212. this._engine.enableEffect(this._effect);
  15213. this._engine.setState(false);
  15214. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15215. this._engine.setDepthBuffer(false);
  15216. this._engine.setDepthWrite(false);
  15217. // Texture
  15218. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15219. // Parameters
  15220. if (this.onApply) {
  15221. this.onApply(this._effect);
  15222. }
  15223. return this._effect;
  15224. };
  15225. PostProcess.prototype.dispose = function (camera) {
  15226. camera = camera || this._camera;
  15227. if (this._textures.length > 0) {
  15228. for (var i = 0; i < this._textures.length; i++) {
  15229. this._engine._releaseTexture(this._textures.data[i]);
  15230. }
  15231. this._textures.reset();
  15232. }
  15233. camera.detachPostProcess(this);
  15234. var index = camera._postProcesses.indexOf(this);
  15235. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15236. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15237. }
  15238. };
  15239. return PostProcess;
  15240. })();
  15241. BABYLON.PostProcess = PostProcess;
  15242. })(BABYLON || (BABYLON = {}));
  15243. //# sourceMappingURL=babylon.postProcess.js.map
  15244. var BABYLON;
  15245. (function (BABYLON) {
  15246. var PostProcessManager = (function () {
  15247. function PostProcessManager(scene) {
  15248. this._vertexDeclaration = [2];
  15249. this._vertexStrideSize = 2 * 4;
  15250. this._scene = scene;
  15251. // VBO
  15252. var vertices = [];
  15253. vertices.push(1, 1);
  15254. vertices.push(-1, 1);
  15255. vertices.push(-1, -1);
  15256. vertices.push(1, -1);
  15257. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15258. // Indices
  15259. var indices = [];
  15260. indices.push(0);
  15261. indices.push(1);
  15262. indices.push(2);
  15263. indices.push(0);
  15264. indices.push(2);
  15265. indices.push(3);
  15266. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15267. }
  15268. // Methods
  15269. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15270. var postProcesses = this._scene.activeCamera._postProcesses;
  15271. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15272. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15273. return false;
  15274. }
  15275. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15276. return true;
  15277. };
  15278. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15279. var postProcesses = this._scene.activeCamera._postProcesses;
  15280. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15281. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15282. return;
  15283. }
  15284. var engine = this._scene.getEngine();
  15285. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15286. if (index < postProcessesTakenIndices.length - 1) {
  15287. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15288. } else {
  15289. if (targetTexture) {
  15290. engine.bindFramebuffer(targetTexture);
  15291. } else {
  15292. engine.restoreDefaultFramebuffer();
  15293. }
  15294. }
  15295. if (doNotPresent) {
  15296. break;
  15297. }
  15298. var pp = postProcesses[postProcessesTakenIndices[index]];
  15299. var effect = pp.apply();
  15300. if (effect) {
  15301. if (pp.onBeforeRender) {
  15302. pp.onBeforeRender(effect);
  15303. }
  15304. // VBOs
  15305. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15306. // Draw order
  15307. engine.draw(true, 0, 6);
  15308. }
  15309. }
  15310. // Restore depth buffer
  15311. engine.setDepthBuffer(true);
  15312. engine.setDepthWrite(true);
  15313. };
  15314. PostProcessManager.prototype.dispose = function () {
  15315. if (this._vertexBuffer) {
  15316. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15317. this._vertexBuffer = null;
  15318. }
  15319. if (this._indexBuffer) {
  15320. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15321. this._indexBuffer = null;
  15322. }
  15323. };
  15324. return PostProcessManager;
  15325. })();
  15326. BABYLON.PostProcessManager = PostProcessManager;
  15327. })(BABYLON || (BABYLON = {}));
  15328. //# sourceMappingURL=babylon.postProcessManager.js.map
  15329. var BABYLON;
  15330. (function (BABYLON) {
  15331. var PassPostProcess = (function (_super) {
  15332. __extends(PassPostProcess, _super);
  15333. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15334. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15335. }
  15336. return PassPostProcess;
  15337. })(BABYLON.PostProcess);
  15338. BABYLON.PassPostProcess = PassPostProcess;
  15339. })(BABYLON || (BABYLON = {}));
  15340. //# sourceMappingURL=babylon.passPostProcess.js.map
  15341. var BABYLON;
  15342. (function (BABYLON) {
  15343. var BlurPostProcess = (function (_super) {
  15344. __extends(BlurPostProcess, _super);
  15345. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15346. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15347. var _this = this;
  15348. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15349. this.direction = direction;
  15350. this.blurWidth = blurWidth;
  15351. this.onApply = function (effect) {
  15352. effect.setFloat2("screenSize", _this.width, _this.height);
  15353. effect.setVector2("direction", _this.direction);
  15354. effect.setFloat("blurWidth", _this.blurWidth);
  15355. };
  15356. }
  15357. return BlurPostProcess;
  15358. })(BABYLON.PostProcess);
  15359. BABYLON.BlurPostProcess = BlurPostProcess;
  15360. })(BABYLON || (BABYLON = {}));
  15361. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15362. var BABYLON;
  15363. (function (BABYLON) {
  15364. var FilterPostProcess = (function (_super) {
  15365. __extends(FilterPostProcess, _super);
  15366. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15367. var _this = this;
  15368. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15369. this.kernelMatrix = kernelMatrix;
  15370. this.onApply = function (effect) {
  15371. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15372. };
  15373. }
  15374. return FilterPostProcess;
  15375. })(BABYLON.PostProcess);
  15376. BABYLON.FilterPostProcess = FilterPostProcess;
  15377. })(BABYLON || (BABYLON = {}));
  15378. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15379. var BABYLON;
  15380. (function (BABYLON) {
  15381. var RefractionPostProcess = (function (_super) {
  15382. __extends(RefractionPostProcess, _super);
  15383. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15384. var _this = this;
  15385. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15386. this.color = color;
  15387. this.depth = depth;
  15388. this.colorLevel = colorLevel;
  15389. this.onActivate = function (cam) {
  15390. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15391. };
  15392. this.onApply = function (effect) {
  15393. effect.setColor3("baseColor", _this.color);
  15394. effect.setFloat("depth", _this.depth);
  15395. effect.setFloat("colorLevel", _this.colorLevel);
  15396. effect.setTexture("refractionSampler", _this._refRexture);
  15397. };
  15398. }
  15399. // Methods
  15400. RefractionPostProcess.prototype.dispose = function (camera) {
  15401. if (this._refRexture) {
  15402. this._refRexture.dispose();
  15403. }
  15404. _super.prototype.dispose.call(this, camera);
  15405. };
  15406. return RefractionPostProcess;
  15407. })(BABYLON.PostProcess);
  15408. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15409. })(BABYLON || (BABYLON = {}));
  15410. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15411. var BABYLON;
  15412. (function (BABYLON) {
  15413. var BlackAndWhitePostProcess = (function (_super) {
  15414. __extends(BlackAndWhitePostProcess, _super);
  15415. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15416. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15417. }
  15418. return BlackAndWhitePostProcess;
  15419. })(BABYLON.PostProcess);
  15420. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15421. })(BABYLON || (BABYLON = {}));
  15422. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15423. var BABYLON;
  15424. (function (BABYLON) {
  15425. var ConvolutionPostProcess = (function (_super) {
  15426. __extends(ConvolutionPostProcess, _super);
  15427. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15428. var _this = this;
  15429. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15430. this.kernel = kernel;
  15431. this.onApply = function (effect) {
  15432. effect.setFloat2("screenSize", _this.width, _this.height);
  15433. effect.setArray("kernel", _this.kernel);
  15434. };
  15435. }
  15436. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15437. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15438. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15439. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15440. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15441. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15442. return ConvolutionPostProcess;
  15443. })(BABYLON.PostProcess);
  15444. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15445. })(BABYLON || (BABYLON = {}));
  15446. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15447. var BABYLON;
  15448. (function (BABYLON) {
  15449. var FxaaPostProcess = (function (_super) {
  15450. __extends(FxaaPostProcess, _super);
  15451. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15452. var _this = this;
  15453. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15454. this.onSizeChanged = function () {
  15455. _this.texelWidth = 1.0 / _this.width;
  15456. _this.texelHeight = 1.0 / _this.height;
  15457. };
  15458. this.onApply = function (effect) {
  15459. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15460. };
  15461. }
  15462. return FxaaPostProcess;
  15463. })(BABYLON.PostProcess);
  15464. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15465. })(BABYLON || (BABYLON = {}));
  15466. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15467. var BABYLON;
  15468. (function (BABYLON) {
  15469. var LensFlare = (function () {
  15470. function LensFlare(size, position, color, imgUrl, system) {
  15471. this.size = size;
  15472. this.position = position;
  15473. this.dispose = function () {
  15474. if (this.texture) {
  15475. this.texture.dispose();
  15476. }
  15477. // Remove from scene
  15478. var index = this._system.lensFlares.indexOf(this);
  15479. this._system.lensFlares.splice(index, 1);
  15480. };
  15481. this.color = color || new BABYLON.Color3(1, 1, 1);
  15482. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15483. this._system = system;
  15484. system.lensFlares.push(this);
  15485. }
  15486. return LensFlare;
  15487. })();
  15488. BABYLON.LensFlare = LensFlare;
  15489. })(BABYLON || (BABYLON = {}));
  15490. //# sourceMappingURL=babylon.lensFlare.js.map
  15491. var BABYLON;
  15492. (function (BABYLON) {
  15493. var LensFlareSystem = (function () {
  15494. function LensFlareSystem(name, emitter, scene) {
  15495. this.name = name;
  15496. this.lensFlares = new Array();
  15497. this.borderLimit = 300;
  15498. this._vertexDeclaration = [2];
  15499. this._vertexStrideSize = 2 * 4;
  15500. this._isEnabled = true;
  15501. this._scene = scene;
  15502. this._emitter = emitter;
  15503. scene.lensFlareSystems.push(this);
  15504. this.meshesSelectionPredicate = function (m) {
  15505. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15506. };
  15507. // VBO
  15508. var vertices = [];
  15509. vertices.push(1, 1);
  15510. vertices.push(-1, 1);
  15511. vertices.push(-1, -1);
  15512. vertices.push(1, -1);
  15513. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15514. // Indices
  15515. var indices = [];
  15516. indices.push(0);
  15517. indices.push(1);
  15518. indices.push(2);
  15519. indices.push(0);
  15520. indices.push(2);
  15521. indices.push(3);
  15522. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15523. // Effects
  15524. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15525. }
  15526. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15527. get: function () {
  15528. return this._isEnabled;
  15529. },
  15530. set: function (value) {
  15531. this._isEnabled = value;
  15532. },
  15533. enumerable: true,
  15534. configurable: true
  15535. });
  15536. LensFlareSystem.prototype.getScene = function () {
  15537. return this._scene;
  15538. };
  15539. LensFlareSystem.prototype.getEmitter = function () {
  15540. return this._emitter;
  15541. };
  15542. LensFlareSystem.prototype.getEmitterPosition = function () {
  15543. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15544. };
  15545. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15546. var position = this.getEmitterPosition();
  15547. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15548. this._positionX = position.x;
  15549. this._positionY = position.y;
  15550. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15551. if (position.z > 0) {
  15552. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15553. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15554. return true;
  15555. }
  15556. }
  15557. return false;
  15558. };
  15559. LensFlareSystem.prototype._isVisible = function () {
  15560. if (!this._isEnabled) {
  15561. return false;
  15562. }
  15563. var emitterPosition = this.getEmitterPosition();
  15564. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15565. var distance = direction.length();
  15566. direction.normalize();
  15567. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15568. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15569. return !pickInfo.hit || pickInfo.distance > distance;
  15570. };
  15571. LensFlareSystem.prototype.render = function () {
  15572. if (!this._effect.isReady())
  15573. return false;
  15574. var engine = this._scene.getEngine();
  15575. var viewport = this._scene.activeCamera.viewport;
  15576. var globalViewport = viewport.toGlobal(engine);
  15577. // Position
  15578. if (!this.computeEffectivePosition(globalViewport)) {
  15579. return false;
  15580. }
  15581. // Visibility
  15582. if (!this._isVisible()) {
  15583. return false;
  15584. }
  15585. // Intensity
  15586. var awayX;
  15587. var awayY;
  15588. if (this._positionX < this.borderLimit + globalViewport.x) {
  15589. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15590. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15591. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15592. } else {
  15593. awayX = 0;
  15594. }
  15595. if (this._positionY < this.borderLimit + globalViewport.y) {
  15596. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15597. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15598. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15599. } else {
  15600. awayY = 0;
  15601. }
  15602. var away = (awayX > awayY) ? awayX : awayY;
  15603. if (away > this.borderLimit) {
  15604. away = this.borderLimit;
  15605. }
  15606. var intensity = 1.0 - (away / this.borderLimit);
  15607. if (intensity < 0) {
  15608. return false;
  15609. }
  15610. if (intensity > 1.0) {
  15611. intensity = 1.0;
  15612. }
  15613. // Position
  15614. var centerX = globalViewport.x + globalViewport.width / 2;
  15615. var centerY = globalViewport.y + globalViewport.height / 2;
  15616. var distX = centerX - this._positionX;
  15617. var distY = centerY - this._positionY;
  15618. // Effects
  15619. engine.enableEffect(this._effect);
  15620. engine.setState(false);
  15621. engine.setDepthBuffer(false);
  15622. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15623. // VBOs
  15624. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15625. for (var index = 0; index < this.lensFlares.length; index++) {
  15626. var flare = this.lensFlares[index];
  15627. var x = centerX - (distX * flare.position);
  15628. var y = centerY - (distY * flare.position);
  15629. var cw = flare.size;
  15630. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15631. var cx = 2 * (x / globalViewport.width) - 1.0;
  15632. var cy = 1.0 - 2 * (y / globalViewport.height);
  15633. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15634. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15635. // Texture
  15636. this._effect.setTexture("textureSampler", flare.texture);
  15637. // Color
  15638. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15639. // Draw order
  15640. engine.draw(true, 0, 6);
  15641. }
  15642. engine.setDepthBuffer(true);
  15643. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15644. return true;
  15645. };
  15646. LensFlareSystem.prototype.dispose = function () {
  15647. if (this._vertexBuffer) {
  15648. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15649. this._vertexBuffer = null;
  15650. }
  15651. if (this._indexBuffer) {
  15652. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15653. this._indexBuffer = null;
  15654. }
  15655. while (this.lensFlares.length) {
  15656. this.lensFlares[0].dispose();
  15657. }
  15658. // Remove from scene
  15659. var index = this._scene.lensFlareSystems.indexOf(this);
  15660. this._scene.lensFlareSystems.splice(index, 1);
  15661. };
  15662. return LensFlareSystem;
  15663. })();
  15664. BABYLON.LensFlareSystem = LensFlareSystem;
  15665. })(BABYLON || (BABYLON = {}));
  15666. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15667. var BABYLON;
  15668. (function (BABYLON) {
  15669. var IntersectionInfo = (function () {
  15670. function IntersectionInfo(bu, bv, distance) {
  15671. this.bu = bu;
  15672. this.bv = bv;
  15673. this.distance = distance;
  15674. this.faceId = 0;
  15675. }
  15676. return IntersectionInfo;
  15677. })();
  15678. BABYLON.IntersectionInfo = IntersectionInfo;
  15679. var PickingInfo = (function () {
  15680. function PickingInfo() {
  15681. this.hit = false;
  15682. this.distance = 0;
  15683. this.pickedPoint = null;
  15684. this.pickedMesh = null;
  15685. this.bu = 0;
  15686. this.bv = 0;
  15687. this.faceId = -1;
  15688. }
  15689. // Methods
  15690. PickingInfo.prototype.getNormal = function () {
  15691. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15692. return null;
  15693. }
  15694. var indices = this.pickedMesh.getIndices();
  15695. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15696. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15697. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15698. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15699. normal0 = normal0.scale(this.bu);
  15700. normal1 = normal1.scale(this.bv);
  15701. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15702. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15703. };
  15704. PickingInfo.prototype.getTextureCoordinates = function () {
  15705. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15706. return null;
  15707. }
  15708. var indices = this.pickedMesh.getIndices();
  15709. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15710. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15711. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15712. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15713. uv0 = uv0.scale(this.bu);
  15714. uv1 = uv1.scale(this.bv);
  15715. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15716. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15717. };
  15718. return PickingInfo;
  15719. })();
  15720. BABYLON.PickingInfo = PickingInfo;
  15721. })(BABYLON || (BABYLON = {}));
  15722. //# sourceMappingURL=babylon.pickingInfo.js.map
  15723. var BABYLON;
  15724. (function (BABYLON) {
  15725. var FilesInput = (function () {
  15726. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15727. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15728. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15729. this.engine = p_engine;
  15730. this.canvas = p_canvas;
  15731. this.currentScene = p_scene;
  15732. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15733. this.progressCallback = p_progressCallback;
  15734. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15735. this.textureLoadingCallback = p_textureLoadingCallback;
  15736. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15737. }
  15738. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15739. var _this = this;
  15740. if (p_elementToMonitor) {
  15741. this.elementToMonitor = p_elementToMonitor;
  15742. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15743. _this.drag(e);
  15744. }, false);
  15745. this.elementToMonitor.addEventListener("dragover", function (e) {
  15746. _this.drag(e);
  15747. }, false);
  15748. this.elementToMonitor.addEventListener("drop", function (e) {
  15749. _this.drop(e);
  15750. }, false);
  15751. }
  15752. };
  15753. FilesInput.prototype.renderFunction = function () {
  15754. if (this.additionnalRenderLoopLogicCallback) {
  15755. this.additionnalRenderLoopLogicCallback();
  15756. }
  15757. if (this.currentScene) {
  15758. if (this.textureLoadingCallback) {
  15759. var remaining = this.currentScene.getWaitingItemsCount();
  15760. if (remaining > 0) {
  15761. this.textureLoadingCallback(remaining);
  15762. }
  15763. }
  15764. this.currentScene.render();
  15765. }
  15766. };
  15767. FilesInput.prototype.drag = function (e) {
  15768. e.stopPropagation();
  15769. e.preventDefault();
  15770. };
  15771. FilesInput.prototype.drop = function (eventDrop) {
  15772. eventDrop.stopPropagation();
  15773. eventDrop.preventDefault();
  15774. this.loadFiles(eventDrop);
  15775. };
  15776. FilesInput.prototype.loadFiles = function (event) {
  15777. var _this = this;
  15778. var that = this;
  15779. if (this.startingProcessingFilesCallback)
  15780. this.startingProcessingFilesCallback();
  15781. var sceneFileToLoad;
  15782. var filesToLoad;
  15783. // Handling data transfer via drag'n'drop
  15784. if (event && event.dataTransfer && event.dataTransfer.files) {
  15785. filesToLoad = event.dataTransfer.files;
  15786. }
  15787. // Handling files from input files
  15788. if (event && event.target && event.target.files) {
  15789. filesToLoad = event.target.files;
  15790. }
  15791. if (filesToLoad && filesToLoad.length > 0) {
  15792. for (var i = 0; i < filesToLoad.length; i++) {
  15793. switch (filesToLoad[i].type) {
  15794. case "image/jpeg":
  15795. case "image/png":
  15796. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15797. break;
  15798. case "image/targa":
  15799. case "image/vnd.ms-dds":
  15800. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15801. break;
  15802. default:
  15803. 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) {
  15804. sceneFileToLoad = filesToLoad[i];
  15805. }
  15806. break;
  15807. }
  15808. }
  15809. // If a ".babylon" file has been provided
  15810. if (sceneFileToLoad) {
  15811. if (this.currentScene) {
  15812. this.engine.stopRenderLoop();
  15813. this.currentScene.dispose();
  15814. }
  15815. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15816. that.currentScene = newScene;
  15817. // Wait for textures and shaders to be ready
  15818. that.currentScene.executeWhenReady(function () {
  15819. // Attach camera to canvas inputs
  15820. if (that.currentScene.activeCamera) {
  15821. that.currentScene.activeCamera.attachControl(that.canvas);
  15822. }
  15823. if (that.sceneLoadedCallback) {
  15824. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15825. }
  15826. that.engine.runRenderLoop(function () {
  15827. that.renderFunction();
  15828. });
  15829. });
  15830. }, function (progress) {
  15831. if (_this.progressCallback) {
  15832. _this.progressCallback(progress);
  15833. }
  15834. });
  15835. } else {
  15836. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15837. }
  15838. }
  15839. };
  15840. FilesInput.FilesTextures = new Array();
  15841. FilesInput.FilesToLoad = new Array();
  15842. return FilesInput;
  15843. })();
  15844. BABYLON.FilesInput = FilesInput;
  15845. })(BABYLON || (BABYLON = {}));
  15846. //# sourceMappingURL=babylon.filesInput.js.map
  15847. var BABYLON;
  15848. (function (BABYLON) {
  15849. var OimoJSPlugin = (function () {
  15850. function OimoJSPlugin() {
  15851. this._registeredMeshes = [];
  15852. /**
  15853. * Update the body position according to the mesh position
  15854. * @param mesh
  15855. */
  15856. this.updateBodyPosition = function (mesh) {
  15857. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15858. var registeredMesh = this._registeredMeshes[index];
  15859. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15860. var body = registeredMesh.body.body;
  15861. mesh.computeWorldMatrix(true);
  15862. var center = mesh.getBoundingInfo().boundingBox.center;
  15863. body.setPosition(center.x, center.y, center.z);
  15864. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15865. return;
  15866. }
  15867. // Case where the parent has been updated
  15868. if (registeredMesh.mesh.parent === mesh) {
  15869. mesh.computeWorldMatrix(true);
  15870. registeredMesh.mesh.computeWorldMatrix(true);
  15871. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15872. var absoluteRotation = mesh.rotation;
  15873. body = registeredMesh.body.body;
  15874. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15875. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15876. return;
  15877. }
  15878. }
  15879. };
  15880. }
  15881. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15882. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15883. };
  15884. OimoJSPlugin.prototype.initialize = function (iterations) {
  15885. this._world = new OIMO.World();
  15886. this._world.clear();
  15887. };
  15888. OimoJSPlugin.prototype.setGravity = function (gravity) {
  15889. this._world.gravity = gravity;
  15890. };
  15891. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15892. var body = null;
  15893. this.unregisterMesh(mesh);
  15894. mesh.computeWorldMatrix(true);
  15895. switch (impostor) {
  15896. case BABYLON.PhysicsEngine.SphereImpostor:
  15897. var bbox = mesh.getBoundingInfo().boundingBox;
  15898. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15899. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15900. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15901. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15902. // The delta between the mesh position and the mesh bounding box center
  15903. var deltaPosition = mesh.position.subtract(bbox.center);
  15904. body = new OIMO.Body({
  15905. type: 'sphere',
  15906. size: [size],
  15907. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15908. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15909. move: options.mass != 0,
  15910. config: [options.mass, options.friction, options.restitution],
  15911. world: this._world
  15912. });
  15913. this._registeredMeshes.push({
  15914. mesh: mesh,
  15915. body: body,
  15916. delta: deltaPosition
  15917. });
  15918. break;
  15919. case BABYLON.PhysicsEngine.PlaneImpostor:
  15920. case BABYLON.PhysicsEngine.BoxImpostor:
  15921. bbox = mesh.getBoundingInfo().boundingBox;
  15922. var min = bbox.minimumWorld;
  15923. var max = bbox.maximumWorld;
  15924. var box = max.subtract(min);
  15925. var sizeX = this._checkWithEpsilon(box.x);
  15926. var sizeY = this._checkWithEpsilon(box.y);
  15927. var sizeZ = this._checkWithEpsilon(box.z);
  15928. // The delta between the mesh position and the mesh boudning box center
  15929. var deltaPosition = mesh.position.subtract(bbox.center);
  15930. body = new OIMO.Body({
  15931. type: 'box',
  15932. size: [sizeX, sizeY, sizeZ],
  15933. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15934. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15935. move: options.mass != 0,
  15936. config: [options.mass, options.friction, options.restitution],
  15937. world: this._world
  15938. });
  15939. this._registeredMeshes.push({
  15940. mesh: mesh,
  15941. body: body,
  15942. delta: deltaPosition
  15943. });
  15944. break;
  15945. }
  15946. return body;
  15947. };
  15948. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  15949. var types = [], sizes = [], positions = [], rotations = [];
  15950. var initialMesh = parts[0].mesh;
  15951. for (var index = 0; index < parts.length; index++) {
  15952. var part = parts[index];
  15953. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  15954. types.push(bodyParameters.type);
  15955. sizes.push.apply(sizes, bodyParameters.size);
  15956. positions.push.apply(positions, bodyParameters.pos);
  15957. rotations.push.apply(rotations, bodyParameters.rot);
  15958. }
  15959. var body = new OIMO.Body({
  15960. type: types,
  15961. size: sizes,
  15962. pos: positions,
  15963. rot: rotations,
  15964. move: options.mass != 0,
  15965. config: [options.mass, options.friction, options.restitution],
  15966. world: this._world
  15967. });
  15968. this._registeredMeshes.push({
  15969. mesh: initialMesh,
  15970. body: body
  15971. });
  15972. return body;
  15973. };
  15974. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  15975. var bodyParameters = null;
  15976. var mesh = part.mesh;
  15977. switch (part.impostor) {
  15978. case BABYLON.PhysicsEngine.SphereImpostor:
  15979. var bbox = mesh.getBoundingInfo().boundingBox;
  15980. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15981. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15982. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15983. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15984. bodyParameters = {
  15985. type: 'sphere',
  15986. /* bug with oimo : sphere needs 3 sizes in this case */
  15987. size: [size, -1, -1],
  15988. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  15989. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15990. };
  15991. break;
  15992. case BABYLON.PhysicsEngine.PlaneImpostor:
  15993. case BABYLON.PhysicsEngine.BoxImpostor:
  15994. bbox = mesh.getBoundingInfo().boundingBox;
  15995. var min = bbox.minimumWorld;
  15996. var max = bbox.maximumWorld;
  15997. var box = max.subtract(min);
  15998. var sizeX = this._checkWithEpsilon(box.x);
  15999. var sizeY = this._checkWithEpsilon(box.y);
  16000. var sizeZ = this._checkWithEpsilon(box.z);
  16001. var relativePosition = mesh.position;
  16002. bodyParameters = {
  16003. type: 'box',
  16004. size: [sizeX, sizeY, sizeZ],
  16005. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16006. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16007. };
  16008. break;
  16009. }
  16010. return bodyParameters;
  16011. };
  16012. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16013. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16014. var registeredMesh = this._registeredMeshes[index];
  16015. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16016. if (registeredMesh.body) {
  16017. this._world.removeRigidBody(registeredMesh.body.body);
  16018. this._unbindBody(registeredMesh.body);
  16019. }
  16020. this._registeredMeshes.splice(index, 1);
  16021. return;
  16022. }
  16023. }
  16024. };
  16025. OimoJSPlugin.prototype._unbindBody = function (body) {
  16026. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16027. var registeredMesh = this._registeredMeshes[index];
  16028. if (registeredMesh.body === body) {
  16029. registeredMesh.body = null;
  16030. }
  16031. }
  16032. };
  16033. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16034. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16035. var registeredMesh = this._registeredMeshes[index];
  16036. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16037. // Get object mass to have a behaviour similar to cannon.js
  16038. var mass = registeredMesh.body.body.massInfo.mass;
  16039. // The force is scaled with the mass of object
  16040. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16041. return;
  16042. }
  16043. }
  16044. };
  16045. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16046. var body1 = null, body2 = null;
  16047. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16048. var registeredMesh = this._registeredMeshes[index];
  16049. if (registeredMesh.mesh === mesh1) {
  16050. body1 = registeredMesh.body.body;
  16051. } else if (registeredMesh.mesh === mesh2) {
  16052. body2 = registeredMesh.body.body;
  16053. }
  16054. }
  16055. if (!body1 || !body2) {
  16056. return false;
  16057. }
  16058. if (!options) {
  16059. options = {};
  16060. }
  16061. new OIMO.Link({
  16062. type: options.type,
  16063. body1: body1,
  16064. body2: body2,
  16065. min: options.min,
  16066. max: options.max,
  16067. axe1: options.axe1,
  16068. axe2: options.axe2,
  16069. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16070. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16071. collision: options.collision,
  16072. spring: options.spring,
  16073. world: this._world
  16074. });
  16075. return true;
  16076. };
  16077. OimoJSPlugin.prototype.dispose = function () {
  16078. this._world.clear();
  16079. while (this._registeredMeshes.length) {
  16080. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16081. }
  16082. };
  16083. OimoJSPlugin.prototype.isSupported = function () {
  16084. return OIMO !== undefined;
  16085. };
  16086. OimoJSPlugin.prototype._getLastShape = function (body) {
  16087. var lastShape = body.shapes;
  16088. while (lastShape.next) {
  16089. lastShape = lastShape.next;
  16090. }
  16091. return lastShape;
  16092. };
  16093. OimoJSPlugin.prototype.runOneStep = function (time) {
  16094. this._world.step();
  16095. // Update the position of all registered meshes
  16096. var i = this._registeredMeshes.length;
  16097. var m;
  16098. while (i--) {
  16099. var body = this._registeredMeshes[i].body.body;
  16100. var mesh = this._registeredMeshes[i].mesh;
  16101. var delta = this._registeredMeshes[i].delta;
  16102. if (!body.sleeping) {
  16103. if (body.shapes.next) {
  16104. var parentShape = this._getLastShape(body);
  16105. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16106. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16107. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16108. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16109. if (!mesh.rotationQuaternion) {
  16110. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16111. }
  16112. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16113. mesh.computeWorldMatrix();
  16114. } else {
  16115. m = body.getMatrix();
  16116. mtx = BABYLON.Matrix.FromArray(m);
  16117. // Body position
  16118. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16119. if (!delta) {
  16120. mesh.position.x = bodyX;
  16121. mesh.position.y = bodyY;
  16122. mesh.position.z = bodyZ;
  16123. } else {
  16124. mesh.position.x = bodyX + delta.x;
  16125. mesh.position.y = bodyY + delta.y;
  16126. mesh.position.z = bodyZ + delta.z;
  16127. }
  16128. if (!mesh.rotationQuaternion) {
  16129. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16130. }
  16131. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16132. mesh.computeWorldMatrix();
  16133. }
  16134. }
  16135. }
  16136. };
  16137. return OimoJSPlugin;
  16138. })();
  16139. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16140. })(BABYLON || (BABYLON = {}));
  16141. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16142. var BABYLON;
  16143. (function (BABYLON) {
  16144. var PhysicsEngine = (function () {
  16145. function PhysicsEngine(plugin) {
  16146. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16147. }
  16148. PhysicsEngine.prototype._initialize = function (gravity) {
  16149. this._currentPlugin.initialize();
  16150. this._setGravity(gravity);
  16151. };
  16152. PhysicsEngine.prototype._runOneStep = function (delta) {
  16153. if (delta > 0.1) {
  16154. delta = 0.1;
  16155. } else if (delta <= 0) {
  16156. delta = 1.0 / 60.0;
  16157. }
  16158. this._currentPlugin.runOneStep(delta);
  16159. };
  16160. PhysicsEngine.prototype._setGravity = function (gravity) {
  16161. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16162. this._currentPlugin.setGravity(this.gravity);
  16163. };
  16164. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16165. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16166. };
  16167. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16168. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16169. };
  16170. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16171. this._currentPlugin.unregisterMesh(mesh);
  16172. };
  16173. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16174. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16175. };
  16176. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16177. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16178. };
  16179. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16180. this._currentPlugin.updateBodyPosition(mesh);
  16181. };
  16182. PhysicsEngine.prototype.dispose = function () {
  16183. this._currentPlugin.dispose();
  16184. };
  16185. PhysicsEngine.prototype.isSupported = function () {
  16186. return this._currentPlugin.isSupported();
  16187. };
  16188. PhysicsEngine.NoImpostor = 0;
  16189. PhysicsEngine.SphereImpostor = 1;
  16190. PhysicsEngine.BoxImpostor = 2;
  16191. PhysicsEngine.PlaneImpostor = 3;
  16192. PhysicsEngine.MeshImpostor = 4;
  16193. PhysicsEngine.CapsuleImpostor = 5;
  16194. PhysicsEngine.ConeImpostor = 6;
  16195. PhysicsEngine.CylinderImpostor = 7;
  16196. PhysicsEngine.ConvexHullImpostor = 8;
  16197. PhysicsEngine.Epsilon = 0.001;
  16198. return PhysicsEngine;
  16199. })();
  16200. BABYLON.PhysicsEngine = PhysicsEngine;
  16201. })(BABYLON || (BABYLON = {}));
  16202. //# sourceMappingURL=babylon.physicsEngine.js.map
  16203. var BABYLON;
  16204. (function (BABYLON) {
  16205. var serializeLight = function (light) {
  16206. var serializationObject = {};
  16207. serializationObject.name = light.name;
  16208. serializationObject.id = light.id;
  16209. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16210. if (light instanceof BABYLON.PointLight) {
  16211. serializationObject.type = 0;
  16212. serializationObject.position = light.position.asArray();
  16213. } else if (light instanceof BABYLON.DirectionalLight) {
  16214. serializationObject.type = 1;
  16215. var directionalLight = light;
  16216. serializationObject.position = directionalLight.position.asArray();
  16217. serializationObject.direction = directionalLight.direction.asArray();
  16218. } else if (light instanceof BABYLON.SpotLight) {
  16219. serializationObject.type = 2;
  16220. var spotLight = light;
  16221. serializationObject.position = spotLight.position.asArray();
  16222. serializationObject.direction = spotLight.position.asArray();
  16223. serializationObject.angle = spotLight.angle;
  16224. serializationObject.exponent = spotLight.exponent;
  16225. } else if (light instanceof BABYLON.HemisphericLight) {
  16226. serializationObject.type = 3;
  16227. var hemisphericLight = light;
  16228. serializationObject.direction = hemisphericLight.direction.asArray();
  16229. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16230. }
  16231. if (light.intensity) {
  16232. serializationObject.intensity = light.intensity;
  16233. }
  16234. serializationObject.range = light.range;
  16235. serializationObject.diffuse = light.diffuse.asArray();
  16236. serializationObject.specular = light.specular.asArray();
  16237. return serializationObject;
  16238. };
  16239. var serializeFresnelParameter = function (fresnelParameter) {
  16240. var serializationObject = {};
  16241. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16242. serializationObject.leftColor = fresnelParameter.leftColor;
  16243. serializationObject.rightColor = fresnelParameter.rightColor;
  16244. serializationObject.bias = fresnelParameter.bias;
  16245. serializationObject.power = fresnelParameter.power;
  16246. return serializationObject;
  16247. };
  16248. var serializeCamera = function (camera) {
  16249. var serializationObject = {};
  16250. serializationObject.name = camera.name;
  16251. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16252. serializationObject.id = camera.id;
  16253. serializationObject.position = camera.position.asArray();
  16254. // Parent
  16255. if (camera.parent) {
  16256. serializationObject.parentId = camera.parent.id;
  16257. }
  16258. // Target
  16259. serializationObject.rotation = camera.rotation.asArray();
  16260. // Locked target
  16261. if (camera.lockedTarget && camera.lockedTarget.id) {
  16262. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16263. }
  16264. serializationObject.fov = camera.fov;
  16265. serializationObject.minZ = camera.minZ;
  16266. serializationObject.maxZ = camera.maxZ;
  16267. serializationObject.speed = camera.speed;
  16268. serializationObject.inertia = camera.inertia;
  16269. serializationObject.checkCollisions = camera.checkCollisions;
  16270. serializationObject.applyGravity = camera.applyGravity;
  16271. if (camera.ellipsoid) {
  16272. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16273. }
  16274. // Animations
  16275. appendAnimations(camera, serializationObject);
  16276. // Layer mask
  16277. serializationObject.layerMask = camera.layerMask;
  16278. return serializationObject;
  16279. };
  16280. var appendAnimations = function (source, destination) {
  16281. if (source.animations) {
  16282. destination.animations = [];
  16283. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16284. var animation = source.animations[animationIndex];
  16285. destination.animations.push(serializeAnimation(animation));
  16286. }
  16287. }
  16288. };
  16289. var serializeAnimation = function (animation) {
  16290. var serializationObject = {};
  16291. serializationObject.name = animation.name;
  16292. serializationObject.property = animation.targetProperty;
  16293. serializationObject.framePerSecond = animation.framePerSecond;
  16294. serializationObject.dataType = animation.dataType;
  16295. serializationObject.loopBehavior = animation.loopMode;
  16296. var dataType = animation.dataType;
  16297. serializationObject.keys = [];
  16298. var keys = animation.getKeys();
  16299. for (var index = 0; index < keys.length; index++) {
  16300. var animationKey = keys[index];
  16301. var key = {};
  16302. key.frame = animationKey.frame;
  16303. switch (dataType) {
  16304. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16305. key.values = [animationKey.value];
  16306. break;
  16307. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16308. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16309. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16310. key.values = animationKey.value.asArray();
  16311. break;
  16312. }
  16313. serializationObject.keys.push(key);
  16314. }
  16315. return serializationObject;
  16316. };
  16317. var serializeMultiMaterial = function (material) {
  16318. var serializationObject = {};
  16319. serializationObject.name = material.name;
  16320. serializationObject.id = material.id;
  16321. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16322. serializationObject.materials = [];
  16323. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16324. var subMat = material.subMaterials[matIndex];
  16325. if (subMat) {
  16326. serializationObject.materials.push(subMat.id);
  16327. } else {
  16328. serializationObject.materials.push(null);
  16329. }
  16330. }
  16331. return serializationObject;
  16332. };
  16333. var serializeMaterial = function (material) {
  16334. var serializationObject = {};
  16335. serializationObject.name = material.name;
  16336. serializationObject.ambient = material.ambientColor.asArray();
  16337. serializationObject.diffuse = material.diffuseColor.asArray();
  16338. serializationObject.specular = material.specularColor.asArray();
  16339. serializationObject.specularPower = material.specularPower;
  16340. serializationObject.emissive = material.emissiveColor.asArray();
  16341. serializationObject.alpha = material.alpha;
  16342. serializationObject.id = material.id;
  16343. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16344. serializationObject.backFaceCulling = material.backFaceCulling;
  16345. if (material.diffuseTexture) {
  16346. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16347. }
  16348. if (material.diffuseFresnelParameters) {
  16349. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16350. }
  16351. if (material.ambientTexture) {
  16352. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16353. }
  16354. if (material.opacityTexture) {
  16355. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16356. }
  16357. if (material.opacityFresnelParameters) {
  16358. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16359. }
  16360. if (material.reflectionTexture) {
  16361. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16362. }
  16363. if (material.reflectionFresnelParameters) {
  16364. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16365. }
  16366. if (material.emissiveTexture) {
  16367. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16368. }
  16369. if (material.emissiveFresnelParameters) {
  16370. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16371. }
  16372. if (material.specularTexture) {
  16373. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16374. }
  16375. if (material.bumpTexture) {
  16376. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16377. }
  16378. return serializationObject;
  16379. };
  16380. var serializeTexture = function (texture) {
  16381. var serializationObject = {};
  16382. if (!texture.name) {
  16383. return null;
  16384. }
  16385. if (texture instanceof BABYLON.CubeTexture) {
  16386. serializationObject.name = texture.name;
  16387. serializationObject.hasAlpha = texture.hasAlpha;
  16388. serializationObject.level = texture.level;
  16389. serializationObject.coordinatesMode = texture.coordinatesMode;
  16390. return serializationObject;
  16391. }
  16392. if (texture instanceof BABYLON.MirrorTexture) {
  16393. var mirrorTexture = texture;
  16394. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16395. serializationObject.renderList = [];
  16396. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16397. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16398. }
  16399. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16400. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16401. var renderTargetTexture = texture;
  16402. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16403. serializationObject.renderList = [];
  16404. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16405. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16406. }
  16407. }
  16408. var regularTexture = texture;
  16409. serializationObject.name = texture.name;
  16410. serializationObject.hasAlpha = texture.hasAlpha;
  16411. serializationObject.level = texture.level;
  16412. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16413. serializationObject.coordinatesMode = texture.coordinatesMode;
  16414. serializationObject.uOffset = regularTexture.uOffset;
  16415. serializationObject.vOffset = regularTexture.vOffset;
  16416. serializationObject.uScale = regularTexture.uScale;
  16417. serializationObject.vScale = regularTexture.vScale;
  16418. serializationObject.uAng = regularTexture.uAng;
  16419. serializationObject.vAng = regularTexture.vAng;
  16420. serializationObject.wAng = regularTexture.wAng;
  16421. serializationObject.wrapU = texture.wrapU;
  16422. serializationObject.wrapV = texture.wrapV;
  16423. // Animations
  16424. appendAnimations(texture, serializationObject);
  16425. return serializationObject;
  16426. };
  16427. var serializeSkeleton = function (skeleton) {
  16428. var serializationObject = {};
  16429. serializationObject.name = skeleton.name;
  16430. serializationObject.id = skeleton.id;
  16431. serializationObject.bones = [];
  16432. for (var index = 0; index < skeleton.bones.length; index++) {
  16433. var bone = skeleton.bones[index];
  16434. var serializedBone = {
  16435. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16436. name: bone.name,
  16437. matrix: bone.getLocalMatrix().toArray()
  16438. };
  16439. serializationObject.bones.push(serializedBone);
  16440. if (bone.animations && bone.animations.length > 0) {
  16441. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16442. }
  16443. }
  16444. return serializationObject;
  16445. };
  16446. var serializeParticleSystem = function (particleSystem) {
  16447. var serializationObject = {};
  16448. serializationObject.emitterId = particleSystem.emitter.id;
  16449. serializationObject.capacity = particleSystem.getCapacity();
  16450. if (particleSystem.particleTexture) {
  16451. serializationObject.textureName = particleSystem.particleTexture.name;
  16452. }
  16453. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16454. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16455. serializationObject.minSize = particleSystem.minSize;
  16456. serializationObject.maxSize = particleSystem.maxSize;
  16457. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16458. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16459. serializationObject.emitRate = particleSystem.emitRate;
  16460. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16461. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16462. serializationObject.gravity = particleSystem.gravity.asArray();
  16463. serializationObject.direction1 = particleSystem.direction1.asArray();
  16464. serializationObject.direction2 = particleSystem.direction2.asArray();
  16465. serializationObject.color1 = particleSystem.color1.asArray();
  16466. serializationObject.color2 = particleSystem.color2.asArray();
  16467. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16468. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16469. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16470. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16471. serializationObject.blendMode = particleSystem.blendMode;
  16472. return serializationObject;
  16473. };
  16474. var serializeLensFlareSystem = function (lensFlareSystem) {
  16475. var serializationObject = {};
  16476. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16477. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16478. serializationObject.flares = [];
  16479. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16480. var flare = lensFlareSystem.lensFlares[index];
  16481. serializationObject.flares.push({
  16482. size: flare.size,
  16483. position: flare.position,
  16484. color: flare.color.asArray(),
  16485. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16486. });
  16487. }
  16488. return serializationObject;
  16489. };
  16490. var serializeShadowGenerator = function (light) {
  16491. var serializationObject = {};
  16492. var shadowGenerator = light.getShadowGenerator();
  16493. serializationObject.lightId = light.id;
  16494. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16495. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16496. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16497. serializationObject.renderList = [];
  16498. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16499. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16500. serializationObject.renderList.push(mesh.id);
  16501. }
  16502. return serializationObject;
  16503. };
  16504. var serializedGeometries = [];
  16505. var serializeGeometry = function (geometry, serializationGeometries) {
  16506. if (serializedGeometries[geometry.id]) {
  16507. return;
  16508. }
  16509. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16510. serializationGeometries.boxes.push(serializeBox(geometry));
  16511. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16512. serializationGeometries.spheres.push(serializeSphere(geometry));
  16513. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16514. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16515. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16516. serializationGeometries.toruses.push(serializeTorus(geometry));
  16517. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16518. serializationGeometries.grounds.push(serializeGround(geometry));
  16519. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16520. serializationGeometries.planes.push(serializePlane(geometry));
  16521. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16522. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16523. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16524. throw new Error("Unknow primitive type");
  16525. } else {
  16526. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16527. }
  16528. serializedGeometries[geometry.id] = true;
  16529. };
  16530. var serializeGeometryBase = function (geometry) {
  16531. var serializationObject = {};
  16532. serializationObject.id = geometry.id;
  16533. if (BABYLON.Tags.HasTags(geometry)) {
  16534. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16535. }
  16536. return serializationObject;
  16537. };
  16538. var serializeVertexData = function (vertexData) {
  16539. var serializationObject = serializeGeometryBase(vertexData);
  16540. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16541. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16542. }
  16543. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16544. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16545. }
  16546. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16547. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16548. }
  16549. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16550. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16551. }
  16552. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16553. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16554. }
  16555. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16556. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16557. serializationObject.matricesIndices._isExpanded = true;
  16558. }
  16559. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16560. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16561. }
  16562. serializationObject.indices = vertexData.getIndices();
  16563. return serializationObject;
  16564. };
  16565. var serializePrimitive = function (primitive) {
  16566. var serializationObject = serializeGeometryBase(primitive);
  16567. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16568. return serializationObject;
  16569. };
  16570. var serializeBox = function (box) {
  16571. var serializationObject = serializePrimitive(box);
  16572. serializationObject.size = box.size;
  16573. return serializationObject;
  16574. };
  16575. var serializeSphere = function (sphere) {
  16576. var serializationObject = serializePrimitive(sphere);
  16577. serializationObject.segments = sphere.segments;
  16578. serializationObject.diameter = sphere.diameter;
  16579. return serializationObject;
  16580. };
  16581. var serializeCylinder = function (cylinder) {
  16582. var serializationObject = serializePrimitive(cylinder);
  16583. serializationObject.height = cylinder.height;
  16584. serializationObject.diameterTop = cylinder.diameterTop;
  16585. serializationObject.diameterBottom = cylinder.diameterBottom;
  16586. serializationObject.tessellation = cylinder.tessellation;
  16587. return serializationObject;
  16588. };
  16589. var serializeTorus = function (torus) {
  16590. var serializationObject = serializePrimitive(torus);
  16591. serializationObject.diameter = torus.diameter;
  16592. serializationObject.thickness = torus.thickness;
  16593. serializationObject.tessellation = torus.tessellation;
  16594. return serializationObject;
  16595. };
  16596. var serializeGround = function (ground) {
  16597. var serializationObject = serializePrimitive(ground);
  16598. serializationObject.width = ground.width;
  16599. serializationObject.height = ground.height;
  16600. serializationObject.subdivisions = ground.subdivisions;
  16601. return serializationObject;
  16602. };
  16603. var serializePlane = function (plane) {
  16604. var serializationObject = serializePrimitive(plane);
  16605. serializationObject.size = plane.size;
  16606. return serializationObject;
  16607. };
  16608. var serializeTorusKnot = function (torusKnot) {
  16609. var serializationObject = serializePrimitive(torusKnot);
  16610. serializationObject.radius = torusKnot.radius;
  16611. serializationObject.tube = torusKnot.tube;
  16612. serializationObject.radialSegments = torusKnot.radialSegments;
  16613. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16614. serializationObject.p = torusKnot.p;
  16615. serializationObject.q = torusKnot.q;
  16616. return serializationObject;
  16617. };
  16618. var serializeMesh = function (mesh, serializationScene) {
  16619. var serializationObject = {};
  16620. serializationObject.name = mesh.name;
  16621. serializationObject.id = mesh.id;
  16622. if (BABYLON.Tags.HasTags(mesh)) {
  16623. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16624. }
  16625. serializationObject.position = mesh.position.asArray();
  16626. if (mesh.rotationQuaternion) {
  16627. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16628. } else if (mesh.rotation) {
  16629. serializationObject.rotation = mesh.rotation.asArray();
  16630. }
  16631. serializationObject.scaling = mesh.scaling.asArray();
  16632. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16633. serializationObject.isEnabled = mesh.isEnabled();
  16634. serializationObject.isVisible = mesh.isVisible;
  16635. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16636. serializationObject.pickable = mesh.isPickable;
  16637. serializationObject.receiveShadows = mesh.receiveShadows;
  16638. serializationObject.billboardMode = mesh.billboardMode;
  16639. serializationObject.visibility = mesh.visibility;
  16640. serializationObject.checkCollisions = mesh.checkCollisions;
  16641. // Parent
  16642. if (mesh.parent) {
  16643. serializationObject.parentId = mesh.parent.id;
  16644. }
  16645. // Geometry
  16646. var geometry = mesh._geometry;
  16647. if (geometry) {
  16648. var geometryId = geometry.id;
  16649. serializationObject.geometryId = geometryId;
  16650. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16651. // 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
  16652. serializeGeometry(geometry, serializationScene.geometries);
  16653. }
  16654. // SubMeshes
  16655. serializationObject.subMeshes = [];
  16656. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16657. var subMesh = mesh.subMeshes[subIndex];
  16658. serializationObject.subMeshes.push({
  16659. materialIndex: subMesh.materialIndex,
  16660. verticesStart: subMesh.verticesStart,
  16661. verticesCount: subMesh.verticesCount,
  16662. indexStart: subMesh.indexStart,
  16663. indexCount: subMesh.indexCount
  16664. });
  16665. }
  16666. }
  16667. // Material
  16668. if (mesh.material) {
  16669. serializationObject.materialId = mesh.material.id;
  16670. } else {
  16671. mesh.material = null;
  16672. }
  16673. // Skeleton
  16674. if (mesh.skeleton) {
  16675. serializationObject.skeletonId = mesh.skeleton.id;
  16676. }
  16677. // Physics
  16678. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16679. serializationObject.physicsMass = mesh.getPhysicsMass();
  16680. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16681. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16682. switch (mesh.getPhysicsImpostor()) {
  16683. case BABYLON.PhysicsEngine.BoxImpostor:
  16684. serializationObject.physicsImpostor = 1;
  16685. break;
  16686. case BABYLON.PhysicsEngine.SphereImpostor:
  16687. serializationObject.physicsImpostor = 2;
  16688. break;
  16689. }
  16690. }
  16691. // Instances
  16692. serializationObject.instances = [];
  16693. for (var index = 0; index < mesh.instances.length; index++) {
  16694. var instance = mesh.instances[index];
  16695. var serializationInstance = {
  16696. name: instance.name,
  16697. position: instance.position,
  16698. rotation: instance.rotation,
  16699. rotationQuaternion: instance.rotationQuaternion,
  16700. scaling: instance.scaling
  16701. };
  16702. serializationObject.instances.push(serializationInstance);
  16703. // Animations
  16704. appendAnimations(instance, serializationInstance);
  16705. }
  16706. // Animations
  16707. appendAnimations(mesh, serializationObject);
  16708. // Layer mask
  16709. serializationObject.layerMask = mesh.layerMask;
  16710. return serializationObject;
  16711. };
  16712. var SceneSerializer = (function () {
  16713. function SceneSerializer() {
  16714. }
  16715. SceneSerializer.Serialize = function (scene) {
  16716. var serializationObject = {};
  16717. // Scene
  16718. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16719. serializationObject.autoClear = scene.autoClear;
  16720. serializationObject.clearColor = scene.clearColor.asArray();
  16721. serializationObject.ambientColor = scene.ambientColor.asArray();
  16722. serializationObject.gravity = scene.gravity.asArray();
  16723. // Fog
  16724. if (scene.fogMode && scene.fogMode !== 0) {
  16725. serializationObject.fogMode = scene.fogMode;
  16726. serializationObject.fogColor = scene.fogColor.asArray();
  16727. serializationObject.fogStart = scene.fogStart;
  16728. serializationObject.fogEnd = scene.fogEnd;
  16729. serializationObject.fogDensity = scene.fogDensity;
  16730. }
  16731. // Lights
  16732. serializationObject.lights = [];
  16733. for (var index = 0; index < scene.lights.length; index++) {
  16734. var light = scene.lights[index];
  16735. serializationObject.lights.push(serializeLight(light));
  16736. }
  16737. // Cameras
  16738. serializationObject.cameras = [];
  16739. for (index = 0; index < scene.cameras.length; index++) {
  16740. var camera = scene.cameras[index];
  16741. if (camera instanceof BABYLON.FreeCamera) {
  16742. serializationObject.cameras.push(serializeCamera(camera));
  16743. }
  16744. }
  16745. if (scene.activeCamera) {
  16746. serializationObject.activeCameraID = scene.activeCamera.id;
  16747. }
  16748. // Materials
  16749. serializationObject.materials = [];
  16750. serializationObject.multiMaterials = [];
  16751. for (index = 0; index < scene.materials.length; index++) {
  16752. var material = scene.materials[index];
  16753. if (material instanceof BABYLON.StandardMaterial) {
  16754. serializationObject.materials.push(serializeMaterial(material));
  16755. } else if (material instanceof BABYLON.MultiMaterial) {
  16756. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16757. }
  16758. }
  16759. // Skeletons
  16760. serializationObject.skeletons = [];
  16761. for (index = 0; index < scene.skeletons.length; index++) {
  16762. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16763. }
  16764. // Geometries
  16765. serializationObject.geometries = {};
  16766. serializationObject.geometries.boxes = [];
  16767. serializationObject.geometries.spheres = [];
  16768. serializationObject.geometries.cylinders = [];
  16769. serializationObject.geometries.toruses = [];
  16770. serializationObject.geometries.grounds = [];
  16771. serializationObject.geometries.planes = [];
  16772. serializationObject.geometries.torusKnots = [];
  16773. serializationObject.geometries.vertexData = [];
  16774. serializedGeometries = [];
  16775. var geometries = scene.getGeometries();
  16776. for (var index = 0; index < geometries.length; index++) {
  16777. var geometry = geometries[index];
  16778. if (geometry.isReady()) {
  16779. serializeGeometry(geometry, serializationObject.geometries);
  16780. }
  16781. }
  16782. // Meshes
  16783. serializationObject.meshes = [];
  16784. for (index = 0; index < scene.meshes.length; index++) {
  16785. var abstractMesh = scene.meshes[index];
  16786. if (abstractMesh instanceof BABYLON.Mesh) {
  16787. var mesh = abstractMesh;
  16788. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16789. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16790. }
  16791. }
  16792. }
  16793. // Particles Systems
  16794. serializationObject.particleSystems = [];
  16795. for (index = 0; index < scene.particleSystems.length; index++) {
  16796. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16797. }
  16798. // Lens flares
  16799. serializationObject.lensFlareSystems = [];
  16800. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16801. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16802. }
  16803. // Shadows
  16804. serializationObject.shadowGenerators = [];
  16805. for (index = 0; index < scene.lights.length; index++) {
  16806. light = scene.lights[index];
  16807. if (light.getShadowGenerator()) {
  16808. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16809. }
  16810. }
  16811. return serializationObject;
  16812. };
  16813. return SceneSerializer;
  16814. })();
  16815. BABYLON.SceneSerializer = SceneSerializer;
  16816. })(BABYLON || (BABYLON = {}));
  16817. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16818. var BABYLON;
  16819. (function (BABYLON) {
  16820. var SceneLoader = (function () {
  16821. function SceneLoader() {
  16822. }
  16823. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16824. get: function () {
  16825. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16826. },
  16827. set: function (value) {
  16828. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16829. },
  16830. enumerable: true,
  16831. configurable: true
  16832. });
  16833. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16834. get: function () {
  16835. return SceneLoader._ShowLoadingScreen;
  16836. },
  16837. set: function (value) {
  16838. SceneLoader._ShowLoadingScreen = value;
  16839. },
  16840. enumerable: true,
  16841. configurable: true
  16842. });
  16843. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16844. var dotPosition = sceneFilename.lastIndexOf(".");
  16845. var queryStringPosition = sceneFilename.indexOf("?");
  16846. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16847. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16848. var plugin = this._registeredPlugins[index];
  16849. if (plugin.extensions.indexOf(extension) !== -1) {
  16850. return plugin;
  16851. }
  16852. }
  16853. return this._registeredPlugins[this._registeredPlugins.length - 1];
  16854. };
  16855. // Public functions
  16856. SceneLoader.RegisterPlugin = function (plugin) {
  16857. plugin.extensions = plugin.extensions.toLowerCase();
  16858. SceneLoader._registeredPlugins.push(plugin);
  16859. };
  16860. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16861. var manifestChecked = function (success) {
  16862. scene.database = database;
  16863. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16864. var importMeshFromData = function (data) {
  16865. var meshes = [];
  16866. var particleSystems = [];
  16867. var skeletons = [];
  16868. try {
  16869. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16870. if (onerror) {
  16871. onerror(scene, 'unable to load the scene');
  16872. }
  16873. return;
  16874. }
  16875. } catch (e) {
  16876. if (onerror) {
  16877. onerror(scene, e);
  16878. }
  16879. return;
  16880. }
  16881. if (onsuccess) {
  16882. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16883. onsuccess(meshes, particleSystems, skeletons);
  16884. }
  16885. };
  16886. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16887. // Direct load
  16888. importMeshFromData(sceneFilename.substr(5));
  16889. return;
  16890. }
  16891. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  16892. importMeshFromData(data);
  16893. }, progressCallBack, database);
  16894. };
  16895. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  16896. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16897. };
  16898. /**
  16899. * Load a scene
  16900. * @param rootUrl a string that defines the root url for scene and resources
  16901. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16902. * @param engine is the instance of BABYLON.Engine to use to create the scene
  16903. */
  16904. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  16905. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  16906. };
  16907. /**
  16908. * Append a scene
  16909. * @param rootUrl a string that defines the root url for scene and resources
  16910. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16911. * @param scene is the instance of BABYLON.Scene to append to
  16912. */
  16913. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16914. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  16915. var database;
  16916. if (SceneLoader.ShowLoadingScreen) {
  16917. scene.getEngine().displayLoadingUI();
  16918. }
  16919. var loadSceneFromData = function (data) {
  16920. scene.database = database;
  16921. if (!plugin.load(scene, data, rootUrl)) {
  16922. if (onerror) {
  16923. onerror(scene);
  16924. }
  16925. scene.getEngine().hideLoadingUI();
  16926. return;
  16927. }
  16928. if (onsuccess) {
  16929. onsuccess(scene);
  16930. }
  16931. if (SceneLoader.ShowLoadingScreen) {
  16932. scene.executeWhenReady(function () {
  16933. scene.getEngine().hideLoadingUI();
  16934. });
  16935. }
  16936. };
  16937. var manifestChecked = function (success) {
  16938. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  16939. };
  16940. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16941. // Direct load
  16942. loadSceneFromData(sceneFilename.substr(5));
  16943. return;
  16944. }
  16945. if (rootUrl.indexOf("file:") === -1) {
  16946. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  16947. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16948. } else {
  16949. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  16950. }
  16951. };
  16952. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  16953. SceneLoader._ShowLoadingScreen = true;
  16954. SceneLoader._registeredPlugins = new Array();
  16955. return SceneLoader;
  16956. })();
  16957. BABYLON.SceneLoader = SceneLoader;
  16958. ;
  16959. })(BABYLON || (BABYLON = {}));
  16960. //# sourceMappingURL=babylon.sceneLoader.js.map
  16961. var BABYLON;
  16962. (function (BABYLON) {
  16963. (function (Internals) {
  16964. var checkColors4 = function (colors, count) {
  16965. // Check if color3 was used
  16966. if (colors.length === count * 3) {
  16967. var colors4 = [];
  16968. for (var index = 0; index < colors.length; index += 3) {
  16969. var newIndex = (index / 3) * 4;
  16970. colors4[newIndex] = colors[index];
  16971. colors4[newIndex + 1] = colors[index + 1];
  16972. colors4[newIndex + 2] = colors[index + 2];
  16973. colors4[newIndex + 3] = 1.0;
  16974. }
  16975. return colors4;
  16976. }
  16977. return colors;
  16978. };
  16979. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  16980. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  16981. texture.name = parsedTexture.name;
  16982. texture.hasAlpha = parsedTexture.hasAlpha;
  16983. texture.level = parsedTexture.level;
  16984. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16985. return texture;
  16986. };
  16987. var loadTexture = function (rootUrl, parsedTexture, scene) {
  16988. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  16989. return null;
  16990. }
  16991. if (parsedTexture.isCube) {
  16992. return loadCubeTexture(rootUrl, parsedTexture, scene);
  16993. }
  16994. var texture;
  16995. if (parsedTexture.mirrorPlane) {
  16996. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16997. texture._waitingRenderList = parsedTexture.renderList;
  16998. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  16999. } else if (parsedTexture.isRenderTarget) {
  17000. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17001. texture._waitingRenderList = parsedTexture.renderList;
  17002. } else {
  17003. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17004. }
  17005. texture.name = parsedTexture.name;
  17006. texture.hasAlpha = parsedTexture.hasAlpha;
  17007. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17008. texture.level = parsedTexture.level;
  17009. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17010. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17011. texture.uOffset = parsedTexture.uOffset;
  17012. texture.vOffset = parsedTexture.vOffset;
  17013. texture.uScale = parsedTexture.uScale;
  17014. texture.vScale = parsedTexture.vScale;
  17015. texture.uAng = parsedTexture.uAng;
  17016. texture.vAng = parsedTexture.vAng;
  17017. texture.wAng = parsedTexture.wAng;
  17018. texture.wrapU = parsedTexture.wrapU;
  17019. texture.wrapV = parsedTexture.wrapV;
  17020. // Animations
  17021. if (parsedTexture.animations) {
  17022. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17023. var parsedAnimation = parsedTexture.animations[animationIndex];
  17024. texture.animations.push(parseAnimation(parsedAnimation));
  17025. }
  17026. }
  17027. return texture;
  17028. };
  17029. var parseSkeleton = function (parsedSkeleton, scene) {
  17030. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17031. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17032. var parsedBone = parsedSkeleton.bones[index];
  17033. var parentBone = null;
  17034. if (parsedBone.parentBoneIndex > -1) {
  17035. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17036. }
  17037. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17038. if (parsedBone.animation) {
  17039. bone.animations.push(parseAnimation(parsedBone.animation));
  17040. }
  17041. }
  17042. return skeleton;
  17043. };
  17044. var parseFresnelParameters = function (parsedFresnelParameters) {
  17045. var fresnelParameters = new BABYLON.FresnelParameters();
  17046. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17047. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17048. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17049. fresnelParameters.bias = parsedFresnelParameters.bias;
  17050. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17051. return fresnelParameters;
  17052. };
  17053. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17054. var material;
  17055. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17056. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17057. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17058. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17059. material.specularPower = parsedMaterial.specularPower;
  17060. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17061. material.alpha = parsedMaterial.alpha;
  17062. material.id = parsedMaterial.id;
  17063. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17064. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17065. material.wireframe = parsedMaterial.wireframe;
  17066. if (parsedMaterial.diffuseTexture) {
  17067. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17068. }
  17069. if (parsedMaterial.diffuseFresnelParameters) {
  17070. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17071. }
  17072. if (parsedMaterial.ambientTexture) {
  17073. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17074. }
  17075. if (parsedMaterial.opacityTexture) {
  17076. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17077. }
  17078. if (parsedMaterial.opacityFresnelParameters) {
  17079. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17080. }
  17081. if (parsedMaterial.reflectionTexture) {
  17082. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17083. }
  17084. if (parsedMaterial.reflectionFresnelParameters) {
  17085. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17086. }
  17087. if (parsedMaterial.emissiveTexture) {
  17088. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17089. }
  17090. if (parsedMaterial.emissiveFresnelParameters) {
  17091. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17092. }
  17093. if (parsedMaterial.specularTexture) {
  17094. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17095. }
  17096. if (parsedMaterial.bumpTexture) {
  17097. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17098. }
  17099. return material;
  17100. };
  17101. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17102. for (var index = 0; index < parsedData.materials.length; index++) {
  17103. var parsedMaterial = parsedData.materials[index];
  17104. if (parsedMaterial.id === id) {
  17105. return parseMaterial(parsedMaterial, scene, rootUrl);
  17106. }
  17107. }
  17108. return null;
  17109. };
  17110. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17111. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17112. multiMaterial.id = parsedMultiMaterial.id;
  17113. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17114. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17115. var subMatId = parsedMultiMaterial.materials[matIndex];
  17116. if (subMatId) {
  17117. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17118. } else {
  17119. multiMaterial.subMaterials.push(null);
  17120. }
  17121. }
  17122. return multiMaterial;
  17123. };
  17124. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17125. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17126. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17127. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17128. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17129. var parsedFlare = parsedLensFlareSystem.flares[index];
  17130. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17131. }
  17132. return lensFlareSystem;
  17133. };
  17134. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17135. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17136. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17137. if (parsedParticleSystem.textureName) {
  17138. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17139. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17140. }
  17141. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17142. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17143. particleSystem.minSize = parsedParticleSystem.minSize;
  17144. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17145. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17146. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17147. particleSystem.emitter = emitter;
  17148. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17149. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17150. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17151. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17152. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17153. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17154. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17155. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17156. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17157. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17158. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17159. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17160. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17161. particleSystem.start();
  17162. return particleSystem;
  17163. };
  17164. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17165. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17166. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17167. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17168. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17169. shadowGenerator.getShadowMap().renderList.push(mesh);
  17170. }
  17171. if (parsedShadowGenerator.usePoissonSampling) {
  17172. shadowGenerator.usePoissonSampling = true;
  17173. } else {
  17174. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17175. }
  17176. return shadowGenerator;
  17177. };
  17178. var parseAnimation = function (parsedAnimation) {
  17179. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17180. var dataType = parsedAnimation.dataType;
  17181. var keys = [];
  17182. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17183. var key = parsedAnimation.keys[index];
  17184. var data;
  17185. switch (dataType) {
  17186. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17187. data = key.values[0];
  17188. break;
  17189. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17190. data = BABYLON.Quaternion.FromArray(key.values);
  17191. break;
  17192. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17193. data = BABYLON.Matrix.FromArray(key.values);
  17194. break;
  17195. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17196. default:
  17197. data = BABYLON.Vector3.FromArray(key.values);
  17198. break;
  17199. }
  17200. keys.push({
  17201. frame: key.frame,
  17202. value: data
  17203. });
  17204. }
  17205. animation.setKeys(keys);
  17206. return animation;
  17207. };
  17208. var parseLight = function (parsedLight, scene) {
  17209. var light;
  17210. switch (parsedLight.type) {
  17211. case 0:
  17212. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17213. break;
  17214. case 1:
  17215. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17216. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17217. break;
  17218. case 2:
  17219. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17220. break;
  17221. case 3:
  17222. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17223. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17224. break;
  17225. }
  17226. light.id = parsedLight.id;
  17227. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17228. if (parsedLight.intensity !== undefined) {
  17229. light.intensity = parsedLight.intensity;
  17230. }
  17231. if (parsedLight.range) {
  17232. light.range = parsedLight.range;
  17233. }
  17234. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17235. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17236. if (parsedLight.excludedMeshesIds) {
  17237. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17238. }
  17239. // Parent
  17240. if (parsedLight.parentId) {
  17241. light._waitingParentId = parsedLight.parentId;
  17242. }
  17243. if (parsedLight.includedOnlyMeshesIds) {
  17244. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17245. }
  17246. // Animations
  17247. if (parsedLight.animations) {
  17248. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17249. var parsedAnimation = parsedLight.animations[animationIndex];
  17250. light.animations.push(parseAnimation(parsedAnimation));
  17251. }
  17252. }
  17253. if (parsedLight.autoAnimate) {
  17254. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17255. }
  17256. };
  17257. var parseCamera = function (parsedCamera, scene) {
  17258. var camera;
  17259. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17260. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17261. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17262. var alpha = parsedCamera.alpha;
  17263. var beta = parsedCamera.beta;
  17264. var radius = parsedCamera.radius;
  17265. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17266. var eye_space = parsedCamera.eye_space;
  17267. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17268. } else {
  17269. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17270. }
  17271. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17272. var eye_space = parsedCamera.eye_space;
  17273. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17274. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17275. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17276. } else if (parsedCamera.type === "FollowCamera") {
  17277. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17278. camera.heightOffset = parsedCamera.heightOffset;
  17279. camera.radius = parsedCamera.radius;
  17280. camera.rotationOffset = parsedCamera.rotationOffset;
  17281. if (lockedTargetMesh)
  17282. camera.target = lockedTargetMesh;
  17283. } else if (parsedCamera.type === "GamepadCamera") {
  17284. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17285. } else if (parsedCamera.type === "OculusCamera") {
  17286. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17287. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17288. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17289. } else if (parsedCamera.type === "TouchCamera") {
  17290. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17291. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17292. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17293. } else if (parsedCamera.type === "WebVRCamera") {
  17294. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17295. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17296. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17297. } else {
  17298. // Free Camera is the default value
  17299. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17300. }
  17301. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17302. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17303. camera.lockedTarget = lockedTargetMesh;
  17304. }
  17305. camera.id = parsedCamera.id;
  17306. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17307. // Parent
  17308. if (parsedCamera.parentId) {
  17309. camera._waitingParentId = parsedCamera.parentId;
  17310. }
  17311. // Target
  17312. if (parsedCamera.target) {
  17313. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17314. } else {
  17315. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17316. }
  17317. camera.fov = parsedCamera.fov;
  17318. camera.minZ = parsedCamera.minZ;
  17319. camera.maxZ = parsedCamera.maxZ;
  17320. camera.speed = parsedCamera.speed;
  17321. camera.inertia = parsedCamera.inertia;
  17322. camera.checkCollisions = parsedCamera.checkCollisions;
  17323. camera.applyGravity = parsedCamera.applyGravity;
  17324. if (parsedCamera.ellipsoid) {
  17325. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17326. }
  17327. // Animations
  17328. if (parsedCamera.animations) {
  17329. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17330. var parsedAnimation = parsedCamera.animations[animationIndex];
  17331. camera.animations.push(parseAnimation(parsedAnimation));
  17332. }
  17333. }
  17334. if (parsedCamera.autoAnimate) {
  17335. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17336. }
  17337. // Layer Mask
  17338. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17339. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17340. } else {
  17341. camera.layerMask = 0xFFFFFFFF;
  17342. }
  17343. return camera;
  17344. };
  17345. var parseGeometry = function (parsedGeometry, scene) {
  17346. var id = parsedGeometry.id;
  17347. return scene.getGeometryByID(id);
  17348. };
  17349. var parseBox = function (parsedBox, scene) {
  17350. if (parseGeometry(parsedBox, scene)) {
  17351. return null;
  17352. }
  17353. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17354. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17355. scene.pushGeometry(box, true);
  17356. return box;
  17357. };
  17358. var parseSphere = function (parsedSphere, scene) {
  17359. if (parseGeometry(parsedSphere, scene)) {
  17360. return null;
  17361. }
  17362. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17363. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17364. scene.pushGeometry(sphere, true);
  17365. return sphere;
  17366. };
  17367. var parseCylinder = function (parsedCylinder, scene) {
  17368. if (parseGeometry(parsedCylinder, scene)) {
  17369. return null;
  17370. }
  17371. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17372. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17373. scene.pushGeometry(cylinder, true);
  17374. return cylinder;
  17375. };
  17376. var parseTorus = function (parsedTorus, scene) {
  17377. if (parseGeometry(parsedTorus, scene)) {
  17378. return null;
  17379. }
  17380. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17381. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17382. scene.pushGeometry(torus, true);
  17383. return torus;
  17384. };
  17385. var parseGround = function (parsedGround, scene) {
  17386. if (parseGeometry(parsedGround, scene)) {
  17387. return null;
  17388. }
  17389. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17390. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17391. scene.pushGeometry(ground, true);
  17392. return ground;
  17393. };
  17394. var parsePlane = function (parsedPlane, scene) {
  17395. if (parseGeometry(parsedPlane, scene)) {
  17396. return null;
  17397. }
  17398. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17399. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17400. scene.pushGeometry(plane, true);
  17401. return plane;
  17402. };
  17403. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17404. if (parseGeometry(parsedTorusKnot, scene)) {
  17405. return null;
  17406. }
  17407. 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);
  17408. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17409. scene.pushGeometry(torusKnot, true);
  17410. return torusKnot;
  17411. };
  17412. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17413. if (parseGeometry(parsedVertexData, scene)) {
  17414. return null;
  17415. }
  17416. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17417. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17418. if (parsedVertexData.delayLoadingFile) {
  17419. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17420. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17421. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17422. geometry._delayInfo = [];
  17423. if (parsedVertexData.hasUVs) {
  17424. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17425. }
  17426. if (parsedVertexData.hasUVs2) {
  17427. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17428. }
  17429. if (parsedVertexData.hasColors) {
  17430. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17431. }
  17432. if (parsedVertexData.hasMatricesIndices) {
  17433. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17434. }
  17435. if (parsedVertexData.hasMatricesWeights) {
  17436. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17437. }
  17438. geometry._delayLoadingFunction = importVertexData;
  17439. } else {
  17440. importVertexData(parsedVertexData, geometry);
  17441. }
  17442. scene.pushGeometry(geometry, true);
  17443. return geometry;
  17444. };
  17445. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17446. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17447. mesh.id = parsedMesh.id;
  17448. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17449. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17450. if (parsedMesh.rotationQuaternion) {
  17451. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17452. } else if (parsedMesh.rotation) {
  17453. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17454. }
  17455. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17456. if (parsedMesh.localMatrix) {
  17457. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17458. } else if (parsedMesh.pivotMatrix) {
  17459. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17460. }
  17461. mesh.setEnabled(parsedMesh.isEnabled);
  17462. mesh.isVisible = parsedMesh.isVisible;
  17463. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17464. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17465. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17466. if (parsedMesh.applyFog !== undefined) {
  17467. mesh.applyFog = parsedMesh.applyFog;
  17468. }
  17469. if (parsedMesh.pickable !== undefined) {
  17470. mesh.isPickable = parsedMesh.pickable;
  17471. }
  17472. if (parsedMesh.alphaIndex !== undefined) {
  17473. mesh.alphaIndex = parsedMesh.alphaIndex;
  17474. }
  17475. mesh.receiveShadows = parsedMesh.receiveShadows;
  17476. mesh.billboardMode = parsedMesh.billboardMode;
  17477. if (parsedMesh.visibility !== undefined) {
  17478. mesh.visibility = parsedMesh.visibility;
  17479. }
  17480. mesh.checkCollisions = parsedMesh.checkCollisions;
  17481. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17482. // Parent
  17483. if (parsedMesh.parentId) {
  17484. mesh._waitingParentId = parsedMesh.parentId;
  17485. }
  17486. // Geometry
  17487. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17488. if (parsedMesh.delayLoadingFile) {
  17489. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17490. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17491. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17492. if (parsedMesh._binaryInfo) {
  17493. mesh._binaryInfo = parsedMesh._binaryInfo;
  17494. }
  17495. mesh._delayInfo = [];
  17496. if (parsedMesh.hasUVs) {
  17497. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17498. }
  17499. if (parsedMesh.hasUVs2) {
  17500. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17501. }
  17502. if (parsedMesh.hasColors) {
  17503. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17504. }
  17505. if (parsedMesh.hasMatricesIndices) {
  17506. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17507. }
  17508. if (parsedMesh.hasMatricesWeights) {
  17509. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17510. }
  17511. mesh._delayLoadingFunction = importGeometry;
  17512. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17513. mesh._checkDelayState();
  17514. }
  17515. } else {
  17516. importGeometry(parsedMesh, mesh);
  17517. }
  17518. // Material
  17519. if (parsedMesh.materialId) {
  17520. mesh.setMaterialByID(parsedMesh.materialId);
  17521. } else {
  17522. mesh.material = null;
  17523. }
  17524. // Skeleton
  17525. if (parsedMesh.skeletonId > -1) {
  17526. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17527. }
  17528. // Physics
  17529. if (parsedMesh.physicsImpostor) {
  17530. if (!scene.isPhysicsEnabled()) {
  17531. scene.enablePhysics();
  17532. }
  17533. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17534. }
  17535. // Animations
  17536. if (parsedMesh.animations) {
  17537. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17538. var parsedAnimation = parsedMesh.animations[animationIndex];
  17539. mesh.animations.push(parseAnimation(parsedAnimation));
  17540. }
  17541. }
  17542. if (parsedMesh.autoAnimate) {
  17543. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17544. }
  17545. // Layer Mask
  17546. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17547. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17548. } else {
  17549. mesh.layerMask = 0xFFFFFFFF;
  17550. }
  17551. // Instances
  17552. if (parsedMesh.instances) {
  17553. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17554. var parsedInstance = parsedMesh.instances[index];
  17555. var instance = mesh.createInstance(parsedInstance.name);
  17556. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17557. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17558. if (parsedInstance.rotationQuaternion) {
  17559. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17560. } else if (parsedInstance.rotation) {
  17561. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17562. }
  17563. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17564. instance.checkCollisions = mesh.checkCollisions;
  17565. if (parsedMesh.animations) {
  17566. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17567. parsedAnimation = parsedMesh.animations[animationIndex];
  17568. instance.animations.push(parseAnimation(parsedAnimation));
  17569. }
  17570. }
  17571. }
  17572. }
  17573. return mesh;
  17574. };
  17575. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17576. names = (names instanceof Array) ? names : [names];
  17577. for (var i in names) {
  17578. if (mesh.name === names[i]) {
  17579. hierarchyIds.push(mesh.id);
  17580. return true;
  17581. }
  17582. }
  17583. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17584. hierarchyIds.push(mesh.id);
  17585. return true;
  17586. }
  17587. return false;
  17588. };
  17589. var importVertexData = function (parsedVertexData, geometry) {
  17590. var vertexData = new BABYLON.VertexData();
  17591. // positions
  17592. var positions = parsedVertexData.positions;
  17593. if (positions) {
  17594. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17595. }
  17596. // normals
  17597. var normals = parsedVertexData.normals;
  17598. if (normals) {
  17599. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17600. }
  17601. // uvs
  17602. var uvs = parsedVertexData.uvs;
  17603. if (uvs) {
  17604. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17605. }
  17606. // uv2s
  17607. var uv2s = parsedVertexData.uv2s;
  17608. if (uv2s) {
  17609. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17610. }
  17611. // colors
  17612. var colors = parsedVertexData.colors;
  17613. if (colors) {
  17614. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17615. }
  17616. // matricesIndices
  17617. var matricesIndices = parsedVertexData.matricesIndices;
  17618. if (matricesIndices) {
  17619. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17620. }
  17621. // matricesWeights
  17622. var matricesWeights = parsedVertexData.matricesWeights;
  17623. if (matricesWeights) {
  17624. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17625. }
  17626. // indices
  17627. var indices = parsedVertexData.indices;
  17628. if (indices) {
  17629. vertexData.indices = indices;
  17630. }
  17631. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17632. };
  17633. var importGeometry = function (parsedGeometry, mesh) {
  17634. var scene = mesh.getScene();
  17635. // Geometry
  17636. var geometryId = parsedGeometry.geometryId;
  17637. if (geometryId) {
  17638. var geometry = scene.getGeometryByID(geometryId);
  17639. if (geometry) {
  17640. geometry.applyToMesh(mesh);
  17641. }
  17642. } else if (parsedGeometry instanceof ArrayBuffer) {
  17643. var binaryInfo = mesh._binaryInfo;
  17644. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17645. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17646. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17647. }
  17648. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17649. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17650. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17651. }
  17652. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17653. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17654. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17655. }
  17656. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17657. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17658. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17659. }
  17660. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17661. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17662. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17663. }
  17664. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17665. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17667. }
  17668. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17669. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17671. }
  17672. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17673. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17674. mesh.setIndices(indicesData);
  17675. }
  17676. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17677. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17678. mesh.subMeshes = [];
  17679. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17680. var materialIndex = subMeshesData[(i * 5) + 0];
  17681. var verticesStart = subMeshesData[(i * 5) + 1];
  17682. var verticesCount = subMeshesData[(i * 5) + 2];
  17683. var indexStart = subMeshesData[(i * 5) + 3];
  17684. var indexCount = subMeshesData[(i * 5) + 4];
  17685. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17686. }
  17687. }
  17688. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17689. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17690. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17691. if (parsedGeometry.uvs) {
  17692. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17693. }
  17694. if (parsedGeometry.uvs2) {
  17695. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17696. }
  17697. if (parsedGeometry.colors) {
  17698. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17699. }
  17700. if (parsedGeometry.matricesIndices) {
  17701. if (!parsedGeometry.matricesIndices._isExpanded) {
  17702. var floatIndices = [];
  17703. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17704. var matricesIndex = parsedGeometry.matricesIndices[i];
  17705. floatIndices.push(matricesIndex & 0x000000FF);
  17706. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17707. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17708. floatIndices.push(matricesIndex >> 24);
  17709. }
  17710. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17711. } else {
  17712. delete parsedGeometry.matricesIndices._isExpanded;
  17713. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17714. }
  17715. }
  17716. if (parsedGeometry.matricesWeights) {
  17717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17718. }
  17719. mesh.setIndices(parsedGeometry.indices);
  17720. // SubMeshes
  17721. if (parsedGeometry.subMeshes) {
  17722. mesh.subMeshes = [];
  17723. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17724. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17725. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17726. }
  17727. }
  17728. }
  17729. // Flat shading
  17730. if (mesh._shouldGenerateFlatShading) {
  17731. mesh.convertToFlatShadedMesh();
  17732. delete mesh._shouldGenerateFlatShading;
  17733. }
  17734. // Update
  17735. mesh.computeWorldMatrix(true);
  17736. // Octree
  17737. if (scene._selectionOctree) {
  17738. scene._selectionOctree.addMesh(mesh);
  17739. }
  17740. };
  17741. BABYLON.SceneLoader.RegisterPlugin({
  17742. extensions: ".babylon",
  17743. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17744. var parsedData = JSON.parse(data);
  17745. var loadedSkeletonsIds = [];
  17746. var loadedMaterialsIds = [];
  17747. var hierarchyIds = [];
  17748. for (var index = 0; index < parsedData.meshes.length; index++) {
  17749. var parsedMesh = parsedData.meshes[index];
  17750. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17751. if (meshesNames instanceof Array) {
  17752. // Remove found mesh name from list.
  17753. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17754. }
  17755. // Material ?
  17756. if (parsedMesh.materialId) {
  17757. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17758. if (!materialFound) {
  17759. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17760. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17761. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17762. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17763. var subMatId = parsedMultiMaterial.materials[matIndex];
  17764. loadedMaterialsIds.push(subMatId);
  17765. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17766. }
  17767. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17768. parseMultiMaterial(parsedMultiMaterial, scene);
  17769. materialFound = true;
  17770. break;
  17771. }
  17772. }
  17773. }
  17774. if (!materialFound) {
  17775. loadedMaterialsIds.push(parsedMesh.materialId);
  17776. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17777. }
  17778. }
  17779. // Skeleton ?
  17780. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17781. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17782. if (!skeletonAlreadyLoaded) {
  17783. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17784. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17785. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17786. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17787. loadedSkeletonsIds.push(parsedSkeleton.id);
  17788. }
  17789. }
  17790. }
  17791. }
  17792. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17793. meshes.push(mesh);
  17794. }
  17795. }
  17796. for (index = 0; index < scene.meshes.length; index++) {
  17797. var currentMesh = scene.meshes[index];
  17798. if (currentMesh._waitingParentId) {
  17799. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17800. currentMesh._waitingParentId = undefined;
  17801. }
  17802. }
  17803. // Particles
  17804. if (parsedData.particleSystems) {
  17805. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17806. var parsedParticleSystem = parsedData.particleSystems[index];
  17807. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17808. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17809. }
  17810. }
  17811. }
  17812. return true;
  17813. },
  17814. load: function (scene, data, rootUrl) {
  17815. var parsedData = JSON.parse(data);
  17816. // Scene
  17817. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17818. scene.autoClear = parsedData.autoClear;
  17819. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17820. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17821. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17822. // Fog
  17823. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17824. scene.fogMode = parsedData.fogMode;
  17825. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17826. scene.fogStart = parsedData.fogStart;
  17827. scene.fogEnd = parsedData.fogEnd;
  17828. scene.fogDensity = parsedData.fogDensity;
  17829. }
  17830. for (var index = 0; index < parsedData.lights.length; index++) {
  17831. var parsedLight = parsedData.lights[index];
  17832. parseLight(parsedLight, scene);
  17833. }
  17834. // Materials
  17835. if (parsedData.materials) {
  17836. for (index = 0; index < parsedData.materials.length; index++) {
  17837. var parsedMaterial = parsedData.materials[index];
  17838. parseMaterial(parsedMaterial, scene, rootUrl);
  17839. }
  17840. }
  17841. if (parsedData.multiMaterials) {
  17842. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17843. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17844. parseMultiMaterial(parsedMultiMaterial, scene);
  17845. }
  17846. }
  17847. // Skeletons
  17848. if (parsedData.skeletons) {
  17849. for (index = 0; index < parsedData.skeletons.length; index++) {
  17850. var parsedSkeleton = parsedData.skeletons[index];
  17851. parseSkeleton(parsedSkeleton, scene);
  17852. }
  17853. }
  17854. // Geometries
  17855. var geometries = parsedData.geometries;
  17856. if (geometries) {
  17857. // Boxes
  17858. var boxes = geometries.boxes;
  17859. if (boxes) {
  17860. for (index = 0; index < boxes.length; index++) {
  17861. var parsedBox = boxes[index];
  17862. parseBox(parsedBox, scene);
  17863. }
  17864. }
  17865. // Spheres
  17866. var spheres = geometries.spheres;
  17867. if (spheres) {
  17868. for (index = 0; index < spheres.length; index++) {
  17869. var parsedSphere = spheres[index];
  17870. parseSphere(parsedSphere, scene);
  17871. }
  17872. }
  17873. // Cylinders
  17874. var cylinders = geometries.cylinders;
  17875. if (cylinders) {
  17876. for (index = 0; index < cylinders.length; index++) {
  17877. var parsedCylinder = cylinders[index];
  17878. parseCylinder(parsedCylinder, scene);
  17879. }
  17880. }
  17881. // Toruses
  17882. var toruses = geometries.toruses;
  17883. if (toruses) {
  17884. for (index = 0; index < toruses.length; index++) {
  17885. var parsedTorus = toruses[index];
  17886. parseTorus(parsedTorus, scene);
  17887. }
  17888. }
  17889. // Grounds
  17890. var grounds = geometries.grounds;
  17891. if (grounds) {
  17892. for (index = 0; index < grounds.length; index++) {
  17893. var parsedGround = grounds[index];
  17894. parseGround(parsedGround, scene);
  17895. }
  17896. }
  17897. // Planes
  17898. var planes = geometries.planes;
  17899. if (planes) {
  17900. for (index = 0; index < planes.length; index++) {
  17901. var parsedPlane = planes[index];
  17902. parsePlane(parsedPlane, scene);
  17903. }
  17904. }
  17905. // TorusKnots
  17906. var torusKnots = geometries.torusKnots;
  17907. if (torusKnots) {
  17908. for (index = 0; index < torusKnots.length; index++) {
  17909. var parsedTorusKnot = torusKnots[index];
  17910. parseTorusKnot(parsedTorusKnot, scene);
  17911. }
  17912. }
  17913. // VertexData
  17914. var vertexData = geometries.vertexData;
  17915. if (vertexData) {
  17916. for (index = 0; index < vertexData.length; index++) {
  17917. var parsedVertexData = vertexData[index];
  17918. parseVertexData(parsedVertexData, scene, rootUrl);
  17919. }
  17920. }
  17921. }
  17922. for (index = 0; index < parsedData.meshes.length; index++) {
  17923. var parsedMesh = parsedData.meshes[index];
  17924. parseMesh(parsedMesh, scene, rootUrl);
  17925. }
  17926. for (index = 0; index < parsedData.cameras.length; index++) {
  17927. var parsedCamera = parsedData.cameras[index];
  17928. parseCamera(parsedCamera, scene);
  17929. }
  17930. if (parsedData.activeCameraID) {
  17931. scene.setActiveCameraByID(parsedData.activeCameraID);
  17932. }
  17933. for (index = 0; index < scene.cameras.length; index++) {
  17934. var camera = scene.cameras[index];
  17935. if (camera._waitingParentId) {
  17936. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  17937. camera._waitingParentId = undefined;
  17938. }
  17939. }
  17940. for (index = 0; index < scene.lights.length; index++) {
  17941. var light = scene.lights[index];
  17942. if (light._waitingParentId) {
  17943. light.parent = scene.getLastEntryByID(light._waitingParentId);
  17944. light._waitingParentId = undefined;
  17945. }
  17946. }
  17947. for (index = 0; index < scene.meshes.length; index++) {
  17948. var mesh = scene.meshes[index];
  17949. if (mesh._waitingParentId) {
  17950. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  17951. mesh._waitingParentId = undefined;
  17952. }
  17953. }
  17954. // Particles Systems
  17955. if (parsedData.particleSystems) {
  17956. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17957. var parsedParticleSystem = parsedData.particleSystems[index];
  17958. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  17959. }
  17960. }
  17961. // Lens flares
  17962. if (parsedData.lensFlareSystems) {
  17963. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  17964. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  17965. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  17966. }
  17967. }
  17968. // Shadows
  17969. if (parsedData.shadowGenerators) {
  17970. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  17971. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  17972. parseShadowGenerator(parsedShadowGenerator, scene);
  17973. }
  17974. }
  17975. // Finish
  17976. return true;
  17977. }
  17978. });
  17979. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17980. var Internals = BABYLON.Internals;
  17981. })(BABYLON || (BABYLON = {}));
  17982. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  17983. var BABYLON;
  17984. (function (BABYLON) {
  17985. // Unique ID when we import meshes from Babylon to CSG
  17986. var currentCSGMeshId = 0;
  17987. // # class Vertex
  17988. // Represents a vertex of a polygon. Use your own vertex class instead of this
  17989. // one to provide additional features like texture coordinates and vertex
  17990. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  17991. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  17992. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  17993. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  17994. // is not used anywhere else.
  17995. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  17996. var Vertex = (function () {
  17997. function Vertex(pos, normal, uv) {
  17998. this.pos = pos;
  17999. this.normal = normal;
  18000. this.uv = uv;
  18001. }
  18002. Vertex.prototype.clone = function () {
  18003. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18004. };
  18005. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18006. // orientation of a polygon is flipped.
  18007. Vertex.prototype.flip = function () {
  18008. this.normal = this.normal.scale(-1);
  18009. };
  18010. // Create a new vertex between this vertex and `other` by linearly
  18011. // interpolating all properties using a parameter of `t`. Subclasses should
  18012. // override this to interpolate additional properties.
  18013. Vertex.prototype.interpolate = function (other, t) {
  18014. 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));
  18015. };
  18016. return Vertex;
  18017. })();
  18018. // # class Plane
  18019. // Represents a plane in 3D space.
  18020. var Plane = (function () {
  18021. function Plane(normal, w) {
  18022. this.normal = normal;
  18023. this.w = w;
  18024. }
  18025. Plane.FromPoints = function (a, b, c) {
  18026. var v0 = c.subtract(a);
  18027. var v1 = b.subtract(a);
  18028. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18029. return null;
  18030. }
  18031. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18032. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18033. };
  18034. Plane.prototype.clone = function () {
  18035. return new Plane(this.normal.clone(), this.w);
  18036. };
  18037. Plane.prototype.flip = function () {
  18038. this.normal.scaleInPlace(-1);
  18039. this.w = -this.w;
  18040. };
  18041. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18042. // fragments in the appropriate lists. Coplanar polygons go into either
  18043. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18044. // respect to this plane. Polygons in front or in back of this plane go into
  18045. // either `front` or `back`.
  18046. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18047. var COPLANAR = 0;
  18048. var FRONT = 1;
  18049. var BACK = 2;
  18050. var SPANNING = 3;
  18051. // Classify each point as well as the entire polygon into one of the above
  18052. // four classes.
  18053. var polygonType = 0;
  18054. var types = [];
  18055. for (var i = 0; i < polygon.vertices.length; i++) {
  18056. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18057. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18058. polygonType |= type;
  18059. types.push(type);
  18060. }
  18061. switch (polygonType) {
  18062. case COPLANAR:
  18063. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18064. break;
  18065. case FRONT:
  18066. front.push(polygon);
  18067. break;
  18068. case BACK:
  18069. back.push(polygon);
  18070. break;
  18071. case SPANNING:
  18072. var f = [], b = [];
  18073. for (i = 0; i < polygon.vertices.length; i++) {
  18074. var j = (i + 1) % polygon.vertices.length;
  18075. var ti = types[i], tj = types[j];
  18076. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18077. if (ti != BACK)
  18078. f.push(vi);
  18079. if (ti != FRONT)
  18080. b.push(ti != BACK ? vi.clone() : vi);
  18081. if ((ti | tj) == SPANNING) {
  18082. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18083. var v = vi.interpolate(vj, t);
  18084. f.push(v);
  18085. b.push(v.clone());
  18086. }
  18087. }
  18088. if (f.length >= 3) {
  18089. var poly = new Polygon(f, polygon.shared);
  18090. if (poly.plane)
  18091. front.push(poly);
  18092. }
  18093. if (b.length >= 3) {
  18094. poly = new Polygon(b, polygon.shared);
  18095. if (poly.plane)
  18096. back.push(poly);
  18097. }
  18098. break;
  18099. }
  18100. };
  18101. Plane.EPSILON = 1e-5;
  18102. return Plane;
  18103. })();
  18104. // # class Polygon
  18105. // Represents a convex polygon. The vertices used to initialize a polygon must
  18106. // be coplanar and form a convex loop.
  18107. //
  18108. // Each convex polygon has a `shared` property, which is shared between all
  18109. // polygons that are clones of each other or were split from the same polygon.
  18110. // This can be used to define per-polygon properties (such as surface color).
  18111. var Polygon = (function () {
  18112. function Polygon(vertices, shared) {
  18113. this.vertices = vertices;
  18114. this.shared = shared;
  18115. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18116. }
  18117. Polygon.prototype.clone = function () {
  18118. var vertices = this.vertices.map(function (v) {
  18119. return v.clone();
  18120. });
  18121. return new Polygon(vertices, this.shared);
  18122. };
  18123. Polygon.prototype.flip = function () {
  18124. this.vertices.reverse().map(function (v) {
  18125. v.flip();
  18126. });
  18127. this.plane.flip();
  18128. };
  18129. return Polygon;
  18130. })();
  18131. // # class Node
  18132. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18133. // by picking a polygon to split along. That polygon (and all other coplanar
  18134. // polygons) are added directly to that node and the other polygons are added to
  18135. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18136. // no distinction between internal and leaf nodes.
  18137. var Node = (function () {
  18138. function Node(polygons) {
  18139. this.plane = null;
  18140. this.front = null;
  18141. this.back = null;
  18142. this.polygons = [];
  18143. if (polygons) {
  18144. this.build(polygons);
  18145. }
  18146. }
  18147. Node.prototype.clone = function () {
  18148. var node = new Node();
  18149. node.plane = this.plane && this.plane.clone();
  18150. node.front = this.front && this.front.clone();
  18151. node.back = this.back && this.back.clone();
  18152. node.polygons = this.polygons.map(function (p) {
  18153. return p.clone();
  18154. });
  18155. return node;
  18156. };
  18157. // Convert solid space to empty space and empty space to solid space.
  18158. Node.prototype.invert = function () {
  18159. for (var i = 0; i < this.polygons.length; i++) {
  18160. this.polygons[i].flip();
  18161. }
  18162. if (this.plane) {
  18163. this.plane.flip();
  18164. }
  18165. if (this.front) {
  18166. this.front.invert();
  18167. }
  18168. if (this.back) {
  18169. this.back.invert();
  18170. }
  18171. var temp = this.front;
  18172. this.front = this.back;
  18173. this.back = temp;
  18174. };
  18175. // Recursively remove all polygons in `polygons` that are inside this BSP
  18176. // tree.
  18177. Node.prototype.clipPolygons = function (polygons) {
  18178. if (!this.plane)
  18179. return polygons.slice();
  18180. var front = [], back = [];
  18181. for (var i = 0; i < polygons.length; i++) {
  18182. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18183. }
  18184. if (this.front) {
  18185. front = this.front.clipPolygons(front);
  18186. }
  18187. if (this.back) {
  18188. back = this.back.clipPolygons(back);
  18189. } else {
  18190. back = [];
  18191. }
  18192. return front.concat(back);
  18193. };
  18194. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18195. // `bsp`.
  18196. Node.prototype.clipTo = function (bsp) {
  18197. this.polygons = bsp.clipPolygons(this.polygons);
  18198. if (this.front)
  18199. this.front.clipTo(bsp);
  18200. if (this.back)
  18201. this.back.clipTo(bsp);
  18202. };
  18203. // Return a list of all polygons in this BSP tree.
  18204. Node.prototype.allPolygons = function () {
  18205. var polygons = this.polygons.slice();
  18206. if (this.front)
  18207. polygons = polygons.concat(this.front.allPolygons());
  18208. if (this.back)
  18209. polygons = polygons.concat(this.back.allPolygons());
  18210. return polygons;
  18211. };
  18212. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18213. // new polygons are filtered down to the bottom of the tree and become new
  18214. // nodes there. Each set of polygons is partitioned using the first polygon
  18215. // (no heuristic is used to pick a good split).
  18216. Node.prototype.build = function (polygons) {
  18217. if (!polygons.length)
  18218. return;
  18219. if (!this.plane)
  18220. this.plane = polygons[0].plane.clone();
  18221. var front = [], back = [];
  18222. for (var i = 0; i < polygons.length; i++) {
  18223. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18224. }
  18225. if (front.length) {
  18226. if (!this.front)
  18227. this.front = new Node();
  18228. this.front.build(front);
  18229. }
  18230. if (back.length) {
  18231. if (!this.back)
  18232. this.back = new Node();
  18233. this.back.build(back);
  18234. }
  18235. };
  18236. return Node;
  18237. })();
  18238. var CSG = (function () {
  18239. function CSG() {
  18240. this.polygons = new Array();
  18241. }
  18242. // Convert BABYLON.Mesh to BABYLON.CSG
  18243. CSG.FromMesh = function (mesh) {
  18244. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18245. if (mesh instanceof BABYLON.Mesh) {
  18246. mesh.computeWorldMatrix(true);
  18247. var matrix = mesh.getWorldMatrix();
  18248. var meshPosition = mesh.position.clone();
  18249. var meshRotation = mesh.rotation.clone();
  18250. var meshScaling = mesh.scaling.clone();
  18251. } else {
  18252. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18253. }
  18254. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18255. var subMeshes = mesh.subMeshes;
  18256. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18257. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18258. vertices = [];
  18259. for (var j = 0; j < 3; j++) {
  18260. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18261. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18262. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18263. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18264. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18265. vertex = new Vertex(position, normal, uv);
  18266. vertices.push(vertex);
  18267. }
  18268. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18269. // To handle the case of degenerated triangle
  18270. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18271. if (polygon.plane)
  18272. polygons.push(polygon);
  18273. }
  18274. }
  18275. var csg = CSG.FromPolygons(polygons);
  18276. csg.matrix = matrix;
  18277. csg.position = meshPosition;
  18278. csg.rotation = meshRotation;
  18279. csg.scaling = meshScaling;
  18280. currentCSGMeshId++;
  18281. return csg;
  18282. };
  18283. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18284. CSG.FromPolygons = function (polygons) {
  18285. var csg = new BABYLON.CSG();
  18286. csg.polygons = polygons;
  18287. return csg;
  18288. };
  18289. CSG.prototype.clone = function () {
  18290. var csg = new BABYLON.CSG();
  18291. csg.polygons = this.polygons.map(function (p) {
  18292. return p.clone();
  18293. });
  18294. csg.copyTransformAttributes(this);
  18295. return csg;
  18296. };
  18297. CSG.prototype.toPolygons = function () {
  18298. return this.polygons;
  18299. };
  18300. CSG.prototype.union = function (csg) {
  18301. var a = new Node(this.clone().polygons);
  18302. var b = new Node(csg.clone().polygons);
  18303. a.clipTo(b);
  18304. b.clipTo(a);
  18305. b.invert();
  18306. b.clipTo(a);
  18307. b.invert();
  18308. a.build(b.allPolygons());
  18309. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18310. };
  18311. CSG.prototype.unionInPlace = function (csg) {
  18312. var a = new Node(this.polygons);
  18313. var b = new Node(csg.polygons);
  18314. a.clipTo(b);
  18315. b.clipTo(a);
  18316. b.invert();
  18317. b.clipTo(a);
  18318. b.invert();
  18319. a.build(b.allPolygons());
  18320. this.polygons = a.allPolygons();
  18321. };
  18322. CSG.prototype.subtract = function (csg) {
  18323. var a = new Node(this.clone().polygons);
  18324. var b = new Node(csg.clone().polygons);
  18325. a.invert();
  18326. a.clipTo(b);
  18327. b.clipTo(a);
  18328. b.invert();
  18329. b.clipTo(a);
  18330. b.invert();
  18331. a.build(b.allPolygons());
  18332. a.invert();
  18333. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18334. };
  18335. CSG.prototype.subtractInPlace = function (csg) {
  18336. var a = new Node(this.polygons);
  18337. var b = new Node(csg.polygons);
  18338. a.invert();
  18339. a.clipTo(b);
  18340. b.clipTo(a);
  18341. b.invert();
  18342. b.clipTo(a);
  18343. b.invert();
  18344. a.build(b.allPolygons());
  18345. a.invert();
  18346. this.polygons = a.allPolygons();
  18347. };
  18348. CSG.prototype.intersect = function (csg) {
  18349. var a = new Node(this.clone().polygons);
  18350. var b = new Node(csg.clone().polygons);
  18351. a.invert();
  18352. b.clipTo(a);
  18353. b.invert();
  18354. a.clipTo(b);
  18355. b.clipTo(a);
  18356. a.build(b.allPolygons());
  18357. a.invert();
  18358. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18359. };
  18360. CSG.prototype.intersectInPlace = function (csg) {
  18361. var a = new Node(this.polygons);
  18362. var b = new Node(csg.polygons);
  18363. a.invert();
  18364. b.clipTo(a);
  18365. b.invert();
  18366. a.clipTo(b);
  18367. b.clipTo(a);
  18368. a.build(b.allPolygons());
  18369. a.invert();
  18370. this.polygons = a.allPolygons();
  18371. };
  18372. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18373. // not modified.
  18374. CSG.prototype.inverse = function () {
  18375. var csg = this.clone();
  18376. csg.inverseInPlace();
  18377. return csg;
  18378. };
  18379. CSG.prototype.inverseInPlace = function () {
  18380. this.polygons.map(function (p) {
  18381. p.flip();
  18382. });
  18383. };
  18384. // This is used to keep meshes transformations so they can be restored
  18385. // when we build back a Babylon Mesh
  18386. // NB : All CSG operations are performed in world coordinates
  18387. CSG.prototype.copyTransformAttributes = function (csg) {
  18388. this.matrix = csg.matrix;
  18389. this.position = csg.position;
  18390. this.rotation = csg.rotation;
  18391. this.scaling = csg.scaling;
  18392. return this;
  18393. };
  18394. // Build Raw mesh from CSG
  18395. // Coordinates here are in world space
  18396. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18397. var matrix = this.matrix.clone();
  18398. matrix.invert();
  18399. 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;
  18400. if (keepSubMeshes) {
  18401. // Sort Polygons, since subMeshes are indices range
  18402. polygons.sort(function (a, b) {
  18403. if (a.shared.meshId === b.shared.meshId) {
  18404. return a.shared.subMeshId - b.shared.subMeshId;
  18405. } else {
  18406. return a.shared.meshId - b.shared.meshId;
  18407. }
  18408. });
  18409. }
  18410. for (var i = 0, il = polygons.length; i < il; i++) {
  18411. polygon = polygons[i];
  18412. // Building SubMeshes
  18413. if (!subMesh_dict[polygon.shared.meshId]) {
  18414. subMesh_dict[polygon.shared.meshId] = {};
  18415. }
  18416. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18417. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18418. indexStart: +Infinity,
  18419. indexEnd: -Infinity,
  18420. materialIndex: polygon.shared.materialIndex
  18421. };
  18422. }
  18423. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18424. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18425. polygonIndices[0] = 0;
  18426. polygonIndices[1] = j - 1;
  18427. polygonIndices[2] = j;
  18428. for (var k = 0; k < 3; k++) {
  18429. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18430. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18431. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18432. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18433. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18434. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18435. // Check if 2 points can be merged
  18436. 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)) {
  18437. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18438. uvs.push(uv.x, uv.y);
  18439. normals.push(normal.x, normal.y, normal.z);
  18440. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18441. }
  18442. indices.push(vertex_idx);
  18443. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18444. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18445. currentIndex++;
  18446. }
  18447. }
  18448. }
  18449. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18450. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18451. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18452. mesh.setIndices(indices);
  18453. if (keepSubMeshes) {
  18454. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18455. var materialIndexOffset = 0, materialMaxIndex;
  18456. mesh.subMeshes.length = 0;
  18457. for (var m in subMesh_dict) {
  18458. materialMaxIndex = -1;
  18459. for (var sm in subMesh_dict[m]) {
  18460. subMesh_obj = subMesh_dict[m][sm];
  18461. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18462. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18463. }
  18464. materialIndexOffset += ++materialMaxIndex;
  18465. }
  18466. }
  18467. return mesh;
  18468. };
  18469. // Build Mesh from CSG taking material and transforms into account
  18470. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18471. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18472. mesh.material = material;
  18473. mesh.position.copyFrom(this.position);
  18474. mesh.rotation.copyFrom(this.rotation);
  18475. mesh.scaling.copyFrom(this.scaling);
  18476. mesh.computeWorldMatrix(true);
  18477. return mesh;
  18478. };
  18479. return CSG;
  18480. })();
  18481. BABYLON.CSG = CSG;
  18482. })(BABYLON || (BABYLON = {}));
  18483. //# sourceMappingURL=babylon.csg.js.map
  18484. var BABYLON;
  18485. (function (BABYLON) {
  18486. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18487. __extends(OculusDistortionCorrectionPostProcess, _super);
  18488. //ANY
  18489. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18490. var _this = this;
  18491. _super.call(this, name, "oculusDistortionCorrection", [
  18492. 'LensCenter',
  18493. 'Scale',
  18494. 'ScaleIn',
  18495. 'HmdWarpParam'
  18496. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18497. this._isRightEye = isRightEye;
  18498. this._distortionFactors = cameraSettings.DistortionK;
  18499. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18500. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18501. this.onSizeChanged = function () {
  18502. _this.aspectRatio = _this.width * .5 / _this.height;
  18503. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18504. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18505. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18506. };
  18507. this.onApply = function (effect) {
  18508. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18509. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18510. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18511. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18512. };
  18513. }
  18514. return OculusDistortionCorrectionPostProcess;
  18515. })(BABYLON.PostProcess);
  18516. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18517. })(BABYLON || (BABYLON = {}));
  18518. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18519. // Mainly based on these 2 articles :
  18520. // 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
  18521. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18522. var BABYLON;
  18523. (function (BABYLON) {
  18524. (function (JoystickAxis) {
  18525. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18526. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18527. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18528. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18529. var JoystickAxis = BABYLON.JoystickAxis;
  18530. var VirtualJoystick = (function () {
  18531. function VirtualJoystick(leftJoystick) {
  18532. var _this = this;
  18533. if (leftJoystick) {
  18534. this._leftJoystick = true;
  18535. } else {
  18536. this._leftJoystick = false;
  18537. }
  18538. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18539. VirtualJoystick._globalJoystickIndex++;
  18540. // By default left & right arrow keys are moving the X
  18541. // and up & down keys are moving the Y
  18542. this._axisTargetedByLeftAndRight = 0 /* X */;
  18543. this._axisTargetedByUpAndDown = 1 /* Y */;
  18544. this.reverseLeftRight = false;
  18545. this.reverseUpDown = false;
  18546. // collections of pointers
  18547. this._touches = new BABYLON.VirtualJoystick.Collection();
  18548. this.deltaPosition = BABYLON.Vector3.Zero();
  18549. this._joystickSensibility = 25;
  18550. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18551. this._rotationSpeed = 25;
  18552. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18553. this._rotateOnAxisRelativeToMesh = false;
  18554. // injecting a canvas element on top of the canvas 3D game
  18555. if (!VirtualJoystick.vjCanvas) {
  18556. window.addEventListener("resize", function () {
  18557. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18558. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18559. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18560. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18561. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18562. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18563. }, false);
  18564. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18565. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18566. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18567. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18568. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18569. VirtualJoystick.vjCanvas.style.width = "100%";
  18570. VirtualJoystick.vjCanvas.style.height = "100%";
  18571. VirtualJoystick.vjCanvas.style.position = "absolute";
  18572. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18573. VirtualJoystick.vjCanvas.style.top = "0px";
  18574. VirtualJoystick.vjCanvas.style.left = "0px";
  18575. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18576. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18577. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18578. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18579. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18580. document.body.appendChild(VirtualJoystick.vjCanvas);
  18581. }
  18582. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18583. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18584. this.pressed = false;
  18585. // default joystick color
  18586. this._joystickColor = "cyan";
  18587. this._joystickPointerID = -1;
  18588. // current joystick position
  18589. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18590. // origin joystick position
  18591. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18592. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18593. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18594. _this._onPointerDown(evt);
  18595. }, false);
  18596. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18597. _this._onPointerMove(evt);
  18598. }, false);
  18599. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18600. _this._onPointerUp(evt);
  18601. }, false);
  18602. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18603. _this._onPointerUp(evt);
  18604. }, false);
  18605. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18606. evt.preventDefault(); // Disables system menu
  18607. }, false);
  18608. requestAnimationFrame(function () {
  18609. _this._drawVirtualJoystick();
  18610. });
  18611. }
  18612. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18613. this._joystickSensibility = newJoystickSensibility;
  18614. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18615. };
  18616. VirtualJoystick.prototype._onPointerDown = function (e) {
  18617. var positionOnScreenCondition;
  18618. e.preventDefault();
  18619. if (this._leftJoystick === true) {
  18620. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18621. } else {
  18622. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18623. }
  18624. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18625. // First contact will be dedicated to the virtual joystick
  18626. this._joystickPointerID = e.pointerId;
  18627. this._joystickPointerStartPos.x = e.clientX;
  18628. this._joystickPointerStartPos.y = e.clientY;
  18629. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18630. this._deltaJoystickVector.x = 0;
  18631. this._deltaJoystickVector.y = 0;
  18632. this.pressed = true;
  18633. this._touches.add(e.pointerId.toString(), e);
  18634. } else {
  18635. // You can only trigger the action buttons with a joystick declared
  18636. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18637. this._action();
  18638. this._touches.add(e.pointerId.toString(), e);
  18639. }
  18640. }
  18641. };
  18642. VirtualJoystick.prototype._onPointerMove = function (e) {
  18643. // If the current pointer is the one associated to the joystick (first touch contact)
  18644. if (this._joystickPointerID == e.pointerId) {
  18645. this._joystickPointerPos.x = e.clientX;
  18646. this._joystickPointerPos.y = e.clientY;
  18647. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18648. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18649. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18650. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18651. switch (this._axisTargetedByLeftAndRight) {
  18652. case 0 /* X */:
  18653. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18654. break;
  18655. case 1 /* Y */:
  18656. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18657. break;
  18658. case 2 /* Z */:
  18659. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18660. break;
  18661. }
  18662. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18663. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18664. switch (this._axisTargetedByUpAndDown) {
  18665. case 0 /* X */:
  18666. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18667. break;
  18668. case 1 /* Y */:
  18669. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18670. break;
  18671. case 2 /* Z */:
  18672. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18673. break;
  18674. }
  18675. } else {
  18676. if (this._touches.item(e.pointerId.toString())) {
  18677. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18678. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18679. }
  18680. }
  18681. };
  18682. VirtualJoystick.prototype._onPointerUp = function (e) {
  18683. this._clearCanvas();
  18684. if (this._joystickPointerID == e.pointerId) {
  18685. this._joystickPointerID = -1;
  18686. this.pressed = false;
  18687. }
  18688. this._deltaJoystickVector.x = 0;
  18689. this._deltaJoystickVector.y = 0;
  18690. this._touches.remove(e.pointerId.toString());
  18691. };
  18692. /**
  18693. * Change the color of the virtual joystick
  18694. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18695. */
  18696. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18697. this._joystickColor = newColor;
  18698. };
  18699. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18700. this._action = action;
  18701. };
  18702. // Define which axis you'd like to control for left & right
  18703. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18704. switch (axis) {
  18705. case 0 /* X */:
  18706. case 1 /* Y */:
  18707. case 2 /* Z */:
  18708. this._axisTargetedByLeftAndRight = axis;
  18709. break;
  18710. default:
  18711. this._axisTargetedByLeftAndRight = 0 /* X */;
  18712. break;
  18713. }
  18714. };
  18715. // Define which axis you'd like to control for up & down
  18716. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18717. switch (axis) {
  18718. case 0 /* X */:
  18719. case 1 /* Y */:
  18720. case 2 /* Z */:
  18721. this._axisTargetedByUpAndDown = axis;
  18722. break;
  18723. default:
  18724. this._axisTargetedByUpAndDown = 1 /* Y */;
  18725. break;
  18726. }
  18727. };
  18728. VirtualJoystick.prototype._clearCanvas = function () {
  18729. if (this._leftJoystick) {
  18730. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18731. } else {
  18732. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18733. }
  18734. };
  18735. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18736. var _this = this;
  18737. if (this.pressed) {
  18738. this._clearCanvas();
  18739. this._touches.forEach(function (touch) {
  18740. if (touch.pointerId === _this._joystickPointerID) {
  18741. VirtualJoystick.vjCanvasContext.beginPath();
  18742. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18743. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18744. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18745. VirtualJoystick.vjCanvasContext.stroke();
  18746. VirtualJoystick.vjCanvasContext.beginPath();
  18747. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18748. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18749. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18750. VirtualJoystick.vjCanvasContext.stroke();
  18751. VirtualJoystick.vjCanvasContext.beginPath();
  18752. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18753. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18754. VirtualJoystick.vjCanvasContext.stroke();
  18755. } else {
  18756. VirtualJoystick.vjCanvasContext.beginPath();
  18757. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18758. VirtualJoystick.vjCanvasContext.beginPath();
  18759. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18760. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18761. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18762. VirtualJoystick.vjCanvasContext.stroke();
  18763. }
  18764. ;
  18765. });
  18766. }
  18767. requestAnimationFrame(function () {
  18768. _this._drawVirtualJoystick();
  18769. });
  18770. };
  18771. VirtualJoystick.prototype.releaseCanvas = function () {
  18772. if (VirtualJoystick.vjCanvas) {
  18773. document.body.removeChild(VirtualJoystick.vjCanvas);
  18774. VirtualJoystick.vjCanvas = null;
  18775. }
  18776. };
  18777. VirtualJoystick._globalJoystickIndex = 0;
  18778. return VirtualJoystick;
  18779. })();
  18780. BABYLON.VirtualJoystick = VirtualJoystick;
  18781. })(BABYLON || (BABYLON = {}));
  18782. var BABYLON;
  18783. (function (BABYLON) {
  18784. (function (VirtualJoystick) {
  18785. var Collection = (function () {
  18786. function Collection() {
  18787. this._count = 0;
  18788. this._collection = new Array();
  18789. }
  18790. Collection.prototype.Count = function () {
  18791. return this._count;
  18792. };
  18793. Collection.prototype.add = function (key, item) {
  18794. if (this._collection[key] != undefined) {
  18795. return undefined;
  18796. }
  18797. this._collection[key] = item;
  18798. return ++this._count;
  18799. };
  18800. Collection.prototype.remove = function (key) {
  18801. if (this._collection[key] == undefined) {
  18802. return undefined;
  18803. }
  18804. delete this._collection[key];
  18805. return --this._count;
  18806. };
  18807. Collection.prototype.item = function (key) {
  18808. return this._collection[key];
  18809. };
  18810. Collection.prototype.forEach = function (block) {
  18811. var key;
  18812. for (key in this._collection) {
  18813. if (this._collection.hasOwnProperty(key)) {
  18814. block(this._collection[key]);
  18815. }
  18816. }
  18817. };
  18818. return Collection;
  18819. })();
  18820. VirtualJoystick.Collection = Collection;
  18821. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18822. var VirtualJoystick = BABYLON.VirtualJoystick;
  18823. })(BABYLON || (BABYLON = {}));
  18824. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18825. var BABYLON;
  18826. (function (BABYLON) {
  18827. var OculusRiftDevKit2013_Metric = {
  18828. HResolution: 1280,
  18829. VResolution: 800,
  18830. HScreenSize: 0.149759993,
  18831. VScreenSize: 0.0935999975,
  18832. VScreenCenter: 0.0467999987,
  18833. EyeToScreenDistance: 0.0410000011,
  18834. LensSeparationDistance: 0.0635000020,
  18835. InterpupillaryDistance: 0.0640000030,
  18836. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18837. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18838. PostProcessScaleFactor: 1.714605507808412,
  18839. LensCenterOffset: 0.151976421
  18840. };
  18841. var _OculusInnerCamera = (function (_super) {
  18842. __extends(_OculusInnerCamera, _super);
  18843. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18844. _super.call(this, name, position, scene);
  18845. this._workMatrix = new BABYLON.Matrix();
  18846. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18847. // Constants
  18848. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18849. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18850. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18851. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18852. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18853. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18854. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18855. // Postprocess
  18856. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18857. }
  18858. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  18859. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18860. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18861. return this._projectionMatrix;
  18862. };
  18863. _OculusInnerCamera.prototype._getViewMatrix = function () {
  18864. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18865. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18866. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18867. // Computing target and final matrix
  18868. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18869. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18870. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18871. return this._viewMatrix;
  18872. };
  18873. return _OculusInnerCamera;
  18874. })(BABYLON.FreeCamera);
  18875. var OculusCamera = (function (_super) {
  18876. __extends(OculusCamera, _super);
  18877. function OculusCamera(name, position, scene) {
  18878. _super.call(this, name, position, scene);
  18879. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  18880. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  18881. this.subCameras.push(this._leftCamera);
  18882. this.subCameras.push(this._rightCamera);
  18883. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18884. }
  18885. OculusCamera.prototype._update = function () {
  18886. this._leftCamera.position.copyFrom(this.position);
  18887. this._rightCamera.position.copyFrom(this.position);
  18888. this._updateCamera(this._leftCamera);
  18889. this._updateCamera(this._rightCamera);
  18890. _super.prototype._update.call(this);
  18891. };
  18892. OculusCamera.prototype._updateCamera = function (camera) {
  18893. camera.minZ = this.minZ;
  18894. camera.maxZ = this.maxZ;
  18895. camera.rotation.x = this.rotation.x;
  18896. camera.rotation.y = this.rotation.y;
  18897. camera.rotation.z = this.rotation.z;
  18898. };
  18899. // Oculus events
  18900. OculusCamera.prototype._onOrientationEvent = function (evt) {
  18901. var yaw = evt.alpha / 180 * Math.PI;
  18902. var pitch = evt.beta / 180 * Math.PI;
  18903. var roll = evt.gamma / 180 * Math.PI;
  18904. if (!this._offsetOrientation) {
  18905. this._offsetOrientation = {
  18906. yaw: yaw,
  18907. pitch: pitch,
  18908. roll: roll
  18909. };
  18910. return;
  18911. } else {
  18912. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18913. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18914. this.rotation.z += this._offsetOrientation.roll - roll;
  18915. this._offsetOrientation.yaw = yaw;
  18916. this._offsetOrientation.pitch = pitch;
  18917. this._offsetOrientation.roll = roll;
  18918. }
  18919. };
  18920. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  18921. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18922. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18923. };
  18924. OculusCamera.prototype.detachControl = function (element) {
  18925. _super.prototype.detachControl.call(this, element);
  18926. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18927. };
  18928. return OculusCamera;
  18929. })(BABYLON.FreeCamera);
  18930. BABYLON.OculusCamera = OculusCamera;
  18931. })(BABYLON || (BABYLON = {}));
  18932. //# sourceMappingURL=babylon.oculusCamera.js.map
  18933. var BABYLON;
  18934. (function (BABYLON) {
  18935. var OculusRiftDevKit2013_Metric = {
  18936. HResolution: 1280,
  18937. VResolution: 800,
  18938. HScreenSize: 0.149759993,
  18939. VScreenSize: 0.0935999975,
  18940. VScreenCenter: 0.0467999987,
  18941. EyeToScreenDistance: 0.0410000011,
  18942. LensSeparationDistance: 0.0635000020,
  18943. InterpupillaryDistance: 0.0640000030,
  18944. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18945. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18946. PostProcessScaleFactor: 1.714605507808412,
  18947. LensCenterOffset: 0.151976421
  18948. };
  18949. var _OculusInnerGamepadCamera = (function (_super) {
  18950. __extends(_OculusInnerGamepadCamera, _super);
  18951. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  18952. _super.call(this, name, position, scene);
  18953. this._workMatrix = new BABYLON.Matrix();
  18954. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18955. // Constants
  18956. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18957. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18958. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18959. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18960. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18961. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18962. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18963. // Postprocess
  18964. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18965. }
  18966. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  18967. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18968. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18969. return this._projectionMatrix;
  18970. };
  18971. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  18972. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18973. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18974. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18975. // Computing target and final matrix
  18976. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18977. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18978. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18979. return this._viewMatrix;
  18980. };
  18981. return _OculusInnerGamepadCamera;
  18982. })(BABYLON.FreeCamera);
  18983. var OculusGamepadCamera = (function (_super) {
  18984. __extends(OculusGamepadCamera, _super);
  18985. function OculusGamepadCamera(name, position, scene) {
  18986. var _this = this;
  18987. _super.call(this, name, position, scene);
  18988. this.angularSensibility = 200;
  18989. this.moveSensibility = 75;
  18990. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  18991. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  18992. this.subCameras.push(this._leftCamera);
  18993. this.subCameras.push(this._rightCamera);
  18994. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18995. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  18996. _this._onNewGameConnected(gamepad);
  18997. });
  18998. }
  18999. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19000. // Only the first gamepad can control the camera
  19001. if (gamepad.index === 0) {
  19002. this._gamepad = gamepad;
  19003. }
  19004. };
  19005. OculusGamepadCamera.prototype._update = function () {
  19006. this._leftCamera.position.copyFrom(this.position);
  19007. this._rightCamera.position.copyFrom(this.position);
  19008. this._updateCamera(this._leftCamera);
  19009. this._updateCamera(this._rightCamera);
  19010. _super.prototype._update.call(this);
  19011. };
  19012. OculusGamepadCamera.prototype._checkInputs = function () {
  19013. if (!this._gamepad) {
  19014. return;
  19015. }
  19016. var LSValues = this._gamepad.leftStick;
  19017. var normalizedLX = LSValues.x / this.moveSensibility;
  19018. var normalizedLY = LSValues.y / this.moveSensibility;
  19019. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19020. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19021. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19022. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19023. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19024. };
  19025. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19026. camera.minZ = this.minZ;
  19027. camera.maxZ = this.maxZ;
  19028. camera.rotation.x = this.rotation.x;
  19029. camera.rotation.y = this.rotation.y;
  19030. camera.rotation.z = this.rotation.z;
  19031. };
  19032. // Oculus events
  19033. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19034. var yaw = evt.alpha / 180 * Math.PI;
  19035. var pitch = evt.beta / 180 * Math.PI;
  19036. var roll = evt.gamma / 180 * Math.PI;
  19037. if (!this._offsetOrientation) {
  19038. this._offsetOrientation = {
  19039. yaw: yaw,
  19040. pitch: pitch,
  19041. roll: roll
  19042. };
  19043. return;
  19044. } else {
  19045. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19046. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19047. this.rotation.z += this._offsetOrientation.roll - roll;
  19048. this._offsetOrientation.yaw = yaw;
  19049. this._offsetOrientation.pitch = pitch;
  19050. this._offsetOrientation.roll = roll;
  19051. }
  19052. };
  19053. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19054. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19055. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19056. };
  19057. OculusGamepadCamera.prototype.detachControl = function (element) {
  19058. _super.prototype.detachControl.call(this, element);
  19059. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19060. };
  19061. OculusGamepadCamera.prototype.dispose = function () {
  19062. this._gamepads.dispose();
  19063. _super.prototype.dispose.call(this);
  19064. };
  19065. return OculusGamepadCamera;
  19066. })(BABYLON.FreeCamera);
  19067. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19068. })(BABYLON || (BABYLON = {}));
  19069. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19070. var BABYLON;
  19071. (function (BABYLON) {
  19072. // We're mainly based on the logic defined into the FreeCamera code
  19073. var VirtualJoysticksCamera = (function (_super) {
  19074. __extends(VirtualJoysticksCamera, _super);
  19075. function VirtualJoysticksCamera(name, position, scene) {
  19076. _super.call(this, name, position, scene);
  19077. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19078. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19079. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19080. this._leftjoystick.setJoystickSensibility(0.15);
  19081. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19082. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19083. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19084. this._rightjoystick.reverseUpDown = true;
  19085. this._rightjoystick.setJoystickSensibility(0.05);
  19086. this._rightjoystick.setJoystickColor("yellow");
  19087. }
  19088. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19089. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19090. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19091. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19092. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19093. if (!this._leftjoystick.pressed) {
  19094. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19095. }
  19096. if (!this._rightjoystick.pressed) {
  19097. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19098. }
  19099. };
  19100. VirtualJoysticksCamera.prototype.dispose = function () {
  19101. this._leftjoystick.releaseCanvas();
  19102. _super.prototype.dispose.call(this);
  19103. };
  19104. return VirtualJoysticksCamera;
  19105. })(BABYLON.FreeCamera);
  19106. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19107. })(BABYLON || (BABYLON = {}));
  19108. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19109. var BABYLON;
  19110. (function (BABYLON) {
  19111. var ShaderMaterial = (function (_super) {
  19112. __extends(ShaderMaterial, _super);
  19113. function ShaderMaterial(name, scene, shaderPath, options) {
  19114. _super.call(this, name, scene);
  19115. this._textures = new Array();
  19116. this._floats = new Array();
  19117. this._floatsArrays = {};
  19118. this._colors3 = new Array();
  19119. this._colors4 = new Array();
  19120. this._vectors2 = new Array();
  19121. this._vectors3 = new Array();
  19122. this._matrices = new Array();
  19123. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19124. this._shaderPath = shaderPath;
  19125. options.needAlphaBlending = options.needAlphaBlending || false;
  19126. options.needAlphaTesting = options.needAlphaTesting || false;
  19127. options.attributes = options.attributes || ["position", "normal", "uv"];
  19128. options.uniforms = options.uniforms || ["worldViewProjection"];
  19129. options.samplers = options.samplers || [];
  19130. this._options = options;
  19131. }
  19132. ShaderMaterial.prototype.needAlphaBlending = function () {
  19133. return this._options.needAlphaBlending;
  19134. };
  19135. ShaderMaterial.prototype.needAlphaTesting = function () {
  19136. return this._options.needAlphaTesting;
  19137. };
  19138. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19139. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19140. this._options.uniforms.push(uniformName);
  19141. }
  19142. };
  19143. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19144. if (this._options.samplers.indexOf(name) === -1) {
  19145. this._options.samplers.push(name);
  19146. }
  19147. this._textures[name] = texture;
  19148. return this;
  19149. };
  19150. ShaderMaterial.prototype.setFloat = function (name, value) {
  19151. this._checkUniform(name);
  19152. this._floats[name] = value;
  19153. return this;
  19154. };
  19155. ShaderMaterial.prototype.setFloats = function (name, value) {
  19156. this._checkUniform(name);
  19157. this._floatsArrays[name] = value;
  19158. return this;
  19159. };
  19160. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19161. this._checkUniform(name);
  19162. this._colors3[name] = value;
  19163. return this;
  19164. };
  19165. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19166. this._checkUniform(name);
  19167. this._colors4[name] = value;
  19168. return this;
  19169. };
  19170. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19171. this._checkUniform(name);
  19172. this._vectors2[name] = value;
  19173. return this;
  19174. };
  19175. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19176. this._checkUniform(name);
  19177. this._vectors3[name] = value;
  19178. return this;
  19179. };
  19180. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19181. this._checkUniform(name);
  19182. this._matrices[name] = value;
  19183. return this;
  19184. };
  19185. ShaderMaterial.prototype.isReady = function () {
  19186. var scene = this.getScene();
  19187. var engine = scene.getEngine();
  19188. if (!this.checkReadyOnEveryCall) {
  19189. if (this._renderId === scene.getRenderId()) {
  19190. return true;
  19191. }
  19192. }
  19193. var previousEffect = this._effect;
  19194. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19195. if (!this._effect.isReady()) {
  19196. return false;
  19197. }
  19198. if (previousEffect !== this._effect) {
  19199. scene.resetCachedMaterial();
  19200. }
  19201. this._renderId = scene.getRenderId();
  19202. return true;
  19203. };
  19204. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19205. var scene = this.getScene();
  19206. if (this._options.uniforms.indexOf("world") !== -1) {
  19207. this._effect.setMatrix("world", world);
  19208. }
  19209. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19210. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19211. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19212. }
  19213. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19214. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19215. }
  19216. };
  19217. ShaderMaterial.prototype.bind = function (world) {
  19218. // Std values
  19219. this.bindOnlyWorldMatrix(world);
  19220. if (this.getScene().getCachedMaterial() !== this) {
  19221. if (this._options.uniforms.indexOf("view") !== -1) {
  19222. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19223. }
  19224. if (this._options.uniforms.indexOf("projection") !== -1) {
  19225. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19226. }
  19227. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19228. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19229. }
  19230. for (var name in this._textures) {
  19231. this._effect.setTexture(name, this._textures[name]);
  19232. }
  19233. for (name in this._floats) {
  19234. this._effect.setFloat(name, this._floats[name]);
  19235. }
  19236. for (name in this._floatsArrays) {
  19237. this._effect.setArray(name, this._floatsArrays[name]);
  19238. }
  19239. for (name in this._colors3) {
  19240. this._effect.setColor3(name, this._colors3[name]);
  19241. }
  19242. for (name in this._colors4) {
  19243. var color = this._colors4[name];
  19244. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19245. }
  19246. for (name in this._vectors2) {
  19247. this._effect.setVector2(name, this._vectors2[name]);
  19248. }
  19249. for (name in this._vectors3) {
  19250. this._effect.setVector3(name, this._vectors3[name]);
  19251. }
  19252. for (name in this._matrices) {
  19253. this._effect.setMatrix(name, this._matrices[name]);
  19254. }
  19255. }
  19256. _super.prototype.bind.call(this, world, null);
  19257. };
  19258. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19259. for (var name in this._textures) {
  19260. this._textures[name].dispose();
  19261. }
  19262. this._textures = [];
  19263. _super.prototype.dispose.call(this, forceDisposeEffect);
  19264. };
  19265. return ShaderMaterial;
  19266. })(BABYLON.Material);
  19267. BABYLON.ShaderMaterial = ShaderMaterial;
  19268. })(BABYLON || (BABYLON = {}));
  19269. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19270. var BABYLON;
  19271. (function (BABYLON) {
  19272. var VertexData = (function () {
  19273. function VertexData() {
  19274. }
  19275. VertexData.prototype.set = function (data, kind) {
  19276. switch (kind) {
  19277. case BABYLON.VertexBuffer.PositionKind:
  19278. this.positions = data;
  19279. break;
  19280. case BABYLON.VertexBuffer.NormalKind:
  19281. this.normals = data;
  19282. break;
  19283. case BABYLON.VertexBuffer.UVKind:
  19284. this.uvs = data;
  19285. break;
  19286. case BABYLON.VertexBuffer.UV2Kind:
  19287. this.uv2s = data;
  19288. break;
  19289. case BABYLON.VertexBuffer.ColorKind:
  19290. this.colors = data;
  19291. break;
  19292. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19293. this.matricesIndices = data;
  19294. break;
  19295. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19296. this.matricesWeights = data;
  19297. break;
  19298. }
  19299. };
  19300. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19301. this._applyTo(mesh, updatable);
  19302. };
  19303. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19304. this._applyTo(geometry, updatable);
  19305. };
  19306. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19307. this._update(mesh);
  19308. };
  19309. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19310. this._update(geometry);
  19311. };
  19312. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19313. if (this.positions) {
  19314. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19315. }
  19316. if (this.normals) {
  19317. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19318. }
  19319. if (this.uvs) {
  19320. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19321. }
  19322. if (this.uv2s) {
  19323. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19324. }
  19325. if (this.colors) {
  19326. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19327. }
  19328. if (this.matricesIndices) {
  19329. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19330. }
  19331. if (this.matricesWeights) {
  19332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19333. }
  19334. if (this.indices) {
  19335. meshOrGeometry.setIndices(this.indices);
  19336. }
  19337. };
  19338. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19339. if (this.positions) {
  19340. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19341. }
  19342. if (this.normals) {
  19343. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19344. }
  19345. if (this.uvs) {
  19346. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19347. }
  19348. if (this.uv2s) {
  19349. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19350. }
  19351. if (this.colors) {
  19352. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19353. }
  19354. if (this.matricesIndices) {
  19355. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19356. }
  19357. if (this.matricesWeights) {
  19358. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19359. }
  19360. if (this.indices) {
  19361. meshOrGeometry.setIndices(this.indices);
  19362. }
  19363. };
  19364. VertexData.prototype.transform = function (matrix) {
  19365. var transformed = BABYLON.Vector3.Zero();
  19366. if (this.positions) {
  19367. var position = BABYLON.Vector3.Zero();
  19368. for (var index = 0; index < this.positions.length; index += 3) {
  19369. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19370. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19371. this.positions[index] = transformed.x;
  19372. this.positions[index + 1] = transformed.y;
  19373. this.positions[index + 2] = transformed.z;
  19374. }
  19375. }
  19376. if (this.normals) {
  19377. var normal = BABYLON.Vector3.Zero();
  19378. for (index = 0; index < this.normals.length; index += 3) {
  19379. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19380. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19381. this.normals[index] = transformed.x;
  19382. this.normals[index + 1] = transformed.y;
  19383. this.normals[index + 2] = transformed.z;
  19384. }
  19385. }
  19386. };
  19387. VertexData.prototype.merge = function (other) {
  19388. if (other.indices) {
  19389. if (!this.indices) {
  19390. this.indices = [];
  19391. }
  19392. var offset = this.positions ? this.positions.length / 3 : 0;
  19393. for (var index = 0; index < other.indices.length; index++) {
  19394. this.indices.push(other.indices[index] + offset);
  19395. }
  19396. }
  19397. if (other.positions) {
  19398. if (!this.positions) {
  19399. this.positions = [];
  19400. }
  19401. for (index = 0; index < other.positions.length; index++) {
  19402. this.positions.push(other.positions[index]);
  19403. }
  19404. }
  19405. if (other.normals) {
  19406. if (!this.normals) {
  19407. this.normals = [];
  19408. }
  19409. for (index = 0; index < other.normals.length; index++) {
  19410. this.normals.push(other.normals[index]);
  19411. }
  19412. }
  19413. if (other.uvs) {
  19414. if (!this.uvs) {
  19415. this.uvs = [];
  19416. }
  19417. for (index = 0; index < other.uvs.length; index++) {
  19418. this.uvs.push(other.uvs[index]);
  19419. }
  19420. }
  19421. if (other.uv2s) {
  19422. if (!this.uv2s) {
  19423. this.uv2s = [];
  19424. }
  19425. for (index = 0; index < other.uv2s.length; index++) {
  19426. this.uv2s.push(other.uv2s[index]);
  19427. }
  19428. }
  19429. if (other.matricesIndices) {
  19430. if (!this.matricesIndices) {
  19431. this.matricesIndices = [];
  19432. }
  19433. for (index = 0; index < other.matricesIndices.length; index++) {
  19434. this.matricesIndices.push(other.matricesIndices[index]);
  19435. }
  19436. }
  19437. if (other.matricesWeights) {
  19438. if (!this.matricesWeights) {
  19439. this.matricesWeights = [];
  19440. }
  19441. for (index = 0; index < other.matricesWeights.length; index++) {
  19442. this.matricesWeights.push(other.matricesWeights[index]);
  19443. }
  19444. }
  19445. if (other.colors) {
  19446. if (!this.colors) {
  19447. this.colors = [];
  19448. }
  19449. for (index = 0; index < other.colors.length; index++) {
  19450. this.colors.push(other.colors[index]);
  19451. }
  19452. }
  19453. };
  19454. // Statics
  19455. VertexData.ExtractFromMesh = function (mesh) {
  19456. return VertexData._ExtractFrom(mesh);
  19457. };
  19458. VertexData.ExtractFromGeometry = function (geometry) {
  19459. return VertexData._ExtractFrom(geometry);
  19460. };
  19461. VertexData._ExtractFrom = function (meshOrGeometry) {
  19462. var result = new BABYLON.VertexData();
  19463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19464. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19465. }
  19466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19467. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19468. }
  19469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19470. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19471. }
  19472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19473. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19474. }
  19475. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19476. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19477. }
  19478. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19479. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19480. }
  19481. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19482. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19483. }
  19484. result.indices = meshOrGeometry.getIndices();
  19485. return result;
  19486. };
  19487. VertexData.CreateBox = function (size) {
  19488. var normalsSource = [
  19489. new BABYLON.Vector3(0, 0, 1),
  19490. new BABYLON.Vector3(0, 0, -1),
  19491. new BABYLON.Vector3(1, 0, 0),
  19492. new BABYLON.Vector3(-1, 0, 0),
  19493. new BABYLON.Vector3(0, 1, 0),
  19494. new BABYLON.Vector3(0, -1, 0)
  19495. ];
  19496. var indices = [];
  19497. var positions = [];
  19498. var normals = [];
  19499. var uvs = [];
  19500. size = size || 1;
  19501. for (var index = 0; index < normalsSource.length; index++) {
  19502. var normal = normalsSource[index];
  19503. // Get two vectors perpendicular to the face normal and to each other.
  19504. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19505. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19506. // Six indices (two triangles) per face.
  19507. var verticesLength = positions.length / 3;
  19508. indices.push(verticesLength);
  19509. indices.push(verticesLength + 1);
  19510. indices.push(verticesLength + 2);
  19511. indices.push(verticesLength);
  19512. indices.push(verticesLength + 2);
  19513. indices.push(verticesLength + 3);
  19514. // Four vertices per face.
  19515. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19516. positions.push(vertex.x, vertex.y, vertex.z);
  19517. normals.push(normal.x, normal.y, normal.z);
  19518. uvs.push(1.0, 1.0);
  19519. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19520. positions.push(vertex.x, vertex.y, vertex.z);
  19521. normals.push(normal.x, normal.y, normal.z);
  19522. uvs.push(0.0, 1.0);
  19523. vertex = normal.add(side1).add(side2).scale(size / 2);
  19524. positions.push(vertex.x, vertex.y, vertex.z);
  19525. normals.push(normal.x, normal.y, normal.z);
  19526. uvs.push(0.0, 0.0);
  19527. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19528. positions.push(vertex.x, vertex.y, vertex.z);
  19529. normals.push(normal.x, normal.y, normal.z);
  19530. uvs.push(1.0, 0.0);
  19531. }
  19532. // Result
  19533. var vertexData = new BABYLON.VertexData();
  19534. vertexData.indices = indices;
  19535. vertexData.positions = positions;
  19536. vertexData.normals = normals;
  19537. vertexData.uvs = uvs;
  19538. return vertexData;
  19539. };
  19540. VertexData.CreateSphere = function (segments, diameter) {
  19541. segments = segments || 32;
  19542. diameter = diameter || 1;
  19543. var radius = diameter / 2;
  19544. var totalZRotationSteps = 2 + segments;
  19545. var totalYRotationSteps = 2 * totalZRotationSteps;
  19546. var indices = [];
  19547. var positions = [];
  19548. var normals = [];
  19549. var uvs = [];
  19550. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19551. var normalizedZ = zRotationStep / totalZRotationSteps;
  19552. var angleZ = (normalizedZ * Math.PI);
  19553. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19554. var normalizedY = yRotationStep / totalYRotationSteps;
  19555. var angleY = normalizedY * Math.PI * 2;
  19556. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19557. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19558. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19559. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19560. var vertex = complete.scale(radius);
  19561. var normal = BABYLON.Vector3.Normalize(vertex);
  19562. positions.push(vertex.x, vertex.y, vertex.z);
  19563. normals.push(normal.x, normal.y, normal.z);
  19564. uvs.push(normalizedZ, normalizedY);
  19565. }
  19566. if (zRotationStep > 0) {
  19567. var verticesCount = positions.length / 3;
  19568. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19569. indices.push((firstIndex));
  19570. indices.push((firstIndex + 1));
  19571. indices.push(firstIndex + totalYRotationSteps + 1);
  19572. indices.push((firstIndex + totalYRotationSteps + 1));
  19573. indices.push((firstIndex + 1));
  19574. indices.push((firstIndex + totalYRotationSteps + 2));
  19575. }
  19576. }
  19577. }
  19578. // Result
  19579. var vertexData = new BABYLON.VertexData();
  19580. vertexData.indices = indices;
  19581. vertexData.positions = positions;
  19582. vertexData.normals = normals;
  19583. vertexData.uvs = uvs;
  19584. return vertexData;
  19585. };
  19586. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19587. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19588. var radiusTop = diameterTop / 2;
  19589. var radiusBottom = diameterBottom / 2;
  19590. var indices = [];
  19591. var positions = [];
  19592. var normals = [];
  19593. var uvs = [];
  19594. height = height || 1;
  19595. diameterTop = diameterTop || 0.5;
  19596. diameterBottom = diameterBottom || 1;
  19597. tessellation = tessellation || 16;
  19598. subdivisions = subdivisions || 1;
  19599. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19600. var getCircleVector = function (i) {
  19601. var angle = (i * 2.0 * Math.PI / tessellation);
  19602. var dx = Math.cos(angle);
  19603. var dz = Math.sin(angle);
  19604. return new BABYLON.Vector3(dx, 0, dz);
  19605. };
  19606. var createCylinderCap = function (isTop) {
  19607. var radius = isTop ? radiusTop : radiusBottom;
  19608. if (radius == 0) {
  19609. return;
  19610. }
  19611. var vbase = positions.length / 3;
  19612. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19613. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19614. if (!isTop) {
  19615. offset.scaleInPlace(-1);
  19616. textureScale.x = -textureScale.x;
  19617. }
  19618. for (i = 0; i < tessellation; i++) {
  19619. var circleVector = getCircleVector(i);
  19620. var position = circleVector.scale(radius).add(offset);
  19621. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19622. positions.push(position.x, position.y, position.z);
  19623. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19624. }
  19625. for (var i = 0; i < tessellation - 2; i++) {
  19626. if (!isTop) {
  19627. indices.push(vbase);
  19628. indices.push(vbase + (i + 2) % tessellation);
  19629. indices.push(vbase + (i + 1) % tessellation);
  19630. } else {
  19631. indices.push(vbase);
  19632. indices.push(vbase + (i + 1) % tessellation);
  19633. indices.push(vbase + (i + 2) % tessellation);
  19634. }
  19635. }
  19636. };
  19637. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19638. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19639. var stride = tessellation + 1;
  19640. for (var i = 0; i <= tessellation; i++) {
  19641. var circleVector = getCircleVector(i);
  19642. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19643. var position, radius = radiusBottom;
  19644. for (var s = 0; s <= subdivisions; s++) {
  19645. // Update variables
  19646. position = circleVector.scale(radius);
  19647. position.addInPlace(base.add(offset.scale(s)));
  19648. textureCoordinate.y += 1 / subdivisions;
  19649. radius += (radiusTop - radiusBottom) / subdivisions;
  19650. // Push in arrays
  19651. positions.push(position.x, position.y, position.z);
  19652. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19653. }
  19654. }
  19655. subdivisions += 1;
  19656. for (var s = 0; s < subdivisions - 1; s++) {
  19657. for (var i = 0; i <= tessellation; i++) {
  19658. indices.push(i * subdivisions + s);
  19659. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19660. indices.push(i * subdivisions + (s + 1));
  19661. indices.push(i * subdivisions + (s + 1));
  19662. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19663. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19664. }
  19665. }
  19666. // Create flat triangle fan caps to seal the top and bottom.
  19667. createCylinderCap(true);
  19668. createCylinderCap(false);
  19669. // Normals
  19670. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19671. // Result
  19672. var vertexData = new BABYLON.VertexData();
  19673. vertexData.indices = indices;
  19674. vertexData.positions = positions;
  19675. vertexData.normals = normals;
  19676. vertexData.uvs = uvs;
  19677. return vertexData;
  19678. };
  19679. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19680. var indices = [];
  19681. var positions = [];
  19682. var normals = [];
  19683. var uvs = [];
  19684. diameter = diameter || 1;
  19685. thickness = thickness || 0.5;
  19686. tessellation = tessellation || 16;
  19687. var stride = tessellation + 1;
  19688. for (var i = 0; i <= tessellation; i++) {
  19689. var u = i / tessellation;
  19690. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19691. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19692. for (var j = 0; j <= tessellation; j++) {
  19693. var v = 1 - j / tessellation;
  19694. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19695. var dx = Math.cos(innerAngle);
  19696. var dy = Math.sin(innerAngle);
  19697. // Create a vertex.
  19698. var normal = new BABYLON.Vector3(dx, dy, 0);
  19699. var position = normal.scale(thickness / 2);
  19700. var textureCoordinate = new BABYLON.Vector2(u, v);
  19701. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19702. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19703. positions.push(position.x, position.y, position.z);
  19704. normals.push(normal.x, normal.y, normal.z);
  19705. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19706. // And create indices for two triangles.
  19707. var nextI = (i + 1) % stride;
  19708. var nextJ = (j + 1) % stride;
  19709. indices.push(i * stride + j);
  19710. indices.push(i * stride + nextJ);
  19711. indices.push(nextI * stride + j);
  19712. indices.push(i * stride + nextJ);
  19713. indices.push(nextI * stride + nextJ);
  19714. indices.push(nextI * stride + j);
  19715. }
  19716. }
  19717. // Result
  19718. var vertexData = new BABYLON.VertexData();
  19719. vertexData.indices = indices;
  19720. vertexData.positions = positions;
  19721. vertexData.normals = normals;
  19722. vertexData.uvs = uvs;
  19723. return vertexData;
  19724. };
  19725. VertexData.CreateLines = function (points) {
  19726. var indices = [];
  19727. var positions = [];
  19728. for (var index = 0; index < points.length; index++) {
  19729. positions.push(points[index].x, points[index].y, points[index].z);
  19730. if (index > 0) {
  19731. indices.push(index - 1);
  19732. indices.push(index);
  19733. }
  19734. }
  19735. // Result
  19736. var vertexData = new BABYLON.VertexData();
  19737. vertexData.indices = indices;
  19738. vertexData.positions = positions;
  19739. return vertexData;
  19740. };
  19741. VertexData.CreateGround = function (width, height, subdivisions) {
  19742. var indices = [];
  19743. var positions = [];
  19744. var normals = [];
  19745. var uvs = [];
  19746. var row, col;
  19747. width = width || 1;
  19748. height = height || 1;
  19749. subdivisions = subdivisions || 1;
  19750. for (row = 0; row <= subdivisions; row++) {
  19751. for (col = 0; col <= subdivisions; col++) {
  19752. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19753. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19754. positions.push(position.x, position.y, position.z);
  19755. normals.push(normal.x, normal.y, normal.z);
  19756. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19757. }
  19758. }
  19759. for (row = 0; row < subdivisions; row++) {
  19760. for (col = 0; col < subdivisions; col++) {
  19761. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19762. indices.push(col + 1 + row * (subdivisions + 1));
  19763. indices.push(col + row * (subdivisions + 1));
  19764. indices.push(col + (row + 1) * (subdivisions + 1));
  19765. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19766. indices.push(col + row * (subdivisions + 1));
  19767. }
  19768. }
  19769. // Result
  19770. var vertexData = new BABYLON.VertexData();
  19771. vertexData.indices = indices;
  19772. vertexData.positions = positions;
  19773. vertexData.normals = normals;
  19774. vertexData.uvs = uvs;
  19775. return vertexData;
  19776. };
  19777. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19778. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19779. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19780. var indices = [];
  19781. var positions = [];
  19782. var normals = [];
  19783. var uvs = [];
  19784. var row, col, tileRow, tileCol;
  19785. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19786. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19787. precision.w = (precision.w < 1) ? 1 : precision.w;
  19788. precision.h = (precision.h < 1) ? 1 : precision.h;
  19789. var tileSize = {
  19790. 'w': (xmax - xmin) / subdivisions.w,
  19791. 'h': (zmax - zmin) / subdivisions.h
  19792. };
  19793. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19794. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19795. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19796. }
  19797. }
  19798. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19799. // Indices
  19800. var base = positions.length / 3;
  19801. var rowLength = precision.w + 1;
  19802. for (row = 0; row < precision.h; row++) {
  19803. for (col = 0; col < precision.w; col++) {
  19804. var square = [
  19805. base + col + row * rowLength,
  19806. base + (col + 1) + row * rowLength,
  19807. base + (col + 1) + (row + 1) * rowLength,
  19808. base + col + (row + 1) * rowLength
  19809. ];
  19810. indices.push(square[1]);
  19811. indices.push(square[2]);
  19812. indices.push(square[3]);
  19813. indices.push(square[0]);
  19814. indices.push(square[1]);
  19815. indices.push(square[3]);
  19816. }
  19817. }
  19818. // Position, normals and uvs
  19819. var position = BABYLON.Vector3.Zero();
  19820. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19821. for (row = 0; row <= precision.h; row++) {
  19822. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19823. for (col = 0; col <= precision.w; col++) {
  19824. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19825. position.y = 0;
  19826. positions.push(position.x, position.y, position.z);
  19827. normals.push(normal.x, normal.y, normal.z);
  19828. uvs.push(col / precision.w, row / precision.h);
  19829. }
  19830. }
  19831. }
  19832. // Result
  19833. var vertexData = new BABYLON.VertexData();
  19834. vertexData.indices = indices;
  19835. vertexData.positions = positions;
  19836. vertexData.normals = normals;
  19837. vertexData.uvs = uvs;
  19838. return vertexData;
  19839. };
  19840. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19841. var indices = [];
  19842. var positions = [];
  19843. var normals = [];
  19844. var uvs = [];
  19845. var row, col;
  19846. for (row = 0; row <= subdivisions; row++) {
  19847. for (col = 0; col <= subdivisions; col++) {
  19848. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19849. // Compute height
  19850. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  19851. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  19852. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  19853. var r = buffer[pos] / 255.0;
  19854. var g = buffer[pos + 1] / 255.0;
  19855. var b = buffer[pos + 2] / 255.0;
  19856. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19857. position.y = minHeight + (maxHeight - minHeight) * gradient;
  19858. // Add vertex
  19859. positions.push(position.x, position.y, position.z);
  19860. normals.push(0, 0, 0);
  19861. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19862. }
  19863. }
  19864. for (row = 0; row < subdivisions; row++) {
  19865. for (col = 0; col < subdivisions; col++) {
  19866. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19867. indices.push(col + 1 + row * (subdivisions + 1));
  19868. indices.push(col + row * (subdivisions + 1));
  19869. indices.push(col + (row + 1) * (subdivisions + 1));
  19870. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19871. indices.push(col + row * (subdivisions + 1));
  19872. }
  19873. }
  19874. // Normals
  19875. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  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.CreatePlane = function (size) {
  19885. var indices = [];
  19886. var positions = [];
  19887. var normals = [];
  19888. var uvs = [];
  19889. size = size || 1;
  19890. // Vertices
  19891. var halfSize = size / 2.0;
  19892. positions.push(-halfSize, -halfSize, 0);
  19893. normals.push(0, 0, -1.0);
  19894. uvs.push(0.0, 0.0);
  19895. positions.push(halfSize, -halfSize, 0);
  19896. normals.push(0, 0, -1.0);
  19897. uvs.push(1.0, 0.0);
  19898. positions.push(halfSize, halfSize, 0);
  19899. normals.push(0, 0, -1.0);
  19900. uvs.push(1.0, 1.0);
  19901. positions.push(-halfSize, halfSize, 0);
  19902. normals.push(0, 0, -1.0);
  19903. uvs.push(0.0, 1.0);
  19904. // Indices
  19905. indices.push(0);
  19906. indices.push(1);
  19907. indices.push(2);
  19908. indices.push(0);
  19909. indices.push(2);
  19910. indices.push(3);
  19911. // Result
  19912. var vertexData = new BABYLON.VertexData();
  19913. vertexData.indices = indices;
  19914. vertexData.positions = positions;
  19915. vertexData.normals = normals;
  19916. vertexData.uvs = uvs;
  19917. return vertexData;
  19918. };
  19919. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19920. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  19921. var indices = [];
  19922. var positions = [];
  19923. var normals = [];
  19924. var uvs = [];
  19925. radius = radius || 2;
  19926. tube = tube || 0.5;
  19927. radialSegments = radialSegments || 32;
  19928. tubularSegments = tubularSegments || 32;
  19929. p = p || 2;
  19930. q = q || 3;
  19931. // Helper
  19932. var getPos = function (angle) {
  19933. var cu = Math.cos(angle);
  19934. var su = Math.sin(angle);
  19935. var quOverP = q / p * angle;
  19936. var cs = Math.cos(quOverP);
  19937. var tx = radius * (2 + cs) * 0.5 * cu;
  19938. var ty = radius * (2 + cs) * su * 0.5;
  19939. var tz = radius * Math.sin(quOverP) * 0.5;
  19940. return new BABYLON.Vector3(tx, ty, tz);
  19941. };
  19942. for (var i = 0; i <= radialSegments; i++) {
  19943. var modI = i % radialSegments;
  19944. var u = modI / radialSegments * 2 * p * Math.PI;
  19945. var p1 = getPos(u);
  19946. var p2 = getPos(u + 0.01);
  19947. var tang = p2.subtract(p1);
  19948. var n = p2.add(p1);
  19949. var bitan = BABYLON.Vector3.Cross(tang, n);
  19950. n = BABYLON.Vector3.Cross(bitan, tang);
  19951. bitan.normalize();
  19952. n.normalize();
  19953. for (var j = 0; j < tubularSegments; j++) {
  19954. var modJ = j % tubularSegments;
  19955. var v = modJ / tubularSegments * 2 * Math.PI;
  19956. var cx = -tube * Math.cos(v);
  19957. var cy = tube * Math.sin(v);
  19958. positions.push(p1.x + cx * n.x + cy * bitan.x);
  19959. positions.push(p1.y + cx * n.y + cy * bitan.y);
  19960. positions.push(p1.z + cx * n.z + cy * bitan.z);
  19961. uvs.push(i / radialSegments);
  19962. uvs.push(j / tubularSegments);
  19963. }
  19964. }
  19965. for (i = 0; i < radialSegments; i++) {
  19966. for (j = 0; j < tubularSegments; j++) {
  19967. var jNext = (j + 1) % tubularSegments;
  19968. var a = i * tubularSegments + j;
  19969. var b = (i + 1) * tubularSegments + j;
  19970. var c = (i + 1) * tubularSegments + jNext;
  19971. var d = i * tubularSegments + jNext;
  19972. indices.push(d);
  19973. indices.push(b);
  19974. indices.push(a);
  19975. indices.push(d);
  19976. indices.push(c);
  19977. indices.push(b);
  19978. }
  19979. }
  19980. // Normals
  19981. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19982. // Result
  19983. var vertexData = new BABYLON.VertexData();
  19984. vertexData.indices = indices;
  19985. vertexData.positions = positions;
  19986. vertexData.normals = normals;
  19987. vertexData.uvs = uvs;
  19988. return vertexData;
  19989. };
  19990. // Tools
  19991. VertexData.ComputeNormals = function (positions, indices, normals) {
  19992. var positionVectors = [];
  19993. var facesOfVertices = [];
  19994. var index;
  19995. for (index = 0; index < positions.length; index += 3) {
  19996. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  19997. positionVectors.push(vector3);
  19998. facesOfVertices.push([]);
  19999. }
  20000. // Compute normals
  20001. var facesNormals = [];
  20002. for (index = 0; index < indices.length / 3; index++) {
  20003. var i1 = indices[index * 3];
  20004. var i2 = indices[index * 3 + 1];
  20005. var i3 = indices[index * 3 + 2];
  20006. var p1 = positionVectors[i1];
  20007. var p2 = positionVectors[i2];
  20008. var p3 = positionVectors[i3];
  20009. var p1p2 = p1.subtract(p2);
  20010. var p3p2 = p3.subtract(p2);
  20011. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20012. facesOfVertices[i1].push(index);
  20013. facesOfVertices[i2].push(index);
  20014. facesOfVertices[i3].push(index);
  20015. }
  20016. for (index = 0; index < positionVectors.length; index++) {
  20017. var faces = facesOfVertices[index];
  20018. var normal = BABYLON.Vector3.Zero();
  20019. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20020. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20021. }
  20022. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20023. normals[index * 3] = normal.x;
  20024. normals[index * 3 + 1] = normal.y;
  20025. normals[index * 3 + 2] = normal.z;
  20026. }
  20027. };
  20028. return VertexData;
  20029. })();
  20030. BABYLON.VertexData = VertexData;
  20031. })(BABYLON || (BABYLON = {}));
  20032. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20033. var BABYLON;
  20034. (function (BABYLON) {
  20035. var buildCamera = function (that, name) {
  20036. that._leftCamera.isIntermediate = true;
  20037. that.subCameras.push(that._leftCamera);
  20038. that.subCameras.push(that._rightCamera);
  20039. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20040. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20041. that._anaglyphPostProcess.onApply = function (effect) {
  20042. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20043. };
  20044. that._update();
  20045. };
  20046. var AnaglyphArcRotateCamera = (function (_super) {
  20047. __extends(AnaglyphArcRotateCamera, _super);
  20048. // ANY
  20049. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20050. _super.call(this, name, alpha, beta, radius, target, scene);
  20051. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20052. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20053. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20054. buildCamera(this, name);
  20055. }
  20056. AnaglyphArcRotateCamera.prototype._update = function () {
  20057. this._updateCamera(this._leftCamera);
  20058. this._updateCamera(this._rightCamera);
  20059. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20060. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20061. _super.prototype._update.call(this);
  20062. };
  20063. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20064. camera.beta = this.beta;
  20065. camera.radius = this.radius;
  20066. camera.minZ = this.minZ;
  20067. camera.maxZ = this.maxZ;
  20068. camera.fov = this.fov;
  20069. camera.target = this.target;
  20070. };
  20071. return AnaglyphArcRotateCamera;
  20072. })(BABYLON.ArcRotateCamera);
  20073. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20074. var AnaglyphFreeCamera = (function (_super) {
  20075. __extends(AnaglyphFreeCamera, _super);
  20076. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20077. _super.call(this, name, position, scene);
  20078. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20079. this._transformMatrix = new BABYLON.Matrix();
  20080. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20081. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20082. buildCamera(this, name);
  20083. }
  20084. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20085. var target = this.getTarget();
  20086. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20087. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20088. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20089. };
  20090. AnaglyphFreeCamera.prototype._update = function () {
  20091. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20092. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20093. this._updateCamera(this._leftCamera);
  20094. this._updateCamera(this._rightCamera);
  20095. _super.prototype._update.call(this);
  20096. };
  20097. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20098. camera.minZ = this.minZ;
  20099. camera.maxZ = this.maxZ;
  20100. camera.fov = this.fov;
  20101. camera.viewport = this.viewport;
  20102. camera.setTarget(this.getTarget());
  20103. };
  20104. return AnaglyphFreeCamera;
  20105. })(BABYLON.FreeCamera);
  20106. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20107. })(BABYLON || (BABYLON = {}));
  20108. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20109. var BABYLON;
  20110. (function (BABYLON) {
  20111. var AnaglyphPostProcess = (function (_super) {
  20112. __extends(AnaglyphPostProcess, _super);
  20113. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20114. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20115. }
  20116. return AnaglyphPostProcess;
  20117. })(BABYLON.PostProcess);
  20118. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20119. })(BABYLON || (BABYLON = {}));
  20120. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20121. var BABYLON;
  20122. (function (BABYLON) {
  20123. var Tags = (function () {
  20124. function Tags() {
  20125. }
  20126. Tags.EnableFor = function (obj) {
  20127. obj._tags = obj._tags || {};
  20128. obj.hasTags = function () {
  20129. return Tags.HasTags(obj);
  20130. };
  20131. obj.addTags = function (tagsString) {
  20132. return Tags.AddTagsTo(obj, tagsString);
  20133. };
  20134. obj.removeTags = function (tagsString) {
  20135. return Tags.RemoveTagsFrom(obj, tagsString);
  20136. };
  20137. obj.matchesTagsQuery = function (tagsQuery) {
  20138. return Tags.MatchesQuery(obj, tagsQuery);
  20139. };
  20140. };
  20141. Tags.DisableFor = function (obj) {
  20142. delete obj._tags;
  20143. delete obj.hasTags;
  20144. delete obj.addTags;
  20145. delete obj.removeTags;
  20146. delete obj.matchesTagsQuery;
  20147. };
  20148. Tags.HasTags = function (obj) {
  20149. if (!obj._tags) {
  20150. return false;
  20151. }
  20152. return !BABYLON.Tools.IsEmpty(obj._tags);
  20153. };
  20154. Tags.GetTags = function (obj) {
  20155. if (!obj._tags) {
  20156. return null;
  20157. }
  20158. return obj._tags;
  20159. };
  20160. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20161. // a tag cannot start with '||', '&&', and '!'
  20162. // it cannot contain whitespaces
  20163. Tags.AddTagsTo = function (obj, tagsString) {
  20164. if (!tagsString) {
  20165. return;
  20166. }
  20167. var tags = tagsString.split(" ");
  20168. for (var t in tags) {
  20169. Tags._AddTagTo(obj, tags[t]);
  20170. }
  20171. };
  20172. Tags._AddTagTo = function (obj, tag) {
  20173. tag = tag.trim();
  20174. if (tag === "" || tag === "true" || tag === "false") {
  20175. return;
  20176. }
  20177. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20178. return;
  20179. }
  20180. Tags.EnableFor(obj);
  20181. obj._tags[tag] = true;
  20182. };
  20183. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20184. if (!Tags.HasTags(obj)) {
  20185. return;
  20186. }
  20187. var tags = tagsString.split(" ");
  20188. for (var t in tags) {
  20189. Tags._RemoveTagFrom(obj, tags[t]);
  20190. }
  20191. };
  20192. Tags._RemoveTagFrom = function (obj, tag) {
  20193. delete obj._tags[tag];
  20194. };
  20195. Tags.MatchesQuery = function (obj, tagsQuery) {
  20196. if (tagsQuery === undefined) {
  20197. return true;
  20198. }
  20199. if (tagsQuery === "") {
  20200. return Tags.HasTags(obj);
  20201. }
  20202. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20203. return Tags.HasTags(obj) && obj._tags[r];
  20204. });
  20205. };
  20206. return Tags;
  20207. })();
  20208. BABYLON.Tags = Tags;
  20209. })(BABYLON || (BABYLON = {}));
  20210. //# sourceMappingURL=babylon.tags.js.map
  20211. var BABYLON;
  20212. (function (BABYLON) {
  20213. (function (Internals) {
  20214. var AndOrNotEvaluator = (function () {
  20215. function AndOrNotEvaluator() {
  20216. }
  20217. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20218. if (!query.match(/\([^\(\)]*\)/g)) {
  20219. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20220. } else {
  20221. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20222. // remove parenthesis
  20223. r = r.slice(1, r.length - 1);
  20224. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20225. });
  20226. }
  20227. if (query === "true") {
  20228. return true;
  20229. }
  20230. if (query === "false") {
  20231. return false;
  20232. }
  20233. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20234. };
  20235. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20236. evaluateCallback = evaluateCallback || (function (r) {
  20237. return r === "true" ? true : false;
  20238. });
  20239. var result;
  20240. var or = parenthesisContent.split("||");
  20241. for (var i in or) {
  20242. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20243. var and = ori.split("&&");
  20244. if (and.length > 1) {
  20245. for (var j = 0; j < and.length; ++j) {
  20246. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20247. if (andj !== "true" && andj !== "false") {
  20248. if (andj[0] === "!") {
  20249. result = !evaluateCallback(andj.substring(1));
  20250. } else {
  20251. result = evaluateCallback(andj);
  20252. }
  20253. } else {
  20254. result = andj === "true" ? true : false;
  20255. }
  20256. if (!result) {
  20257. ori = "false";
  20258. break;
  20259. }
  20260. }
  20261. }
  20262. if (result || ori === "true") {
  20263. result = true;
  20264. break;
  20265. }
  20266. // result equals false (or undefined)
  20267. if (ori !== "true" && ori !== "false") {
  20268. if (ori[0] === "!") {
  20269. result = !evaluateCallback(ori.substring(1));
  20270. } else {
  20271. result = evaluateCallback(ori);
  20272. }
  20273. } else {
  20274. result = ori === "true" ? true : false;
  20275. }
  20276. }
  20277. // the whole parenthesis scope is replaced by 'true' or 'false'
  20278. return result ? "true" : "false";
  20279. };
  20280. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20281. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20282. // remove whitespaces
  20283. r = r.replace(/[\s]/g, function () {
  20284. return "";
  20285. });
  20286. return r.length % 2 ? "!" : "";
  20287. });
  20288. booleanString = booleanString.trim();
  20289. if (booleanString === "!true") {
  20290. booleanString = "false";
  20291. } else if (booleanString === "!false") {
  20292. booleanString = "true";
  20293. }
  20294. return booleanString;
  20295. };
  20296. return AndOrNotEvaluator;
  20297. })();
  20298. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20299. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20300. var Internals = BABYLON.Internals;
  20301. })(BABYLON || (BABYLON = {}));
  20302. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20303. var BABYLON;
  20304. (function (BABYLON) {
  20305. var PostProcessRenderPass = (function () {
  20306. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20307. this._enabled = true;
  20308. this._refCount = 0;
  20309. this._name = name;
  20310. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20311. this.setRenderList(renderList);
  20312. this._renderTexture.onBeforeRender = beforeRender;
  20313. this._renderTexture.onAfterRender = afterRender;
  20314. this._scene = scene;
  20315. this._renderList = renderList;
  20316. }
  20317. // private
  20318. PostProcessRenderPass.prototype._incRefCount = function () {
  20319. if (this._refCount === 0) {
  20320. this._scene.customRenderTargets.push(this._renderTexture);
  20321. }
  20322. return ++this._refCount;
  20323. };
  20324. PostProcessRenderPass.prototype._decRefCount = function () {
  20325. this._refCount--;
  20326. if (this._refCount <= 0) {
  20327. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20328. }
  20329. return this._refCount;
  20330. };
  20331. PostProcessRenderPass.prototype._update = function () {
  20332. this.setRenderList(this._renderList);
  20333. };
  20334. // public
  20335. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20336. this._renderTexture.renderList = renderList;
  20337. };
  20338. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20339. return this._renderTexture;
  20340. };
  20341. return PostProcessRenderPass;
  20342. })();
  20343. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20344. })(BABYLON || (BABYLON = {}));
  20345. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20346. var BABYLON;
  20347. (function (BABYLON) {
  20348. var PostProcessRenderEffect = (function () {
  20349. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20350. this._engine = engine;
  20351. this._name = name;
  20352. this._singleInstance = singleInstance || true;
  20353. this._getPostProcess = getPostProcess;
  20354. this._cameras = [];
  20355. this._indicesForCamera = [];
  20356. this._postProcesses = {};
  20357. this._renderPasses = {};
  20358. this._renderEffectAsPasses = {};
  20359. }
  20360. PostProcessRenderEffect.prototype._update = function () {
  20361. for (var renderPassName in this._renderPasses) {
  20362. this._renderPasses[renderPassName]._update();
  20363. }
  20364. };
  20365. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20366. this._renderPasses[renderPass._name] = renderPass;
  20367. this._linkParameters();
  20368. };
  20369. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20370. delete this._renderPasses[renderPass._name];
  20371. this._linkParameters();
  20372. };
  20373. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20374. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20375. this._linkParameters();
  20376. };
  20377. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20378. for (var renderPassName in this._renderPasses) {
  20379. if (renderPassName === passName) {
  20380. return this._renderPasses[passName];
  20381. }
  20382. }
  20383. };
  20384. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20385. this._renderPasses = {};
  20386. this._linkParameters();
  20387. };
  20388. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20389. var cameraKey;
  20390. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20391. for (var i = 0; i < _cam.length; i++) {
  20392. var camera = _cam[i];
  20393. var cameraName = camera.name;
  20394. if (this._singleInstance) {
  20395. cameraKey = 0;
  20396. } else {
  20397. cameraKey = cameraName;
  20398. }
  20399. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20400. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20401. if (!this._indicesForCamera[cameraName]) {
  20402. this._indicesForCamera[cameraName] = [];
  20403. }
  20404. this._indicesForCamera[cameraName].push(index);
  20405. if (this._cameras.indexOf(camera) === -1) {
  20406. this._cameras[cameraName] = camera;
  20407. }
  20408. for (var passName in this._renderPasses) {
  20409. this._renderPasses[passName]._incRefCount();
  20410. }
  20411. }
  20412. this._linkParameters();
  20413. };
  20414. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20415. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20416. for (var i = 0; i < _cam.length; i++) {
  20417. var camera = _cam[i];
  20418. var cameraName = camera.name;
  20419. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20420. var index = this._cameras.indexOf(cameraName);
  20421. this._indicesForCamera.splice(index, 1);
  20422. this._cameras.splice(index, 1);
  20423. for (var passName in this._renderPasses) {
  20424. this._renderPasses[passName]._decRefCount();
  20425. }
  20426. }
  20427. };
  20428. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20429. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20430. for (var i = 0; i < _cam.length; i++) {
  20431. var camera = _cam[i];
  20432. var cameraName = camera.name;
  20433. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20434. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20435. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20436. }
  20437. }
  20438. for (var passName in this._renderPasses) {
  20439. this._renderPasses[passName]._incRefCount();
  20440. }
  20441. }
  20442. };
  20443. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20444. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20445. for (var i = 0; i < _cam.length; i++) {
  20446. var camera = _cam[i];
  20447. var cameraName = camera.Name;
  20448. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20449. for (var passName in this._renderPasses) {
  20450. this._renderPasses[passName]._decRefCount();
  20451. }
  20452. }
  20453. };
  20454. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20455. if (this._singleInstance) {
  20456. return this._postProcesses[0];
  20457. } else {
  20458. return this._postProcesses[camera.name];
  20459. }
  20460. };
  20461. PostProcessRenderEffect.prototype._linkParameters = function () {
  20462. var _this = this;
  20463. for (var index in this._postProcesses) {
  20464. if (this.applyParameters) {
  20465. this.applyParameters(this._postProcesses[index]);
  20466. }
  20467. this._postProcesses[index].onBeforeRender = function (effect) {
  20468. _this._linkTextures(effect);
  20469. };
  20470. }
  20471. };
  20472. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20473. for (var renderPassName in this._renderPasses) {
  20474. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20475. }
  20476. for (var renderEffectName in this._renderEffectAsPasses) {
  20477. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20478. }
  20479. };
  20480. return PostProcessRenderEffect;
  20481. })();
  20482. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20483. })(BABYLON || (BABYLON = {}));
  20484. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20485. var BABYLON;
  20486. (function (BABYLON) {
  20487. var PostProcessRenderPipeline = (function () {
  20488. function PostProcessRenderPipeline(engine, name) {
  20489. this._engine = engine;
  20490. this._name = name;
  20491. this._renderEffects = {};
  20492. this._renderEffectsForIsolatedPass = {};
  20493. this._cameras = [];
  20494. }
  20495. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20496. this._renderEffects[renderEffect._name] = renderEffect;
  20497. };
  20498. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20499. var renderEffects = this._renderEffects[renderEffectName];
  20500. if (!renderEffects) {
  20501. return;
  20502. }
  20503. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20504. };
  20505. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20506. var renderEffects = this._renderEffects[renderEffectName];
  20507. if (!renderEffects) {
  20508. return;
  20509. }
  20510. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20511. };
  20512. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20513. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20514. var indicesToDelete = [];
  20515. for (var i = 0; i < _cam.length; i++) {
  20516. var camera = _cam[i];
  20517. var cameraName = camera.name;
  20518. if (this._cameras.indexOf(camera) === -1) {
  20519. this._cameras[cameraName] = camera;
  20520. } else if (unique) {
  20521. indicesToDelete.push(i);
  20522. }
  20523. }
  20524. for (var i = 0; i < indicesToDelete.length; i++) {
  20525. cameras.splice(indicesToDelete[i], 1);
  20526. }
  20527. for (var renderEffectName in this._renderEffects) {
  20528. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20529. }
  20530. };
  20531. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20532. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20533. for (var renderEffectName in this._renderEffects) {
  20534. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20535. }
  20536. for (var i = 0; i < _cam.length; i++) {
  20537. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20538. }
  20539. };
  20540. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20541. var _this = this;
  20542. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20543. var pass = null;
  20544. for (var renderEffectName in this._renderEffects) {
  20545. pass = this._renderEffects[renderEffectName].getPass(passName);
  20546. if (pass != null) {
  20547. break;
  20548. }
  20549. }
  20550. if (pass === null) {
  20551. return;
  20552. }
  20553. for (var renderEffectName in this._renderEffects) {
  20554. this._renderEffects[renderEffectName]._disable(_cam);
  20555. }
  20556. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20557. for (var i = 0; i < _cam.length; i++) {
  20558. var camera = _cam[i];
  20559. var cameraName = camera.name;
  20560. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20561. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20562. });
  20563. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20564. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20565. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20566. }
  20567. };
  20568. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20569. var _this = this;
  20570. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20571. for (var i = 0; i < _cam.length; i++) {
  20572. var camera = _cam[i];
  20573. var cameraName = camera.name;
  20574. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20575. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20576. });
  20577. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20578. }
  20579. for (var renderEffectName in this._renderEffects) {
  20580. this._renderEffects[renderEffectName]._enable(_cam);
  20581. }
  20582. };
  20583. PostProcessRenderPipeline.prototype._update = function () {
  20584. for (var renderEffectName in this._renderEffects) {
  20585. this._renderEffects[renderEffectName]._update();
  20586. }
  20587. for (var i = 0; i < this._cameras.length; i++) {
  20588. var cameraName = this._cameras[i].name;
  20589. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20590. this._renderEffectsForIsolatedPass[cameraName]._update();
  20591. }
  20592. }
  20593. };
  20594. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20595. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20596. return PostProcessRenderPipeline;
  20597. })();
  20598. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20599. })(BABYLON || (BABYLON = {}));
  20600. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20601. var BABYLON;
  20602. (function (BABYLON) {
  20603. var PostProcessRenderPipelineManager = (function () {
  20604. function PostProcessRenderPipelineManager() {
  20605. this._renderPipelines = {};
  20606. }
  20607. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20608. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20609. };
  20610. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20611. var renderPipeline = this._renderPipelines[renderPipelineName];
  20612. if (!renderPipeline) {
  20613. return;
  20614. }
  20615. renderPipeline._attachCameras(cameras, unique);
  20616. };
  20617. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20618. var renderPipeline = this._renderPipelines[renderPipelineName];
  20619. if (!renderPipeline) {
  20620. return;
  20621. }
  20622. renderPipeline._detachCameras(cameras);
  20623. };
  20624. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20625. var renderPipeline = this._renderPipelines[renderPipelineName];
  20626. if (!renderPipeline) {
  20627. return;
  20628. }
  20629. renderPipeline._enableEffect(renderEffectName, cameras);
  20630. };
  20631. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20632. var renderPipeline = this._renderPipelines[renderPipelineName];
  20633. if (!renderPipeline) {
  20634. return;
  20635. }
  20636. renderPipeline._disableEffect(renderEffectName, cameras);
  20637. };
  20638. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20639. var renderPipeline = this._renderPipelines[renderPipelineName];
  20640. if (!renderPipeline) {
  20641. return;
  20642. }
  20643. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20644. };
  20645. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20646. var renderPipeline = this._renderPipelines[renderPipelineName];
  20647. if (!renderPipeline) {
  20648. return;
  20649. }
  20650. renderPipeline._disableDisplayOnlyPass(cameras);
  20651. };
  20652. PostProcessRenderPipelineManager.prototype.update = function () {
  20653. for (var renderPipelineName in this._renderPipelines) {
  20654. this._renderPipelines[renderPipelineName]._update();
  20655. }
  20656. };
  20657. return PostProcessRenderPipelineManager;
  20658. })();
  20659. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20660. })(BABYLON || (BABYLON = {}));
  20661. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20662. var BABYLON;
  20663. (function (BABYLON) {
  20664. var DisplayPassPostProcess = (function (_super) {
  20665. __extends(DisplayPassPostProcess, _super);
  20666. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20667. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20668. }
  20669. return DisplayPassPostProcess;
  20670. })(BABYLON.PostProcess);
  20671. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20672. })(BABYLON || (BABYLON = {}));
  20673. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20674. var BABYLON;
  20675. (function (BABYLON) {
  20676. var BoundingBoxRenderer = (function () {
  20677. function BoundingBoxRenderer(scene) {
  20678. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20679. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20680. this.showBackLines = true;
  20681. this.renderList = new BABYLON.SmartArray(32);
  20682. this._scene = scene;
  20683. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20684. attributes: ["position"],
  20685. uniforms: ["worldViewProjection", "color"]
  20686. });
  20687. var engine = this._scene.getEngine();
  20688. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20689. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20690. 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]);
  20691. }
  20692. BoundingBoxRenderer.prototype.reset = function () {
  20693. this.renderList.reset();
  20694. };
  20695. BoundingBoxRenderer.prototype.render = function () {
  20696. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20697. return;
  20698. }
  20699. var engine = this._scene.getEngine();
  20700. engine.setDepthWrite(false);
  20701. this._colorShader._preBind();
  20702. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20703. var boundingBox = this.renderList.data[boundingBoxIndex];
  20704. var min = boundingBox.minimum;
  20705. var max = boundingBox.maximum;
  20706. var diff = max.subtract(min);
  20707. var median = min.add(diff.scale(0.5));
  20708. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20709. // VBOs
  20710. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20711. if (this.showBackLines) {
  20712. // Back
  20713. engine.setDepthFunctionToGreaterOrEqual();
  20714. this._scene.resetCachedMaterial();
  20715. this._colorShader.setColor4("color", this.backColor.toColor4());
  20716. this._colorShader.bind(worldMatrix);
  20717. // Draw order
  20718. engine.draw(false, 0, 24);
  20719. }
  20720. // Front
  20721. engine.setDepthFunctionToLess();
  20722. this._scene.resetCachedMaterial();
  20723. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20724. this._colorShader.bind(worldMatrix);
  20725. // Draw order
  20726. engine.draw(false, 0, 24);
  20727. }
  20728. this._colorShader.unbind();
  20729. engine.setDepthFunctionToLessOrEqual();
  20730. engine.setDepthWrite(true);
  20731. };
  20732. BoundingBoxRenderer.prototype.dispose = function () {
  20733. this._colorShader.dispose();
  20734. this._vb.dispose();
  20735. this._scene.getEngine()._releaseBuffer(this._ib);
  20736. };
  20737. return BoundingBoxRenderer;
  20738. })();
  20739. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20740. })(BABYLON || (BABYLON = {}));
  20741. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20742. /**
  20743. * Based on jsTGALoader - Javascript loader for TGA file
  20744. * By Vincent Thibault
  20745. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20746. */
  20747. var BABYLON;
  20748. (function (BABYLON) {
  20749. (function (Internals) {
  20750. var TGATools = (function () {
  20751. function TGATools() {
  20752. }
  20753. TGATools.GetTGAHeader = function (data) {
  20754. var offset = 0;
  20755. var header = {
  20756. id_length: data[offset++],
  20757. colormap_type: data[offset++],
  20758. image_type: data[offset++],
  20759. colormap_index: data[offset++] | data[offset++] << 8,
  20760. colormap_length: data[offset++] | data[offset++] << 8,
  20761. colormap_size: data[offset++],
  20762. origin: [
  20763. data[offset++] | data[offset++] << 8,
  20764. data[offset++] | data[offset++] << 8
  20765. ],
  20766. width: data[offset++] | data[offset++] << 8,
  20767. height: data[offset++] | data[offset++] << 8,
  20768. pixel_size: data[offset++],
  20769. flags: data[offset++]
  20770. };
  20771. return header;
  20772. };
  20773. TGATools.UploadContent = function (gl, data) {
  20774. // Not enough data to contain header ?
  20775. if (data.length < 19) {
  20776. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20777. return;
  20778. }
  20779. // Read Header
  20780. var offset = 18;
  20781. var header = TGATools.GetTGAHeader(data);
  20782. // Assume it's a valid Targa file.
  20783. if (header.id_length + offset > data.length) {
  20784. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20785. return;
  20786. }
  20787. // Skip not needed data
  20788. offset += header.id_length;
  20789. var use_rle = false;
  20790. var use_pal = false;
  20791. var use_rgb = false;
  20792. var use_grey = false;
  20793. switch (header.image_type) {
  20794. case TGATools._TYPE_RLE_INDEXED:
  20795. use_rle = true;
  20796. case TGATools._TYPE_INDEXED:
  20797. use_pal = true;
  20798. break;
  20799. case TGATools._TYPE_RLE_RGB:
  20800. use_rle = true;
  20801. case TGATools._TYPE_RGB:
  20802. use_rgb = true;
  20803. break;
  20804. case TGATools._TYPE_RLE_GREY:
  20805. use_rle = true;
  20806. case TGATools._TYPE_GREY:
  20807. use_grey = true;
  20808. break;
  20809. }
  20810. var pixel_data;
  20811. var numAlphaBits = header.flags & 0xf;
  20812. var pixel_size = header.pixel_size >> 3;
  20813. var pixel_total = header.width * header.height * pixel_size;
  20814. // Read palettes
  20815. var palettes;
  20816. if (use_pal) {
  20817. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20818. }
  20819. // Read LRE
  20820. if (use_rle) {
  20821. pixel_data = new Uint8Array(pixel_total);
  20822. var c, count, i;
  20823. var localOffset = 0;
  20824. var pixels = new Uint8Array(pixel_size);
  20825. while (offset < pixel_total && localOffset < pixel_total) {
  20826. c = data[offset++];
  20827. count = (c & 0x7f) + 1;
  20828. // RLE pixels
  20829. if (c & 0x80) {
  20830. for (i = 0; i < pixel_size; ++i) {
  20831. pixels[i] = data[offset++];
  20832. }
  20833. for (i = 0; i < count; ++i) {
  20834. pixel_data.set(pixels, localOffset + i * pixel_size);
  20835. }
  20836. localOffset += pixel_size * count;
  20837. } else {
  20838. count *= pixel_size;
  20839. for (i = 0; i < count; ++i) {
  20840. pixel_data[localOffset + i] = data[offset++];
  20841. }
  20842. localOffset += count;
  20843. }
  20844. }
  20845. } else {
  20846. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  20847. }
  20848. // Load to texture
  20849. var x_start, y_start, x_step, y_step, y_end, x_end;
  20850. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  20851. default:
  20852. case TGATools._ORIGIN_UL:
  20853. x_start = 0;
  20854. x_step = 1;
  20855. x_end = header.width;
  20856. y_start = 0;
  20857. y_step = 1;
  20858. y_end = header.height;
  20859. break;
  20860. case TGATools._ORIGIN_BL:
  20861. x_start = 0;
  20862. x_step = 1;
  20863. x_end = header.width;
  20864. y_start = header.height - 1;
  20865. y_step = -1;
  20866. y_end = -1;
  20867. break;
  20868. case TGATools._ORIGIN_UR:
  20869. x_start = header.width - 1;
  20870. x_step = -1;
  20871. x_end = -1;
  20872. y_start = 0;
  20873. y_step = 1;
  20874. y_end = header.height;
  20875. break;
  20876. case TGATools._ORIGIN_BR:
  20877. x_start = header.width - 1;
  20878. x_step = -1;
  20879. x_end = -1;
  20880. y_start = header.height - 1;
  20881. y_step = -1;
  20882. y_end = -1;
  20883. break;
  20884. }
  20885. // Load the specify method
  20886. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  20887. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  20888. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  20889. };
  20890. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20891. var image = pixel_data, colormap = palettes;
  20892. var width = header.width, height = header.height;
  20893. var color, i = 0, x, y;
  20894. var imageData = new Uint8Array(width * height * 4);
  20895. for (y = y_start; y !== y_end; y += y_step) {
  20896. for (x = x_start; x !== x_end; x += x_step, i++) {
  20897. color = image[i];
  20898. imageData[(x + width * y) * 4 + 3] = 255;
  20899. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  20900. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  20901. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  20902. }
  20903. }
  20904. return imageData;
  20905. };
  20906. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20907. var image = pixel_data;
  20908. var width = header.width, height = header.height;
  20909. var color, i = 0, x, y;
  20910. var imageData = new Uint8Array(width * height * 4);
  20911. for (y = y_start; y !== y_end; y += y_step) {
  20912. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20913. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  20914. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  20915. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  20916. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  20917. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  20918. }
  20919. }
  20920. return imageData;
  20921. };
  20922. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20923. var image = pixel_data;
  20924. var width = header.width, height = header.height;
  20925. var i = 0, x, y;
  20926. var imageData = new Uint8Array(width * height * 4);
  20927. for (y = y_start; y !== y_end; y += y_step) {
  20928. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  20929. imageData[(x + width * y) * 4 + 3] = 255;
  20930. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20931. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20932. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20933. }
  20934. }
  20935. return imageData;
  20936. };
  20937. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20938. var image = pixel_data;
  20939. var width = header.width, height = header.height;
  20940. var i = 0, x, y;
  20941. var imageData = new Uint8Array(width * height * 4);
  20942. for (y = y_start; y !== y_end; y += y_step) {
  20943. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  20944. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20945. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20946. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20947. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  20948. }
  20949. }
  20950. return imageData;
  20951. };
  20952. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20953. var image = pixel_data;
  20954. var width = header.width, height = header.height;
  20955. var color, i = 0, x, y;
  20956. var imageData = new Uint8Array(width * height * 4);
  20957. for (y = y_start; y !== y_end; y += y_step) {
  20958. for (x = x_start; x !== x_end; x += x_step, i++) {
  20959. color = image[i];
  20960. imageData[(x + width * y) * 4 + 0] = color;
  20961. imageData[(x + width * y) * 4 + 1] = color;
  20962. imageData[(x + width * y) * 4 + 2] = color;
  20963. imageData[(x + width * y) * 4 + 3] = 255;
  20964. }
  20965. }
  20966. return imageData;
  20967. };
  20968. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20969. var image = pixel_data;
  20970. var width = header.width, height = header.height;
  20971. var i = 0, x, y;
  20972. var imageData = new Uint8Array(width * height * 4);
  20973. for (y = y_start; y !== y_end; y += y_step) {
  20974. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20975. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  20976. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  20977. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20978. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  20979. }
  20980. }
  20981. return imageData;
  20982. };
  20983. TGATools._TYPE_NO_DATA = 0;
  20984. TGATools._TYPE_INDEXED = 1;
  20985. TGATools._TYPE_RGB = 2;
  20986. TGATools._TYPE_GREY = 3;
  20987. TGATools._TYPE_RLE_INDEXED = 9;
  20988. TGATools._TYPE_RLE_RGB = 10;
  20989. TGATools._TYPE_RLE_GREY = 11;
  20990. TGATools._ORIGIN_MASK = 0x30;
  20991. TGATools._ORIGIN_SHIFT = 0x04;
  20992. TGATools._ORIGIN_BL = 0x00;
  20993. TGATools._ORIGIN_BR = 0x01;
  20994. TGATools._ORIGIN_UL = 0x02;
  20995. TGATools._ORIGIN_UR = 0x03;
  20996. return TGATools;
  20997. })();
  20998. Internals.TGATools = TGATools;
  20999. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21000. var Internals = BABYLON.Internals;
  21001. })(BABYLON || (BABYLON = {}));
  21002. //# sourceMappingURL=babylon.tools.tga.js.map
  21003. var BABYLON;
  21004. (function (BABYLON) {
  21005. (function (Internals) {
  21006. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21007. // All values and structures referenced from:
  21008. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21009. var DDS_MAGIC = 0x20534444;
  21010. 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;
  21011. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21012. 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;
  21013. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21014. function FourCCToInt32(value) {
  21015. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21016. }
  21017. function Int32ToFourCC(value) {
  21018. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21019. }
  21020. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21021. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21022. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21023. var headerLengthInt = 31;
  21024. // Offsets into the header array
  21025. var off_magic = 0;
  21026. var off_size = 1;
  21027. var off_flags = 2;
  21028. var off_height = 3;
  21029. var off_width = 4;
  21030. var off_mipmapCount = 7;
  21031. var off_pfFlags = 20;
  21032. var off_pfFourCC = 21;
  21033. var off_RGBbpp = 22;
  21034. var off_RMask = 23;
  21035. var off_GMask = 24;
  21036. var off_BMask = 25;
  21037. var off_AMask = 26;
  21038. var off_caps1 = 27;
  21039. var off_caps2 = 28;
  21040. ;
  21041. var DDSTools = (function () {
  21042. function DDSTools() {
  21043. }
  21044. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21045. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21046. var mipmapCount = 1;
  21047. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21048. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21049. }
  21050. return {
  21051. width: header[off_width],
  21052. height: header[off_height],
  21053. mipmapCount: mipmapCount,
  21054. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21055. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21056. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21057. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21058. };
  21059. };
  21060. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21061. var byteArray = new Uint8Array(dataLength);
  21062. var srcData = new Uint8Array(arrayBuffer);
  21063. var index = 0;
  21064. for (var y = height - 1; y >= 0; y--) {
  21065. for (var x = 0; x < width; x++) {
  21066. var srcPos = dataOffset + (x + y * width) * 4;
  21067. byteArray[index + 2] = srcData[srcPos];
  21068. byteArray[index + 1] = srcData[srcPos + 1];
  21069. byteArray[index] = srcData[srcPos + 2];
  21070. byteArray[index + 3] = srcData[srcPos + 3];
  21071. index += 4;
  21072. }
  21073. }
  21074. return byteArray;
  21075. };
  21076. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21077. var byteArray = new Uint8Array(dataLength);
  21078. var srcData = new Uint8Array(arrayBuffer);
  21079. var index = 0;
  21080. for (var y = height - 1; y >= 0; y--) {
  21081. for (var x = 0; x < width; x++) {
  21082. var srcPos = dataOffset + (x + y * width) * 3;
  21083. byteArray[index + 2] = srcData[srcPos];
  21084. byteArray[index + 1] = srcData[srcPos + 1];
  21085. byteArray[index] = srcData[srcPos + 2];
  21086. index += 3;
  21087. }
  21088. }
  21089. return byteArray;
  21090. };
  21091. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21092. var byteArray = new Uint8Array(dataLength);
  21093. var srcData = new Uint8Array(arrayBuffer);
  21094. var index = 0;
  21095. for (var y = height - 1; y >= 0; y--) {
  21096. for (var x = 0; x < width; x++) {
  21097. var srcPos = dataOffset + (x + y * width);
  21098. byteArray[index] = srcData[srcPos];
  21099. index++;
  21100. }
  21101. }
  21102. return byteArray;
  21103. };
  21104. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21105. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21106. if (header[off_magic] != DDS_MAGIC) {
  21107. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21108. return;
  21109. }
  21110. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21111. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21112. return;
  21113. }
  21114. if (info.isFourCC) {
  21115. fourCC = header[off_pfFourCC];
  21116. switch (fourCC) {
  21117. case FOURCC_DXT1:
  21118. blockBytes = 8;
  21119. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21120. break;
  21121. case FOURCC_DXT3:
  21122. blockBytes = 16;
  21123. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21124. break;
  21125. case FOURCC_DXT5:
  21126. blockBytes = 16;
  21127. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21128. break;
  21129. default:
  21130. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21131. return;
  21132. }
  21133. }
  21134. mipmapCount = 1;
  21135. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21136. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21137. }
  21138. var bpp = header[off_RGBbpp];
  21139. for (var face = 0; face < faces; face++) {
  21140. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21141. width = header[off_width];
  21142. height = header[off_height];
  21143. dataOffset = header[off_size] + 4;
  21144. for (i = 0; i < mipmapCount; ++i) {
  21145. if (info.isRGB) {
  21146. if (bpp == 24) {
  21147. dataLength = width * height * 3;
  21148. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21149. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21150. } else {
  21151. dataLength = width * height * 4;
  21152. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21153. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21154. }
  21155. } else if (info.isLuminance) {
  21156. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21157. var unpaddedRowSize = width;
  21158. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21159. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21160. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21161. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21162. } else {
  21163. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21164. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21165. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21166. }
  21167. dataOffset += dataLength;
  21168. width *= 0.5;
  21169. height *= 0.5;
  21170. width = Math.max(1.0, width);
  21171. height = Math.max(1.0, height);
  21172. }
  21173. }
  21174. };
  21175. return DDSTools;
  21176. })();
  21177. Internals.DDSTools = DDSTools;
  21178. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21179. var Internals = BABYLON.Internals;
  21180. })(BABYLON || (BABYLON = {}));
  21181. //# sourceMappingURL=babylon.tools.dds.js.map
  21182. var BABYLON;
  21183. (function (BABYLON) {
  21184. var SmartArray = (function () {
  21185. function SmartArray(capacity) {
  21186. this.length = 0;
  21187. this._duplicateId = 0;
  21188. this.data = new Array(capacity);
  21189. this._id = SmartArray._GlobalId++;
  21190. }
  21191. SmartArray.prototype.push = function (value) {
  21192. this.data[this.length++] = value;
  21193. if (this.length > this.data.length) {
  21194. this.data.length *= 2;
  21195. }
  21196. if (!value.__smartArrayFlags) {
  21197. value.__smartArrayFlags = {};
  21198. }
  21199. value.__smartArrayFlags[this._id] = this._duplicateId;
  21200. };
  21201. SmartArray.prototype.pushNoDuplicate = function (value) {
  21202. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21203. return;
  21204. }
  21205. this.push(value);
  21206. };
  21207. SmartArray.prototype.sort = function (compareFn) {
  21208. this.data.sort(compareFn);
  21209. };
  21210. SmartArray.prototype.reset = function () {
  21211. this.length = 0;
  21212. this._duplicateId++;
  21213. };
  21214. SmartArray.prototype.concat = function (array) {
  21215. if (array.length === 0) {
  21216. return;
  21217. }
  21218. if (this.length + array.length > this.data.length) {
  21219. this.data.length = (this.length + array.length) * 2;
  21220. }
  21221. for (var index = 0; index < array.length; index++) {
  21222. this.data[this.length++] = (array.data || array)[index];
  21223. }
  21224. };
  21225. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21226. if (array.length === 0) {
  21227. return;
  21228. }
  21229. if (this.length + array.length > this.data.length) {
  21230. this.data.length = (this.length + array.length) * 2;
  21231. }
  21232. for (var index = 0; index < array.length; index++) {
  21233. var item = (array.data || array)[index];
  21234. this.pushNoDuplicate(item);
  21235. }
  21236. };
  21237. SmartArray.prototype.indexOf = function (value) {
  21238. var position = this.data.indexOf(value);
  21239. if (position >= this.length) {
  21240. return -1;
  21241. }
  21242. return position;
  21243. };
  21244. SmartArray._GlobalId = 0;
  21245. return SmartArray;
  21246. })();
  21247. BABYLON.SmartArray = SmartArray;
  21248. })(BABYLON || (BABYLON = {}));
  21249. //# sourceMappingURL=babylon.smartArray.js.map
  21250. var BABYLON;
  21251. (function (BABYLON) {
  21252. var CannonJSPlugin = (function () {
  21253. function CannonJSPlugin() {
  21254. this._registeredMeshes = [];
  21255. this._physicsMaterials = [];
  21256. this.updateBodyPosition = function (mesh) {
  21257. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21258. var registeredMesh = this._registeredMeshes[index];
  21259. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21260. var body = registeredMesh.body;
  21261. var center = mesh.getBoundingInfo().boundingBox.center;
  21262. body.position.set(center.x, center.z, center.y);
  21263. body.quaternion.x = mesh.rotationQuaternion.x;
  21264. body.quaternion.z = mesh.rotationQuaternion.y;
  21265. body.quaternion.y = mesh.rotationQuaternion.z;
  21266. body.quaternion.w = -mesh.rotationQuaternion.w;
  21267. return;
  21268. }
  21269. }
  21270. };
  21271. }
  21272. CannonJSPlugin.prototype.initialize = function (iterations) {
  21273. if (typeof iterations === "undefined") { iterations = 10; }
  21274. this._world = new CANNON.World();
  21275. this._world.broadphase = new CANNON.NaiveBroadphase();
  21276. this._world.solver.iterations = iterations;
  21277. };
  21278. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21279. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21280. };
  21281. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21282. this._world.step(delta);
  21283. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21284. var registeredMesh = this._registeredMeshes[index];
  21285. if (registeredMesh.isChild) {
  21286. continue;
  21287. }
  21288. // Body position
  21289. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21290. var deltaPos = registeredMesh.delta;
  21291. if (deltaPos) {
  21292. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21293. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21294. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21295. } else {
  21296. registeredMesh.mesh.position.x = bodyX;
  21297. registeredMesh.mesh.position.y = bodyZ;
  21298. registeredMesh.mesh.position.z = bodyY;
  21299. }
  21300. if (!registeredMesh.mesh.rotationQuaternion) {
  21301. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21302. }
  21303. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21304. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21305. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21306. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21307. }
  21308. };
  21309. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21310. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21311. };
  21312. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21313. this.unregisterMesh(mesh);
  21314. mesh.computeWorldMatrix(true);
  21315. switch (impostor) {
  21316. case BABYLON.PhysicsEngine.SphereImpostor:
  21317. var bbox = mesh.getBoundingInfo().boundingBox;
  21318. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21319. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21320. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21321. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21322. case BABYLON.PhysicsEngine.BoxImpostor:
  21323. bbox = mesh.getBoundingInfo().boundingBox;
  21324. var min = bbox.minimumWorld;
  21325. var max = bbox.maximumWorld;
  21326. var box = max.subtract(min).scale(0.5);
  21327. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21328. case BABYLON.PhysicsEngine.PlaneImpostor:
  21329. return this._createPlane(mesh, options);
  21330. case BABYLON.PhysicsEngine.MeshImpostor:
  21331. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21332. var rawFaces = mesh.getIndices();
  21333. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21334. }
  21335. return null;
  21336. };
  21337. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21338. var shape = new CANNON.Sphere(radius);
  21339. if (!options) {
  21340. return shape;
  21341. }
  21342. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21343. };
  21344. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21345. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21346. if (!options) {
  21347. return shape;
  21348. }
  21349. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21350. };
  21351. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21352. var shape = new CANNON.Plane();
  21353. if (!options) {
  21354. return shape;
  21355. }
  21356. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21357. };
  21358. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21359. var verts = [], faces = [];
  21360. mesh.computeWorldMatrix(true);
  21361. for (var i = 0; i < rawVerts.length; i += 3) {
  21362. var transformed = BABYLON.Vector3.Zero();
  21363. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21364. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21365. }
  21366. for (var j = 0; j < rawFaces.length; j += 3) {
  21367. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21368. }
  21369. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21370. if (!options) {
  21371. return shape;
  21372. }
  21373. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21374. };
  21375. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21376. var index;
  21377. var mat;
  21378. for (index = 0; index < this._physicsMaterials.length; index++) {
  21379. mat = this._physicsMaterials[index];
  21380. if (mat.friction === friction && mat.restitution === restitution) {
  21381. return mat;
  21382. }
  21383. }
  21384. var currentMat = new CANNON.Material();
  21385. currentMat.friction = friction;
  21386. currentMat.restitution = restitution;
  21387. this._physicsMaterials.push(currentMat);
  21388. for (index = 0; index < this._physicsMaterials.length; index++) {
  21389. mat = this._physicsMaterials[index];
  21390. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21391. contactMaterial.contactEquationStiffness = 1e10;
  21392. contactMaterial.contactEquationRegularizationTime = 10;
  21393. this._world.addContactMaterial(contactMaterial);
  21394. }
  21395. return currentMat;
  21396. };
  21397. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21398. var initialRotation = null;
  21399. if (mesh.rotationQuaternion) {
  21400. initialRotation = mesh.rotationQuaternion.clone();
  21401. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21402. }
  21403. // The delta between the mesh position and the mesh bounding box center
  21404. var bbox = mesh.getBoundingInfo().boundingBox;
  21405. var deltaPosition = mesh.position.subtract(bbox.center);
  21406. var material = this._addMaterial(friction, restitution);
  21407. var body = new CANNON.RigidBody(mass, shape, material);
  21408. if (initialRotation) {
  21409. body.quaternion.x = initialRotation.x;
  21410. body.quaternion.z = initialRotation.y;
  21411. body.quaternion.y = initialRotation.z;
  21412. body.quaternion.w = -initialRotation.w;
  21413. }
  21414. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21415. this._world.add(body);
  21416. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21417. return body;
  21418. };
  21419. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21420. var compoundShape = new CANNON.Compound();
  21421. for (var index = 0; index < parts.length; index++) {
  21422. var mesh = parts[index].mesh;
  21423. var shape = this.registerMesh(mesh, parts[index].impostor);
  21424. if (index == 0) {
  21425. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21426. } else {
  21427. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21428. }
  21429. }
  21430. var initialMesh = parts[0].mesh;
  21431. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21432. body.parts = parts;
  21433. return body;
  21434. };
  21435. CannonJSPlugin.prototype._unbindBody = function (body) {
  21436. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21437. var registeredMesh = this._registeredMeshes[index];
  21438. if (registeredMesh.body === body) {
  21439. registeredMesh.body = null;
  21440. registeredMesh.delta = 0;
  21441. }
  21442. }
  21443. };
  21444. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21445. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21446. var registeredMesh = this._registeredMeshes[index];
  21447. if (registeredMesh.mesh === mesh) {
  21448. // Remove body
  21449. if (registeredMesh.body) {
  21450. this._world.remove(registeredMesh.body);
  21451. this._unbindBody(registeredMesh.body);
  21452. }
  21453. this._registeredMeshes.splice(index, 1);
  21454. return;
  21455. }
  21456. }
  21457. };
  21458. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21459. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21460. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21461. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21462. var registeredMesh = this._registeredMeshes[index];
  21463. if (registeredMesh.mesh === mesh) {
  21464. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21465. return;
  21466. }
  21467. }
  21468. };
  21469. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21470. var body1 = null, body2 = null;
  21471. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21472. var registeredMesh = this._registeredMeshes[index];
  21473. if (registeredMesh.mesh === mesh1) {
  21474. body1 = registeredMesh.body;
  21475. } else if (registeredMesh.mesh === mesh2) {
  21476. body2 = registeredMesh.body;
  21477. }
  21478. }
  21479. if (!body1 || !body2) {
  21480. return false;
  21481. }
  21482. 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));
  21483. this._world.addConstraint(constraint);
  21484. return true;
  21485. };
  21486. CannonJSPlugin.prototype.dispose = function () {
  21487. while (this._registeredMeshes.length) {
  21488. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21489. }
  21490. };
  21491. CannonJSPlugin.prototype.isSupported = function () {
  21492. return window.CANNON !== undefined;
  21493. };
  21494. return CannonJSPlugin;
  21495. })();
  21496. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21497. })(BABYLON || (BABYLON = {}));
  21498. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21499. var BABYLON;
  21500. (function (BABYLON) {
  21501. var Condition = (function () {
  21502. function Condition(actionManager) {
  21503. this._actionManager = actionManager;
  21504. }
  21505. Condition.prototype.isValid = function () {
  21506. return true;
  21507. };
  21508. Condition.prototype._getProperty = function (propertyPath) {
  21509. return this._actionManager._getProperty(propertyPath);
  21510. };
  21511. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21512. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21513. };
  21514. return Condition;
  21515. })();
  21516. BABYLON.Condition = Condition;
  21517. var ValueCondition = (function (_super) {
  21518. __extends(ValueCondition, _super);
  21519. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21520. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21521. _super.call(this, actionManager);
  21522. this.propertyPath = propertyPath;
  21523. this.value = value;
  21524. this.operator = operator;
  21525. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21526. this._property = this._getProperty(this.propertyPath);
  21527. }
  21528. Object.defineProperty(ValueCondition, "IsEqual", {
  21529. get: function () {
  21530. return ValueCondition._IsEqual;
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. Object.defineProperty(ValueCondition, "IsDifferent", {
  21536. get: function () {
  21537. return ValueCondition._IsDifferent;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(ValueCondition, "IsGreater", {
  21543. get: function () {
  21544. return ValueCondition._IsGreater;
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. Object.defineProperty(ValueCondition, "IsLesser", {
  21550. get: function () {
  21551. return ValueCondition._IsLesser;
  21552. },
  21553. enumerable: true,
  21554. configurable: true
  21555. });
  21556. // Methods
  21557. ValueCondition.prototype.isValid = function () {
  21558. switch (this.operator) {
  21559. case ValueCondition.IsGreater:
  21560. return this._target[this._property] > this.value;
  21561. case ValueCondition.IsLesser:
  21562. return this._target[this._property] < this.value;
  21563. case ValueCondition.IsEqual:
  21564. case ValueCondition.IsDifferent:
  21565. var check;
  21566. if (this.value.equals) {
  21567. check = this.value.equals(this._target[this._property]);
  21568. } else {
  21569. check = this.value === this._target[this._property];
  21570. }
  21571. return this.operator === ValueCondition.IsEqual ? check : !check;
  21572. }
  21573. return false;
  21574. };
  21575. ValueCondition._IsEqual = 0;
  21576. ValueCondition._IsDifferent = 1;
  21577. ValueCondition._IsGreater = 2;
  21578. ValueCondition._IsLesser = 3;
  21579. return ValueCondition;
  21580. })(Condition);
  21581. BABYLON.ValueCondition = ValueCondition;
  21582. var PredicateCondition = (function (_super) {
  21583. __extends(PredicateCondition, _super);
  21584. function PredicateCondition(actionManager, predicate) {
  21585. _super.call(this, actionManager);
  21586. this.predicate = predicate;
  21587. }
  21588. PredicateCondition.prototype.isValid = function () {
  21589. return this.predicate();
  21590. };
  21591. return PredicateCondition;
  21592. })(Condition);
  21593. BABYLON.PredicateCondition = PredicateCondition;
  21594. var StateCondition = (function (_super) {
  21595. __extends(StateCondition, _super);
  21596. function StateCondition(actionManager, target, value) {
  21597. _super.call(this, actionManager);
  21598. this.value = value;
  21599. this._target = target;
  21600. }
  21601. // Methods
  21602. StateCondition.prototype.isValid = function () {
  21603. return this._target.state === this.value;
  21604. };
  21605. return StateCondition;
  21606. })(Condition);
  21607. BABYLON.StateCondition = StateCondition;
  21608. })(BABYLON || (BABYLON = {}));
  21609. //# sourceMappingURL=babylon.condition.js.map
  21610. var BABYLON;
  21611. (function (BABYLON) {
  21612. var Action = (function () {
  21613. function Action(triggerOptions, condition) {
  21614. this.triggerOptions = triggerOptions;
  21615. if (triggerOptions.parameter) {
  21616. this.trigger = triggerOptions.trigger;
  21617. this._triggerParameter = triggerOptions.parameter;
  21618. } else {
  21619. this.trigger = triggerOptions;
  21620. }
  21621. this._nextActiveAction = this;
  21622. this._condition = condition;
  21623. }
  21624. // Methods
  21625. Action.prototype._prepare = function () {
  21626. };
  21627. Action.prototype.getTriggerParameter = function () {
  21628. return this._triggerParameter;
  21629. };
  21630. Action.prototype._executeCurrent = function (evt) {
  21631. if (this._condition) {
  21632. var currentRenderId = this._actionManager.getScene().getRenderId();
  21633. // We cache the current evaluation for the current frame
  21634. if (this._condition._evaluationId === currentRenderId) {
  21635. if (!this._condition._currentResult) {
  21636. return;
  21637. }
  21638. } else {
  21639. this._condition._evaluationId = currentRenderId;
  21640. if (!this._condition.isValid()) {
  21641. this._condition._currentResult = false;
  21642. return;
  21643. }
  21644. this._condition._currentResult = true;
  21645. }
  21646. }
  21647. this._nextActiveAction.execute(evt);
  21648. if (this._nextActiveAction._child) {
  21649. if (!this._nextActiveAction._child._actionManager) {
  21650. this._nextActiveAction._child._actionManager = this._actionManager;
  21651. }
  21652. this._nextActiveAction = this._nextActiveAction._child;
  21653. } else {
  21654. this._nextActiveAction = this;
  21655. }
  21656. };
  21657. Action.prototype.execute = function (evt) {
  21658. };
  21659. Action.prototype.then = function (action) {
  21660. this._child = action;
  21661. action._actionManager = this._actionManager;
  21662. action._prepare();
  21663. return action;
  21664. };
  21665. Action.prototype._getProperty = function (propertyPath) {
  21666. return this._actionManager._getProperty(propertyPath);
  21667. };
  21668. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21669. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21670. };
  21671. return Action;
  21672. })();
  21673. BABYLON.Action = Action;
  21674. })(BABYLON || (BABYLON = {}));
  21675. //# sourceMappingURL=babylon.action.js.map
  21676. var BABYLON;
  21677. (function (BABYLON) {
  21678. var ActionEvent = (function () {
  21679. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21680. this.source = source;
  21681. this.pointerX = pointerX;
  21682. this.pointerY = pointerY;
  21683. this.meshUnderPointer = meshUnderPointer;
  21684. this.sourceEvent = sourceEvent;
  21685. }
  21686. ActionEvent.CreateNew = function (source, evt) {
  21687. var scene = source.getScene();
  21688. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21689. };
  21690. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21691. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21692. };
  21693. return ActionEvent;
  21694. })();
  21695. BABYLON.ActionEvent = ActionEvent;
  21696. var ActionManager = (function () {
  21697. function ActionManager(scene) {
  21698. // Members
  21699. this.actions = new Array();
  21700. this._scene = scene;
  21701. scene._actionManagers.push(this);
  21702. }
  21703. Object.defineProperty(ActionManager, "NothingTrigger", {
  21704. get: function () {
  21705. return ActionManager._NothingTrigger;
  21706. },
  21707. enumerable: true,
  21708. configurable: true
  21709. });
  21710. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21711. get: function () {
  21712. return ActionManager._OnPickTrigger;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21718. get: function () {
  21719. return ActionManager._OnLeftPickTrigger;
  21720. },
  21721. enumerable: true,
  21722. configurable: true
  21723. });
  21724. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21725. get: function () {
  21726. return ActionManager._OnRightPickTrigger;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21732. get: function () {
  21733. return ActionManager._OnCenterPickTrigger;
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21739. get: function () {
  21740. return ActionManager._OnPointerOverTrigger;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21746. get: function () {
  21747. return ActionManager._OnPointerOutTrigger;
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21753. get: function () {
  21754. return ActionManager._OnEveryFrameTrigger;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21760. get: function () {
  21761. return ActionManager._OnIntersectionEnterTrigger;
  21762. },
  21763. enumerable: true,
  21764. configurable: true
  21765. });
  21766. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21767. get: function () {
  21768. return ActionManager._OnIntersectionExitTrigger;
  21769. },
  21770. enumerable: true,
  21771. configurable: true
  21772. });
  21773. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21774. get: function () {
  21775. return ActionManager._OnKeyDownTrigger;
  21776. },
  21777. enumerable: true,
  21778. configurable: true
  21779. });
  21780. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21781. get: function () {
  21782. return ActionManager._OnKeyUpTrigger;
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. // Methods
  21788. ActionManager.prototype.dispose = function () {
  21789. var index = this._scene._actionManagers.indexOf(this);
  21790. if (index > -1) {
  21791. this._scene._actionManagers.splice(index, 1);
  21792. }
  21793. };
  21794. ActionManager.prototype.getScene = function () {
  21795. return this._scene;
  21796. };
  21797. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21798. for (var index = 0; index < this.actions.length; index++) {
  21799. var action = this.actions[index];
  21800. if (triggers.indexOf(action.trigger) > -1) {
  21801. return true;
  21802. }
  21803. }
  21804. return false;
  21805. };
  21806. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21807. get: function () {
  21808. for (var index = 0; index < this.actions.length; index++) {
  21809. var action = this.actions[index];
  21810. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21811. return true;
  21812. }
  21813. }
  21814. return false;
  21815. },
  21816. enumerable: true,
  21817. configurable: true
  21818. });
  21819. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21820. get: function () {
  21821. for (var index = 0; index < this.actions.length; index++) {
  21822. var action = this.actions[index];
  21823. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21824. return true;
  21825. }
  21826. }
  21827. return false;
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. ActionManager.prototype.registerAction = function (action) {
  21833. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21834. if (this.getScene().actionManager !== this) {
  21835. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21836. return null;
  21837. }
  21838. }
  21839. this.actions.push(action);
  21840. action._actionManager = this;
  21841. action._prepare();
  21842. return action;
  21843. };
  21844. ActionManager.prototype.processTrigger = function (trigger, evt) {
  21845. for (var index = 0; index < this.actions.length; index++) {
  21846. var action = this.actions[index];
  21847. if (action.trigger === trigger) {
  21848. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  21849. var parameter = action.getTriggerParameter();
  21850. if (parameter) {
  21851. if (evt.sourceEvent.key !== parameter) {
  21852. continue;
  21853. }
  21854. }
  21855. }
  21856. action._executeCurrent(evt);
  21857. }
  21858. }
  21859. };
  21860. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  21861. var properties = propertyPath.split(".");
  21862. for (var index = 0; index < properties.length - 1; index++) {
  21863. target = target[properties[index]];
  21864. }
  21865. return target;
  21866. };
  21867. ActionManager.prototype._getProperty = function (propertyPath) {
  21868. var properties = propertyPath.split(".");
  21869. return properties[properties.length - 1];
  21870. };
  21871. ActionManager._NothingTrigger = 0;
  21872. ActionManager._OnPickTrigger = 1;
  21873. ActionManager._OnLeftPickTrigger = 2;
  21874. ActionManager._OnRightPickTrigger = 3;
  21875. ActionManager._OnCenterPickTrigger = 4;
  21876. ActionManager._OnPointerOverTrigger = 5;
  21877. ActionManager._OnPointerOutTrigger = 6;
  21878. ActionManager._OnEveryFrameTrigger = 7;
  21879. ActionManager._OnIntersectionEnterTrigger = 8;
  21880. ActionManager._OnIntersectionExitTrigger = 9;
  21881. ActionManager._OnKeyDownTrigger = 10;
  21882. ActionManager._OnKeyUpTrigger = 11;
  21883. return ActionManager;
  21884. })();
  21885. BABYLON.ActionManager = ActionManager;
  21886. })(BABYLON || (BABYLON = {}));
  21887. //# sourceMappingURL=babylon.actionManager.js.map
  21888. var BABYLON;
  21889. (function (BABYLON) {
  21890. var InterpolateValueAction = (function (_super) {
  21891. __extends(InterpolateValueAction, _super);
  21892. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  21893. if (typeof duration === "undefined") { duration = 1000; }
  21894. _super.call(this, triggerOptions, condition);
  21895. this.propertyPath = propertyPath;
  21896. this.value = value;
  21897. this.duration = duration;
  21898. this.stopOtherAnimations = stopOtherAnimations;
  21899. this._target = target;
  21900. }
  21901. InterpolateValueAction.prototype._prepare = function () {
  21902. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21903. this._property = this._getProperty(this.propertyPath);
  21904. };
  21905. InterpolateValueAction.prototype.execute = function () {
  21906. var scene = this._actionManager.getScene();
  21907. var keys = [
  21908. {
  21909. frame: 0,
  21910. value: this._target[this._property]
  21911. }, {
  21912. frame: 100,
  21913. value: this.value
  21914. }
  21915. ];
  21916. var dataType;
  21917. if (typeof this.value === "number") {
  21918. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  21919. } else if (this.value instanceof BABYLON.Color3) {
  21920. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  21921. } else if (this.value instanceof BABYLON.Vector3) {
  21922. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  21923. } else if (this.value instanceof BABYLON.Matrix) {
  21924. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  21925. } else if (this.value instanceof BABYLON.Quaternion) {
  21926. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  21927. } else {
  21928. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  21929. return;
  21930. }
  21931. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  21932. animation.setKeys(keys);
  21933. if (this.stopOtherAnimations) {
  21934. scene.stopAnimation(this._target);
  21935. }
  21936. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  21937. };
  21938. return InterpolateValueAction;
  21939. })(BABYLON.Action);
  21940. BABYLON.InterpolateValueAction = InterpolateValueAction;
  21941. })(BABYLON || (BABYLON = {}));
  21942. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  21943. var BABYLON;
  21944. (function (BABYLON) {
  21945. var SwitchBooleanAction = (function (_super) {
  21946. __extends(SwitchBooleanAction, _super);
  21947. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  21948. _super.call(this, triggerOptions, condition);
  21949. this.propertyPath = propertyPath;
  21950. this._target = target;
  21951. }
  21952. SwitchBooleanAction.prototype._prepare = function () {
  21953. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21954. this._property = this._getProperty(this.propertyPath);
  21955. };
  21956. SwitchBooleanAction.prototype.execute = function () {
  21957. this._target[this._property] = !this._target[this._property];
  21958. };
  21959. return SwitchBooleanAction;
  21960. })(BABYLON.Action);
  21961. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  21962. var SetStateAction = (function (_super) {
  21963. __extends(SetStateAction, _super);
  21964. function SetStateAction(triggerOptions, target, value, condition) {
  21965. _super.call(this, triggerOptions, condition);
  21966. this.value = value;
  21967. this._target = target;
  21968. }
  21969. SetStateAction.prototype.execute = function () {
  21970. this._target.state = this.value;
  21971. };
  21972. return SetStateAction;
  21973. })(BABYLON.Action);
  21974. BABYLON.SetStateAction = SetStateAction;
  21975. var SetValueAction = (function (_super) {
  21976. __extends(SetValueAction, _super);
  21977. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  21978. _super.call(this, triggerOptions, condition);
  21979. this.propertyPath = propertyPath;
  21980. this.value = value;
  21981. this._target = target;
  21982. }
  21983. SetValueAction.prototype._prepare = function () {
  21984. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21985. this._property = this._getProperty(this.propertyPath);
  21986. };
  21987. SetValueAction.prototype.execute = function () {
  21988. this._target[this._property] = this.value;
  21989. };
  21990. return SetValueAction;
  21991. })(BABYLON.Action);
  21992. BABYLON.SetValueAction = SetValueAction;
  21993. var IncrementValueAction = (function (_super) {
  21994. __extends(IncrementValueAction, _super);
  21995. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  21996. _super.call(this, triggerOptions, condition);
  21997. this.propertyPath = propertyPath;
  21998. this.value = value;
  21999. this._target = target;
  22000. }
  22001. IncrementValueAction.prototype._prepare = function () {
  22002. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22003. this._property = this._getProperty(this.propertyPath);
  22004. if (typeof this._target[this._property] !== "number") {
  22005. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22006. }
  22007. };
  22008. IncrementValueAction.prototype.execute = function () {
  22009. this._target[this._property] += this.value;
  22010. };
  22011. return IncrementValueAction;
  22012. })(BABYLON.Action);
  22013. BABYLON.IncrementValueAction = IncrementValueAction;
  22014. var PlayAnimationAction = (function (_super) {
  22015. __extends(PlayAnimationAction, _super);
  22016. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22017. _super.call(this, triggerOptions, condition);
  22018. this.from = from;
  22019. this.to = to;
  22020. this.loop = loop;
  22021. this._target = target;
  22022. }
  22023. PlayAnimationAction.prototype._prepare = function () {
  22024. };
  22025. PlayAnimationAction.prototype.execute = function () {
  22026. var scene = this._actionManager.getScene();
  22027. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22028. };
  22029. return PlayAnimationAction;
  22030. })(BABYLON.Action);
  22031. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22032. var StopAnimationAction = (function (_super) {
  22033. __extends(StopAnimationAction, _super);
  22034. function StopAnimationAction(triggerOptions, target, condition) {
  22035. _super.call(this, triggerOptions, condition);
  22036. this._target = target;
  22037. }
  22038. StopAnimationAction.prototype._prepare = function () {
  22039. };
  22040. StopAnimationAction.prototype.execute = function () {
  22041. var scene = this._actionManager.getScene();
  22042. scene.stopAnimation(this._target);
  22043. };
  22044. return StopAnimationAction;
  22045. })(BABYLON.Action);
  22046. BABYLON.StopAnimationAction = StopAnimationAction;
  22047. var DoNothingAction = (function (_super) {
  22048. __extends(DoNothingAction, _super);
  22049. function DoNothingAction(triggerOptions, condition) {
  22050. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22051. _super.call(this, triggerOptions, condition);
  22052. }
  22053. DoNothingAction.prototype.execute = function () {
  22054. };
  22055. return DoNothingAction;
  22056. })(BABYLON.Action);
  22057. BABYLON.DoNothingAction = DoNothingAction;
  22058. var CombineAction = (function (_super) {
  22059. __extends(CombineAction, _super);
  22060. function CombineAction(triggerOptions, children, condition) {
  22061. _super.call(this, triggerOptions, condition);
  22062. this.children = children;
  22063. }
  22064. CombineAction.prototype._prepare = function () {
  22065. for (var index = 0; index < this.children.length; index++) {
  22066. this.children[index]._actionManager = this._actionManager;
  22067. this.children[index]._prepare();
  22068. }
  22069. };
  22070. CombineAction.prototype.execute = function (evt) {
  22071. for (var index = 0; index < this.children.length; index++) {
  22072. this.children[index].execute(evt);
  22073. }
  22074. };
  22075. return CombineAction;
  22076. })(BABYLON.Action);
  22077. BABYLON.CombineAction = CombineAction;
  22078. var ExecuteCodeAction = (function (_super) {
  22079. __extends(ExecuteCodeAction, _super);
  22080. function ExecuteCodeAction(triggerOptions, func, condition) {
  22081. _super.call(this, triggerOptions, condition);
  22082. this.func = func;
  22083. }
  22084. ExecuteCodeAction.prototype.execute = function (evt) {
  22085. this.func(evt);
  22086. };
  22087. return ExecuteCodeAction;
  22088. })(BABYLON.Action);
  22089. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22090. var SetParentAction = (function (_super) {
  22091. __extends(SetParentAction, _super);
  22092. function SetParentAction(triggerOptions, target, parent, condition) {
  22093. _super.call(this, triggerOptions, condition);
  22094. this._target = target;
  22095. this._parent = parent;
  22096. }
  22097. SetParentAction.prototype._prepare = function () {
  22098. };
  22099. SetParentAction.prototype.execute = function () {
  22100. if (this._target.parent === this._parent) {
  22101. return;
  22102. }
  22103. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22104. invertParentWorldMatrix.invert();
  22105. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22106. this._target.parent = this._parent;
  22107. };
  22108. return SetParentAction;
  22109. })(BABYLON.Action);
  22110. BABYLON.SetParentAction = SetParentAction;
  22111. })(BABYLON || (BABYLON = {}));
  22112. //# sourceMappingURL=babylon.directActions.js.map
  22113. var BABYLON;
  22114. (function (BABYLON) {
  22115. var Geometry = (function () {
  22116. function Geometry(id, scene, vertexData, updatable, mesh) {
  22117. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22118. this._totalVertices = 0;
  22119. this._indices = [];
  22120. this.id = id;
  22121. this._engine = scene.getEngine();
  22122. this._meshes = [];
  22123. this._scene = scene;
  22124. // vertexData
  22125. if (vertexData) {
  22126. this.setAllVerticesData(vertexData, updatable);
  22127. } else {
  22128. this._totalVertices = 0;
  22129. this._indices = [];
  22130. }
  22131. // applyToMesh
  22132. if (mesh) {
  22133. this.applyToMesh(mesh);
  22134. }
  22135. }
  22136. Geometry.prototype.getScene = function () {
  22137. return this._scene;
  22138. };
  22139. Geometry.prototype.getEngine = function () {
  22140. return this._engine;
  22141. };
  22142. Geometry.prototype.isReady = function () {
  22143. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22144. };
  22145. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22146. vertexData.applyToGeometry(this, updatable);
  22147. };
  22148. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22149. this._vertexBuffers = this._vertexBuffers || {};
  22150. if (this._vertexBuffers[kind]) {
  22151. this._vertexBuffers[kind].dispose();
  22152. }
  22153. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22154. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22155. stride = this._vertexBuffers[kind].getStrideSize();
  22156. this._totalVertices = data.length / stride;
  22157. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22158. var meshes = this._meshes;
  22159. var numOfMeshes = meshes.length;
  22160. for (var index = 0; index < numOfMeshes; index++) {
  22161. var mesh = meshes[index];
  22162. mesh._resetPointsArrayCache();
  22163. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22164. mesh._createGlobalSubMesh();
  22165. mesh.computeWorldMatrix(true);
  22166. }
  22167. }
  22168. };
  22169. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22170. var vertexBuffer = this.getVertexBuffer(kind);
  22171. if (!vertexBuffer) {
  22172. return;
  22173. }
  22174. vertexBuffer.updateDirectly(data, offset);
  22175. };
  22176. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22177. var vertexBuffer = this.getVertexBuffer(kind);
  22178. if (!vertexBuffer) {
  22179. return;
  22180. }
  22181. vertexBuffer.update(data);
  22182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22183. var extend;
  22184. var stride = vertexBuffer.getStrideSize();
  22185. this._totalVertices = data.length / stride;
  22186. if (updateExtends) {
  22187. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22188. }
  22189. var meshes = this._meshes;
  22190. var numOfMeshes = meshes.length;
  22191. for (var index = 0; index < numOfMeshes; index++) {
  22192. var mesh = meshes[index];
  22193. mesh._resetPointsArrayCache();
  22194. if (updateExtends) {
  22195. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22196. }
  22197. }
  22198. }
  22199. };
  22200. Geometry.prototype.getTotalVertices = function () {
  22201. if (!this.isReady()) {
  22202. return 0;
  22203. }
  22204. return this._totalVertices;
  22205. };
  22206. Geometry.prototype.getVerticesData = function (kind) {
  22207. var vertexBuffer = this.getVertexBuffer(kind);
  22208. if (!vertexBuffer) {
  22209. return null;
  22210. }
  22211. return vertexBuffer.getData();
  22212. };
  22213. Geometry.prototype.getVertexBuffer = function (kind) {
  22214. if (!this.isReady()) {
  22215. return null;
  22216. }
  22217. return this._vertexBuffers[kind];
  22218. };
  22219. Geometry.prototype.getVertexBuffers = function () {
  22220. if (!this.isReady()) {
  22221. return null;
  22222. }
  22223. return this._vertexBuffers;
  22224. };
  22225. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22226. if (!this._vertexBuffers) {
  22227. if (this._delayInfo) {
  22228. return this._delayInfo.indexOf(kind) !== -1;
  22229. }
  22230. return false;
  22231. }
  22232. return this._vertexBuffers[kind] !== undefined;
  22233. };
  22234. Geometry.prototype.getVerticesDataKinds = function () {
  22235. var result = [];
  22236. if (!this._vertexBuffers && this._delayInfo) {
  22237. for (var kind in this._delayInfo) {
  22238. result.push(kind);
  22239. }
  22240. } else {
  22241. for (kind in this._vertexBuffers) {
  22242. result.push(kind);
  22243. }
  22244. }
  22245. return result;
  22246. };
  22247. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22248. if (this._indexBuffer) {
  22249. this._engine._releaseBuffer(this._indexBuffer);
  22250. }
  22251. this._indices = indices;
  22252. if (this._meshes.length !== 0 && this._indices) {
  22253. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22254. }
  22255. if (totalVertices !== undefined) {
  22256. this._totalVertices = totalVertices;
  22257. }
  22258. var meshes = this._meshes;
  22259. var numOfMeshes = meshes.length;
  22260. for (var index = 0; index < numOfMeshes; index++) {
  22261. meshes[index]._createGlobalSubMesh();
  22262. }
  22263. };
  22264. Geometry.prototype.getTotalIndices = function () {
  22265. if (!this.isReady()) {
  22266. return 0;
  22267. }
  22268. return this._indices.length;
  22269. };
  22270. Geometry.prototype.getIndices = function () {
  22271. if (!this.isReady()) {
  22272. return null;
  22273. }
  22274. return this._indices;
  22275. };
  22276. Geometry.prototype.getIndexBuffer = function () {
  22277. if (!this.isReady()) {
  22278. return null;
  22279. }
  22280. return this._indexBuffer;
  22281. };
  22282. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22283. var meshes = this._meshes;
  22284. var index = meshes.indexOf(mesh);
  22285. if (index === -1) {
  22286. return;
  22287. }
  22288. for (var kind in this._vertexBuffers) {
  22289. this._vertexBuffers[kind].dispose();
  22290. }
  22291. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22292. this._indexBuffer = null;
  22293. }
  22294. meshes.splice(index, 1);
  22295. mesh._geometry = null;
  22296. if (meshes.length == 0 && shouldDispose) {
  22297. this.dispose();
  22298. }
  22299. };
  22300. Geometry.prototype.applyToMesh = function (mesh) {
  22301. if (mesh._geometry === this) {
  22302. return;
  22303. }
  22304. var previousGeometry = mesh._geometry;
  22305. if (previousGeometry) {
  22306. previousGeometry.releaseForMesh(mesh);
  22307. }
  22308. var meshes = this._meshes;
  22309. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22310. mesh._geometry = this;
  22311. this._scene.pushGeometry(this);
  22312. meshes.push(mesh);
  22313. if (this.isReady()) {
  22314. this._applyToMesh(mesh);
  22315. } else {
  22316. mesh._boundingInfo = this._boundingInfo;
  22317. }
  22318. };
  22319. Geometry.prototype._applyToMesh = function (mesh) {
  22320. var numOfMeshes = this._meshes.length;
  22321. for (var kind in this._vertexBuffers) {
  22322. if (numOfMeshes === 1) {
  22323. this._vertexBuffers[kind].create();
  22324. }
  22325. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22326. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22327. mesh._resetPointsArrayCache();
  22328. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22329. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22330. mesh._createGlobalSubMesh();
  22331. }
  22332. }
  22333. // indexBuffer
  22334. if (numOfMeshes === 1 && this._indices) {
  22335. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22336. }
  22337. if (this._indexBuffer) {
  22338. this._indexBuffer.references = numOfMeshes;
  22339. }
  22340. };
  22341. Geometry.prototype.load = function (scene, onLoaded) {
  22342. var _this = this;
  22343. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22344. return;
  22345. }
  22346. if (this.isReady()) {
  22347. if (onLoaded) {
  22348. onLoaded();
  22349. }
  22350. return;
  22351. }
  22352. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22353. scene._addPendingData(this);
  22354. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22355. _this._delayLoadingFunction(JSON.parse(data), _this);
  22356. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22357. _this._delayInfo = [];
  22358. scene._removePendingData(_this);
  22359. var meshes = _this._meshes;
  22360. var numOfMeshes = meshes.length;
  22361. for (var index = 0; index < numOfMeshes; index++) {
  22362. _this._applyToMesh(meshes[index]);
  22363. }
  22364. if (onLoaded) {
  22365. onLoaded();
  22366. }
  22367. }, function () {
  22368. }, scene.database);
  22369. };
  22370. Geometry.prototype.dispose = function () {
  22371. var meshes = this._meshes;
  22372. var numOfMeshes = meshes.length;
  22373. for (var index = 0; index < numOfMeshes; index++) {
  22374. this.releaseForMesh(meshes[index]);
  22375. }
  22376. this._meshes = [];
  22377. for (var kind in this._vertexBuffers) {
  22378. this._vertexBuffers[kind].dispose();
  22379. }
  22380. this._vertexBuffers = [];
  22381. this._totalVertices = 0;
  22382. if (this._indexBuffer) {
  22383. this._engine._releaseBuffer(this._indexBuffer);
  22384. }
  22385. this._indexBuffer = null;
  22386. this._indices = [];
  22387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22388. this.delayLoadingFile = null;
  22389. this._delayLoadingFunction = null;
  22390. this._delayInfo = [];
  22391. this._boundingInfo = null; // todo: .dispose()
  22392. var geometries = this._scene.getGeometries();
  22393. index = geometries.indexOf(this);
  22394. if (index > -1) {
  22395. geometries.splice(index, 1);
  22396. }
  22397. };
  22398. Geometry.prototype.copy = function (id) {
  22399. var vertexData = new BABYLON.VertexData();
  22400. vertexData.indices = [];
  22401. var indices = this.getIndices();
  22402. for (var index = 0; index < indices.length; index++) {
  22403. vertexData.indices.push(indices[index]);
  22404. }
  22405. var updatable = false;
  22406. var stopChecking = false;
  22407. for (var kind in this._vertexBuffers) {
  22408. vertexData.set(this.getVerticesData(kind), kind);
  22409. if (!stopChecking) {
  22410. updatable = this.getVertexBuffer(kind).isUpdatable();
  22411. stopChecking = !updatable;
  22412. }
  22413. }
  22414. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  22415. geometry.delayLoadState = this.delayLoadState;
  22416. geometry.delayLoadingFile = this.delayLoadingFile;
  22417. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22418. for (kind in this._delayInfo) {
  22419. geometry._delayInfo = geometry._delayInfo || [];
  22420. geometry._delayInfo.push(kind);
  22421. }
  22422. // Bounding info
  22423. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22424. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22425. return geometry;
  22426. };
  22427. // Statics
  22428. Geometry.ExtractFromMesh = function (mesh, id) {
  22429. var geometry = mesh._geometry;
  22430. if (!geometry) {
  22431. return null;
  22432. }
  22433. return geometry.copy(id);
  22434. };
  22435. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22436. // be aware Math.random() could cause collisions
  22437. Geometry.RandomId = function () {
  22438. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22439. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  22440. return v.toString(16);
  22441. });
  22442. };
  22443. return Geometry;
  22444. })();
  22445. BABYLON.Geometry = Geometry;
  22446. (function (Geometry) {
  22447. /////// Primitives //////////////////////////////////////////////
  22448. (function (Primitives) {
  22449. /// Abstract class
  22450. var _Primitive = (function (_super) {
  22451. __extends(_Primitive, _super);
  22452. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22453. this._beingRegenerated = true;
  22454. this._canBeRegenerated = canBeRegenerated;
  22455. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22456. this._beingRegenerated = false;
  22457. }
  22458. _Primitive.prototype.canBeRegenerated = function () {
  22459. return this._canBeRegenerated;
  22460. };
  22461. _Primitive.prototype.regenerate = function () {
  22462. if (!this._canBeRegenerated) {
  22463. return;
  22464. }
  22465. this._beingRegenerated = true;
  22466. this.setAllVerticesData(this._regenerateVertexData(), false);
  22467. this._beingRegenerated = false;
  22468. };
  22469. _Primitive.prototype.asNewGeometry = function (id) {
  22470. return _super.prototype.copy.call(this, id);
  22471. };
  22472. // overrides
  22473. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22474. if (!this._beingRegenerated) {
  22475. return;
  22476. }
  22477. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22478. };
  22479. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22480. if (!this._beingRegenerated) {
  22481. return;
  22482. }
  22483. _super.prototype.setVerticesData.call(this, kind, data, false);
  22484. };
  22485. // to override
  22486. // protected
  22487. _Primitive.prototype._regenerateVertexData = function () {
  22488. throw new Error("Abstract method");
  22489. };
  22490. _Primitive.prototype.copy = function (id) {
  22491. throw new Error("Must be overriden in sub-classes.");
  22492. };
  22493. return _Primitive;
  22494. })(Geometry);
  22495. Primitives._Primitive = _Primitive;
  22496. var Box = (function (_super) {
  22497. __extends(Box, _super);
  22498. function Box(id, scene, size, canBeRegenerated, mesh) {
  22499. this.size = size;
  22500. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22501. }
  22502. Box.prototype._regenerateVertexData = function () {
  22503. return BABYLON.VertexData.CreateBox(this.size);
  22504. };
  22505. Box.prototype.copy = function (id) {
  22506. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22507. };
  22508. return Box;
  22509. })(_Primitive);
  22510. Primitives.Box = Box;
  22511. var Sphere = (function (_super) {
  22512. __extends(Sphere, _super);
  22513. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22514. this.segments = segments;
  22515. this.diameter = diameter;
  22516. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22517. }
  22518. Sphere.prototype._regenerateVertexData = function () {
  22519. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22520. };
  22521. Sphere.prototype.copy = function (id) {
  22522. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22523. };
  22524. return Sphere;
  22525. })(_Primitive);
  22526. Primitives.Sphere = Sphere;
  22527. var Cylinder = (function (_super) {
  22528. __extends(Cylinder, _super);
  22529. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22530. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22531. this.height = height;
  22532. this.diameterTop = diameterTop;
  22533. this.diameterBottom = diameterBottom;
  22534. this.tessellation = tessellation;
  22535. this.subdivisions = subdivisions;
  22536. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22537. }
  22538. Cylinder.prototype._regenerateVertexData = function () {
  22539. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22540. };
  22541. Cylinder.prototype.copy = function (id) {
  22542. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22543. };
  22544. return Cylinder;
  22545. })(_Primitive);
  22546. Primitives.Cylinder = Cylinder;
  22547. var Torus = (function (_super) {
  22548. __extends(Torus, _super);
  22549. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22550. this.diameter = diameter;
  22551. this.thickness = thickness;
  22552. this.tessellation = tessellation;
  22553. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22554. }
  22555. Torus.prototype._regenerateVertexData = function () {
  22556. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22557. };
  22558. Torus.prototype.copy = function (id) {
  22559. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22560. };
  22561. return Torus;
  22562. })(_Primitive);
  22563. Primitives.Torus = Torus;
  22564. var Ground = (function (_super) {
  22565. __extends(Ground, _super);
  22566. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22567. this.width = width;
  22568. this.height = height;
  22569. this.subdivisions = subdivisions;
  22570. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22571. }
  22572. Ground.prototype._regenerateVertexData = function () {
  22573. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22574. };
  22575. Ground.prototype.copy = function (id) {
  22576. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22577. };
  22578. return Ground;
  22579. })(_Primitive);
  22580. Primitives.Ground = Ground;
  22581. var TiledGround = (function (_super) {
  22582. __extends(TiledGround, _super);
  22583. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22584. this.xmin = xmin;
  22585. this.zmin = zmin;
  22586. this.xmax = xmax;
  22587. this.zmax = zmax;
  22588. this.subdivisions = subdivisions;
  22589. this.precision = precision;
  22590. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22591. }
  22592. TiledGround.prototype._regenerateVertexData = function () {
  22593. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22594. };
  22595. TiledGround.prototype.copy = function (id) {
  22596. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22597. };
  22598. return TiledGround;
  22599. })(_Primitive);
  22600. Primitives.TiledGround = TiledGround;
  22601. var Plane = (function (_super) {
  22602. __extends(Plane, _super);
  22603. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22604. this.size = size;
  22605. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22606. }
  22607. Plane.prototype._regenerateVertexData = function () {
  22608. return BABYLON.VertexData.CreatePlane(this.size);
  22609. };
  22610. Plane.prototype.copy = function (id) {
  22611. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22612. };
  22613. return Plane;
  22614. })(_Primitive);
  22615. Primitives.Plane = Plane;
  22616. var TorusKnot = (function (_super) {
  22617. __extends(TorusKnot, _super);
  22618. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22619. this.radius = radius;
  22620. this.tube = tube;
  22621. this.radialSegments = radialSegments;
  22622. this.tubularSegments = tubularSegments;
  22623. this.p = p;
  22624. this.q = q;
  22625. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22626. }
  22627. TorusKnot.prototype._regenerateVertexData = function () {
  22628. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22629. };
  22630. TorusKnot.prototype.copy = function (id) {
  22631. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22632. };
  22633. return TorusKnot;
  22634. })(_Primitive);
  22635. Primitives.TorusKnot = TorusKnot;
  22636. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22637. var Primitives = Geometry.Primitives;
  22638. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22639. var Geometry = BABYLON.Geometry;
  22640. })(BABYLON || (BABYLON = {}));
  22641. //# sourceMappingURL=babylon.geometry.js.map
  22642. var BABYLON;
  22643. (function (BABYLON) {
  22644. var Gamepads = (function () {
  22645. function Gamepads(ongamedpadconnected) {
  22646. var _this = this;
  22647. this.babylonGamepads = [];
  22648. this.oneGamepadConnected = false;
  22649. this.isMonitoring = false;
  22650. this.gamepadEventSupported = 'GamepadEvent' in window;
  22651. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22652. 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=";
  22653. this._callbackGamepadConnected = ongamedpadconnected;
  22654. if (this.gamepadSupportAvailable) {
  22655. // Checking if the gamepad connected event is supported (like in Firefox)
  22656. if (this.gamepadEventSupported) {
  22657. window.addEventListener('gamepadconnected', function (evt) {
  22658. _this._onGamepadConnected(evt);
  22659. }, false);
  22660. window.addEventListener('gamepaddisconnected', function (evt) {
  22661. _this._onGamepadDisconnected(evt);
  22662. }, false);
  22663. } else {
  22664. this._startMonitoringGamepads();
  22665. }
  22666. if (!this.oneGamepadConnected) {
  22667. this._insertGamepadDOMInstructions();
  22668. }
  22669. } else {
  22670. this._insertGamepadDOMNotSupported();
  22671. }
  22672. }
  22673. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22674. Gamepads.gamepadDOMInfo = document.createElement("div");
  22675. var buttonAImage = document.createElement("img");
  22676. buttonAImage.src = this.buttonADataURL;
  22677. var spanMessage = document.createElement("span");
  22678. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22679. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22680. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22681. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22682. Gamepads.gamepadDOMInfo.style.width = "100%";
  22683. Gamepads.gamepadDOMInfo.style.height = "48px";
  22684. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22685. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22686. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22687. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22688. buttonAImage.style.position = "relative";
  22689. buttonAImage.style.bottom = "8px";
  22690. spanMessage.style.position = "relative";
  22691. spanMessage.style.fontSize = "32px";
  22692. spanMessage.style.bottom = "32px";
  22693. spanMessage.style.color = "green";
  22694. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22695. };
  22696. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22697. Gamepads.gamepadDOMInfo = document.createElement("div");
  22698. var spanMessage = document.createElement("span");
  22699. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22700. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22701. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22702. Gamepads.gamepadDOMInfo.style.width = "100%";
  22703. Gamepads.gamepadDOMInfo.style.height = "40px";
  22704. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22705. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22706. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22707. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22708. spanMessage.style.position = "relative";
  22709. spanMessage.style.fontSize = "32px";
  22710. spanMessage.style.color = "red";
  22711. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22712. };
  22713. Gamepads.prototype.dispose = function () {
  22714. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22715. };
  22716. Gamepads.prototype._onGamepadConnected = function (evt) {
  22717. var newGamepad = this._addNewGamepad(evt.gamepad);
  22718. if (this._callbackGamepadConnected)
  22719. this._callbackGamepadConnected(newGamepad);
  22720. this._startMonitoringGamepads();
  22721. };
  22722. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22723. if (!this.oneGamepadConnected) {
  22724. this.oneGamepadConnected = true;
  22725. if (Gamepads.gamepadDOMInfo) {
  22726. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22727. Gamepads.gamepadDOMInfo = null;
  22728. }
  22729. }
  22730. var newGamepad;
  22731. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22732. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22733. } else {
  22734. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22735. }
  22736. this.babylonGamepads.push(newGamepad);
  22737. return newGamepad;
  22738. };
  22739. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22740. for (var i in this.babylonGamepads) {
  22741. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22742. this.babylonGamepads.splice(i, 1);
  22743. break;
  22744. }
  22745. }
  22746. // If no gamepads are left, stop the polling loop.
  22747. if (this.babylonGamepads.length == 0) {
  22748. this._stopMonitoringGamepads();
  22749. }
  22750. };
  22751. Gamepads.prototype._startMonitoringGamepads = function () {
  22752. if (!this.isMonitoring) {
  22753. this.isMonitoring = true;
  22754. this._checkGamepadsStatus();
  22755. }
  22756. };
  22757. Gamepads.prototype._stopMonitoringGamepads = function () {
  22758. this.isMonitoring = false;
  22759. };
  22760. Gamepads.prototype._checkGamepadsStatus = function () {
  22761. var _this = this;
  22762. // updating gamepad objects
  22763. this._updateGamepadObjects();
  22764. for (var i in this.babylonGamepads) {
  22765. this.babylonGamepads[i].update();
  22766. }
  22767. if (this.isMonitoring) {
  22768. if (window.requestAnimationFrame) {
  22769. window.requestAnimationFrame(function () {
  22770. _this._checkGamepadsStatus();
  22771. });
  22772. } else if (window.mozRequestAnimationFrame) {
  22773. window.mozRequestAnimationFrame(function () {
  22774. _this._checkGamepadsStatus();
  22775. });
  22776. } else if (window.webkitRequestAnimationFrame) {
  22777. window.webkitRequestAnimationFrame(function () {
  22778. _this._checkGamepadsStatus();
  22779. });
  22780. }
  22781. }
  22782. };
  22783. // This function is called only on Chrome, which does not yet support
  22784. // connection/disconnection events, but requires you to monitor
  22785. // an array for changes.
  22786. Gamepads.prototype._updateGamepadObjects = function () {
  22787. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22788. for (var i = 0; i < gamepads.length; i++) {
  22789. if (gamepads[i]) {
  22790. if (!(gamepads[i].index in this.babylonGamepads)) {
  22791. var newGamepad = this._addNewGamepad(gamepads[i]);
  22792. if (this._callbackGamepadConnected) {
  22793. this._callbackGamepadConnected(newGamepad);
  22794. }
  22795. } else {
  22796. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22797. }
  22798. }
  22799. }
  22800. };
  22801. return Gamepads;
  22802. })();
  22803. BABYLON.Gamepads = Gamepads;
  22804. var StickValues = (function () {
  22805. function StickValues(x, y) {
  22806. this.x = x;
  22807. this.y = y;
  22808. }
  22809. return StickValues;
  22810. })();
  22811. BABYLON.StickValues = StickValues;
  22812. var Gamepad = (function () {
  22813. function Gamepad(id, index, browserGamepad) {
  22814. this.id = id;
  22815. this.index = index;
  22816. this.browserGamepad = browserGamepad;
  22817. if (this.browserGamepad.axes.length >= 2) {
  22818. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22819. }
  22820. if (this.browserGamepad.axes.length >= 4) {
  22821. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22822. }
  22823. }
  22824. Gamepad.prototype.onleftstickchanged = function (callback) {
  22825. this._onleftstickchanged = callback;
  22826. };
  22827. Gamepad.prototype.onrightstickchanged = function (callback) {
  22828. this._onrightstickchanged = callback;
  22829. };
  22830. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22831. get: function () {
  22832. return this._leftStick;
  22833. },
  22834. set: function (newValues) {
  22835. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22836. this._onleftstickchanged(newValues);
  22837. }
  22838. this._leftStick = newValues;
  22839. },
  22840. enumerable: true,
  22841. configurable: true
  22842. });
  22843. Object.defineProperty(Gamepad.prototype, "rightStick", {
  22844. get: function () {
  22845. return this._rightStick;
  22846. },
  22847. set: function (newValues) {
  22848. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  22849. this._onrightstickchanged(newValues);
  22850. }
  22851. this._rightStick = newValues;
  22852. },
  22853. enumerable: true,
  22854. configurable: true
  22855. });
  22856. Gamepad.prototype.update = function () {
  22857. if (this._leftStick) {
  22858. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22859. }
  22860. if (this._rightStick) {
  22861. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22862. }
  22863. };
  22864. return Gamepad;
  22865. })();
  22866. BABYLON.Gamepad = Gamepad;
  22867. var GenericPad = (function (_super) {
  22868. __extends(GenericPad, _super);
  22869. function GenericPad(id, index, gamepad) {
  22870. _super.call(this, id, index, gamepad);
  22871. this.id = id;
  22872. this.index = index;
  22873. this.gamepad = gamepad;
  22874. this._buttons = new Array(gamepad.buttons.length);
  22875. }
  22876. GenericPad.prototype.onbuttondown = function (callback) {
  22877. this._onbuttondown = callback;
  22878. };
  22879. GenericPad.prototype.onbuttonup = function (callback) {
  22880. this._onbuttonup = callback;
  22881. };
  22882. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  22883. if (newValue !== currentValue) {
  22884. if (this._onbuttondown && newValue === 1) {
  22885. this._onbuttondown(buttonIndex);
  22886. }
  22887. if (this._onbuttonup && newValue === 0) {
  22888. this._onbuttonup(buttonIndex);
  22889. }
  22890. }
  22891. return newValue;
  22892. };
  22893. GenericPad.prototype.update = function () {
  22894. _super.prototype.update.call(this);
  22895. for (var index = 0; index < this._buttons.length; index++) {
  22896. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  22897. }
  22898. };
  22899. return GenericPad;
  22900. })(Gamepad);
  22901. BABYLON.GenericPad = GenericPad;
  22902. (function (Xbox360Button) {
  22903. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  22904. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  22905. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  22906. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  22907. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  22908. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  22909. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  22910. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  22911. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  22912. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  22913. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  22914. var Xbox360Button = BABYLON.Xbox360Button;
  22915. (function (Xbox360Dpad) {
  22916. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  22917. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  22918. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  22919. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  22920. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  22921. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  22922. var Xbox360Pad = (function (_super) {
  22923. __extends(Xbox360Pad, _super);
  22924. function Xbox360Pad() {
  22925. _super.apply(this, arguments);
  22926. this._leftTrigger = 0;
  22927. this._rightTrigger = 0;
  22928. this._buttonA = 0;
  22929. this._buttonB = 0;
  22930. this._buttonX = 0;
  22931. this._buttonY = 0;
  22932. this._buttonBack = 0;
  22933. this._buttonStart = 0;
  22934. this._buttonLB = 0;
  22935. this._buttonRB = 0;
  22936. this._buttonLeftStick = 0;
  22937. this._buttonRightStick = 0;
  22938. this._dPadUp = 0;
  22939. this._dPadDown = 0;
  22940. this._dPadLeft = 0;
  22941. this._dPadRight = 0;
  22942. }
  22943. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  22944. this._onlefttriggerchanged = callback;
  22945. };
  22946. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  22947. this._onrighttriggerchanged = callback;
  22948. };
  22949. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  22950. get: function () {
  22951. return this._leftTrigger;
  22952. },
  22953. set: function (newValue) {
  22954. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  22955. this._onlefttriggerchanged(newValue);
  22956. }
  22957. this._leftTrigger = newValue;
  22958. },
  22959. enumerable: true,
  22960. configurable: true
  22961. });
  22962. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  22963. get: function () {
  22964. return this._rightTrigger;
  22965. },
  22966. set: function (newValue) {
  22967. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  22968. this._onrighttriggerchanged(newValue);
  22969. }
  22970. this._rightTrigger = newValue;
  22971. },
  22972. enumerable: true,
  22973. configurable: true
  22974. });
  22975. Xbox360Pad.prototype.onbuttondown = function (callback) {
  22976. this._onbuttondown = callback;
  22977. };
  22978. Xbox360Pad.prototype.onbuttonup = function (callback) {
  22979. this._onbuttonup = callback;
  22980. };
  22981. Xbox360Pad.prototype.ondpaddown = function (callback) {
  22982. this._ondpaddown = callback;
  22983. };
  22984. Xbox360Pad.prototype.ondpadup = function (callback) {
  22985. this._ondpadup = callback;
  22986. };
  22987. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  22988. if (newValue !== currentValue) {
  22989. if (this._onbuttondown && newValue === 1) {
  22990. this._onbuttondown(buttonType);
  22991. }
  22992. if (this._onbuttonup && newValue === 0) {
  22993. this._onbuttonup(buttonType);
  22994. }
  22995. }
  22996. return newValue;
  22997. };
  22998. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  22999. if (newValue !== currentValue) {
  23000. if (this._ondpaddown && newValue === 1) {
  23001. this._ondpaddown(buttonType);
  23002. }
  23003. if (this._ondpadup && newValue === 0) {
  23004. this._ondpadup(buttonType);
  23005. }
  23006. }
  23007. return newValue;
  23008. };
  23009. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23010. get: function () {
  23011. return this._buttonA;
  23012. },
  23013. set: function (value) {
  23014. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23015. },
  23016. enumerable: true,
  23017. configurable: true
  23018. });
  23019. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23020. get: function () {
  23021. return this._buttonB;
  23022. },
  23023. set: function (value) {
  23024. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23025. },
  23026. enumerable: true,
  23027. configurable: true
  23028. });
  23029. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23030. get: function () {
  23031. return this._buttonX;
  23032. },
  23033. set: function (value) {
  23034. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23035. },
  23036. enumerable: true,
  23037. configurable: true
  23038. });
  23039. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23040. get: function () {
  23041. return this._buttonY;
  23042. },
  23043. set: function (value) {
  23044. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23045. },
  23046. enumerable: true,
  23047. configurable: true
  23048. });
  23049. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23050. get: function () {
  23051. return this._buttonStart;
  23052. },
  23053. set: function (value) {
  23054. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23055. },
  23056. enumerable: true,
  23057. configurable: true
  23058. });
  23059. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23060. get: function () {
  23061. return this._buttonBack;
  23062. },
  23063. set: function (value) {
  23064. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23065. },
  23066. enumerable: true,
  23067. configurable: true
  23068. });
  23069. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23070. get: function () {
  23071. return this._buttonLB;
  23072. },
  23073. set: function (value) {
  23074. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23075. },
  23076. enumerable: true,
  23077. configurable: true
  23078. });
  23079. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23080. get: function () {
  23081. return this._buttonRB;
  23082. },
  23083. set: function (value) {
  23084. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23085. },
  23086. enumerable: true,
  23087. configurable: true
  23088. });
  23089. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23090. get: function () {
  23091. return this._buttonLeftStick;
  23092. },
  23093. set: function (value) {
  23094. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23095. },
  23096. enumerable: true,
  23097. configurable: true
  23098. });
  23099. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23100. get: function () {
  23101. return this._buttonRightStick;
  23102. },
  23103. set: function (value) {
  23104. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23105. },
  23106. enumerable: true,
  23107. configurable: true
  23108. });
  23109. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23110. get: function () {
  23111. return this._dPadUp;
  23112. },
  23113. set: function (value) {
  23114. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23115. },
  23116. enumerable: true,
  23117. configurable: true
  23118. });
  23119. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23120. get: function () {
  23121. return this._dPadDown;
  23122. },
  23123. set: function (value) {
  23124. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23125. },
  23126. enumerable: true,
  23127. configurable: true
  23128. });
  23129. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23130. get: function () {
  23131. return this._dPadLeft;
  23132. },
  23133. set: function (value) {
  23134. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23135. },
  23136. enumerable: true,
  23137. configurable: true
  23138. });
  23139. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23140. get: function () {
  23141. return this._dPadRight;
  23142. },
  23143. set: function (value) {
  23144. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23145. },
  23146. enumerable: true,
  23147. configurable: true
  23148. });
  23149. Xbox360Pad.prototype.update = function () {
  23150. _super.prototype.update.call(this);
  23151. this.buttonA = this.browserGamepad.buttons[0].value;
  23152. this.buttonB = this.browserGamepad.buttons[1].value;
  23153. this.buttonX = this.browserGamepad.buttons[2].value;
  23154. this.buttonY = this.browserGamepad.buttons[3].value;
  23155. this.buttonLB = this.browserGamepad.buttons[4].value;
  23156. this.buttonRB = this.browserGamepad.buttons[5].value;
  23157. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23158. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23159. this.buttonBack = this.browserGamepad.buttons[8].value;
  23160. this.buttonStart = this.browserGamepad.buttons[9].value;
  23161. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23162. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23163. this.dPadUp = this.browserGamepad.buttons[12].value;
  23164. this.dPadDown = this.browserGamepad.buttons[13].value;
  23165. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23166. this.dPadRight = this.browserGamepad.buttons[15].value;
  23167. };
  23168. return Xbox360Pad;
  23169. })(Gamepad);
  23170. BABYLON.Xbox360Pad = Xbox360Pad;
  23171. })(BABYLON || (BABYLON = {}));
  23172. //# sourceMappingURL=babylon.gamepads.js.map
  23173. var BABYLON;
  23174. (function (BABYLON) {
  23175. // We're mainly based on the logic defined into the FreeCamera code
  23176. var GamepadCamera = (function (_super) {
  23177. __extends(GamepadCamera, _super);
  23178. function GamepadCamera(name, position, scene) {
  23179. var _this = this;
  23180. _super.call(this, name, position, scene);
  23181. this.angularSensibility = 200;
  23182. this.moveSensibility = 75;
  23183. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23184. _this._onNewGameConnected(gamepad);
  23185. });
  23186. }
  23187. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23188. // Only the first gamepad can control the camera
  23189. if (gamepad.index === 0) {
  23190. this._gamepad = gamepad;
  23191. }
  23192. };
  23193. GamepadCamera.prototype._checkInputs = function () {
  23194. if (!this._gamepad) {
  23195. return;
  23196. }
  23197. var LSValues = this._gamepad.leftStick;
  23198. var normalizedLX = LSValues.x / this.moveSensibility;
  23199. var normalizedLY = LSValues.y / this.moveSensibility;
  23200. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23201. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23202. var RSValues = this._gamepad.rightStick;
  23203. var normalizedRX = RSValues.x / this.angularSensibility;
  23204. var normalizedRY = RSValues.y / this.angularSensibility;
  23205. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23206. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23207. ;
  23208. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23209. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23210. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23211. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23212. };
  23213. GamepadCamera.prototype.dispose = function () {
  23214. this._gamepads.dispose();
  23215. _super.prototype.dispose.call(this);
  23216. };
  23217. return GamepadCamera;
  23218. })(BABYLON.FreeCamera);
  23219. BABYLON.GamepadCamera = GamepadCamera;
  23220. })(BABYLON || (BABYLON = {}));
  23221. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23222. var BABYLON;
  23223. (function (BABYLON) {
  23224. var LinesMesh = (function (_super) {
  23225. __extends(LinesMesh, _super);
  23226. function LinesMesh(name, scene, updatable) {
  23227. if (typeof updatable === "undefined") { updatable = false; }
  23228. _super.call(this, name, scene);
  23229. this.color = new BABYLON.Color3(1, 1, 1);
  23230. this.alpha = 1;
  23231. this._indices = new Array();
  23232. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23233. attributes: ["position"],
  23234. uniforms: ["worldViewProjection", "color"],
  23235. needAlphaBlending: true
  23236. });
  23237. }
  23238. Object.defineProperty(LinesMesh.prototype, "material", {
  23239. get: function () {
  23240. return this._colorShader;
  23241. },
  23242. enumerable: true,
  23243. configurable: true
  23244. });
  23245. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23246. get: function () {
  23247. return false;
  23248. },
  23249. enumerable: true,
  23250. configurable: true
  23251. });
  23252. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23253. get: function () {
  23254. return false;
  23255. },
  23256. enumerable: true,
  23257. configurable: true
  23258. });
  23259. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23260. var engine = this.getScene().getEngine();
  23261. var indexToBind = this._geometry.getIndexBuffer();
  23262. // VBOs
  23263. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23264. // Color
  23265. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23266. };
  23267. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23268. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23269. return;
  23270. }
  23271. var engine = this.getScene().getEngine();
  23272. // Draw order
  23273. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23274. };
  23275. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23276. return null;
  23277. };
  23278. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23279. this._colorShader.dispose();
  23280. _super.prototype.dispose.call(this, doNotRecurse);
  23281. };
  23282. return LinesMesh;
  23283. })(BABYLON.Mesh);
  23284. BABYLON.LinesMesh = LinesMesh;
  23285. })(BABYLON || (BABYLON = {}));
  23286. //# sourceMappingURL=babylon.linesMesh.js.map
  23287. var BABYLON;
  23288. (function (BABYLON) {
  23289. var OutlineRenderer = (function () {
  23290. function OutlineRenderer(scene) {
  23291. this._scene = scene;
  23292. }
  23293. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23294. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23295. var scene = this._scene;
  23296. var engine = this._scene.getEngine();
  23297. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23298. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23299. return;
  23300. }
  23301. var mesh = subMesh.getRenderingMesh();
  23302. var material = subMesh.getMaterial();
  23303. engine.enableEffect(this._effect);
  23304. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23305. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23306. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23307. // Bones
  23308. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23309. if (useBones) {
  23310. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23311. }
  23312. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23313. // Alpha test
  23314. if (material && material.needAlphaTesting()) {
  23315. var alphaTexture = material.getAlphaTestTexture();
  23316. this._effect.setTexture("diffuseSampler", alphaTexture);
  23317. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23318. }
  23319. if (hardwareInstancedRendering) {
  23320. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23321. } else {
  23322. if (batch.renderSelf[subMesh._id]) {
  23323. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23324. // Draw
  23325. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23326. }
  23327. if (batch.visibleInstances[subMesh._id]) {
  23328. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23329. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23330. this._effect.setMatrix("world", instance.getWorldMatrix());
  23331. // Draw
  23332. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23333. }
  23334. }
  23335. }
  23336. };
  23337. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23338. var defines = [];
  23339. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23340. var mesh = subMesh.getMesh();
  23341. var material = subMesh.getMaterial();
  23342. // Alpha test
  23343. if (material && material.needAlphaTesting()) {
  23344. defines.push("#define ALPHATEST");
  23345. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23346. attribs.push(BABYLON.VertexBuffer.UVKind);
  23347. defines.push("#define UV1");
  23348. }
  23349. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23350. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23351. defines.push("#define UV2");
  23352. }
  23353. }
  23354. // Bones
  23355. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23358. defines.push("#define BONES");
  23359. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23360. }
  23361. // Instances
  23362. if (useInstances) {
  23363. defines.push("#define INSTANCES");
  23364. attribs.push("world0");
  23365. attribs.push("world1");
  23366. attribs.push("world2");
  23367. attribs.push("world3");
  23368. }
  23369. // Get correct effect
  23370. var join = defines.join("\n");
  23371. if (this._cachedDefines != join) {
  23372. this._cachedDefines = join;
  23373. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23374. }
  23375. return this._effect.isReady();
  23376. };
  23377. return OutlineRenderer;
  23378. })();
  23379. BABYLON.OutlineRenderer = OutlineRenderer;
  23380. })(BABYLON || (BABYLON = {}));
  23381. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23382. var BABYLON;
  23383. (function (BABYLON) {
  23384. var MeshAssetTask = (function () {
  23385. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23386. this.name = name;
  23387. this.meshesNames = meshesNames;
  23388. this.rootUrl = rootUrl;
  23389. this.sceneFilename = sceneFilename;
  23390. this.isCompleted = false;
  23391. }
  23392. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23393. var _this = this;
  23394. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23395. _this.loadedMeshes = meshes;
  23396. _this.loadedParticleSystems = particleSystems;
  23397. _this.loadedSkeletons = skeletons;
  23398. _this.isCompleted = true;
  23399. if (_this.onSuccess) {
  23400. _this.onSuccess(_this);
  23401. }
  23402. onSuccess();
  23403. }, null, function () {
  23404. if (_this.onError) {
  23405. _this.onError(_this);
  23406. }
  23407. onError();
  23408. });
  23409. };
  23410. return MeshAssetTask;
  23411. })();
  23412. BABYLON.MeshAssetTask = MeshAssetTask;
  23413. var TextFileAssetTask = (function () {
  23414. function TextFileAssetTask(name, url) {
  23415. this.name = name;
  23416. this.url = url;
  23417. this.isCompleted = false;
  23418. }
  23419. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23420. var _this = this;
  23421. BABYLON.Tools.LoadFile(this.url, function (data) {
  23422. _this.text = data;
  23423. _this.isCompleted = true;
  23424. if (_this.onSuccess) {
  23425. _this.onSuccess(_this);
  23426. }
  23427. onSuccess();
  23428. }, null, scene.database, false, function () {
  23429. if (_this.onError) {
  23430. _this.onError(_this);
  23431. }
  23432. onError();
  23433. });
  23434. };
  23435. return TextFileAssetTask;
  23436. })();
  23437. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23438. var BinaryFileAssetTask = (function () {
  23439. function BinaryFileAssetTask(name, url) {
  23440. this.name = name;
  23441. this.url = url;
  23442. this.isCompleted = false;
  23443. }
  23444. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23445. var _this = this;
  23446. BABYLON.Tools.LoadFile(this.url, function (data) {
  23447. _this.data = data;
  23448. _this.isCompleted = true;
  23449. if (_this.onSuccess) {
  23450. _this.onSuccess(_this);
  23451. }
  23452. onSuccess();
  23453. }, null, scene.database, true, function () {
  23454. if (_this.onError) {
  23455. _this.onError(_this);
  23456. }
  23457. onError();
  23458. });
  23459. };
  23460. return BinaryFileAssetTask;
  23461. })();
  23462. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23463. var ImageAssetTask = (function () {
  23464. function ImageAssetTask(name, url) {
  23465. this.name = name;
  23466. this.url = url;
  23467. this.isCompleted = false;
  23468. }
  23469. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23470. var _this = this;
  23471. var img = new Image();
  23472. img.onload = function () {
  23473. _this.image = img;
  23474. _this.isCompleted = true;
  23475. if (_this.onSuccess) {
  23476. _this.onSuccess(_this);
  23477. }
  23478. onSuccess();
  23479. };
  23480. img.onerror = function () {
  23481. if (_this.onError) {
  23482. _this.onError(_this);
  23483. }
  23484. onError();
  23485. };
  23486. img.src = this.url;
  23487. };
  23488. return ImageAssetTask;
  23489. })();
  23490. BABYLON.ImageAssetTask = ImageAssetTask;
  23491. var TextureAssetTask = (function () {
  23492. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23493. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23494. this.name = name;
  23495. this.url = url;
  23496. this.noMipmap = noMipmap;
  23497. this.invertY = invertY;
  23498. this.samplingMode = samplingMode;
  23499. this.isCompleted = false;
  23500. }
  23501. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23502. var _this = this;
  23503. var onload = function () {
  23504. _this.isCompleted = true;
  23505. if (_this.onSuccess) {
  23506. _this.onSuccess(_this);
  23507. }
  23508. onSuccess();
  23509. };
  23510. var onerror = function () {
  23511. if (_this.onError) {
  23512. _this.onError(_this);
  23513. }
  23514. onError();
  23515. };
  23516. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23517. };
  23518. return TextureAssetTask;
  23519. })();
  23520. BABYLON.TextureAssetTask = TextureAssetTask;
  23521. var AssetsManager = (function () {
  23522. function AssetsManager(scene) {
  23523. this._tasks = new Array();
  23524. this._waitingTasksCount = 0;
  23525. this.useDefaultLoadingScreen = true;
  23526. this._scene = scene;
  23527. }
  23528. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23529. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23530. this._tasks.push(task);
  23531. return task;
  23532. };
  23533. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23534. var task = new TextFileAssetTask(taskName, url);
  23535. this._tasks.push(task);
  23536. return task;
  23537. };
  23538. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23539. var task = new BinaryFileAssetTask(taskName, url);
  23540. this._tasks.push(task);
  23541. return task;
  23542. };
  23543. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23544. var task = new ImageAssetTask(taskName, url);
  23545. this._tasks.push(task);
  23546. return task;
  23547. };
  23548. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23549. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23550. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23551. this._tasks.push(task);
  23552. return task;
  23553. };
  23554. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23555. this._waitingTasksCount--;
  23556. if (this._waitingTasksCount === 0) {
  23557. if (this.onFinish) {
  23558. this.onFinish(this._tasks);
  23559. }
  23560. this._scene.getEngine().hideLoadingUI();
  23561. }
  23562. };
  23563. AssetsManager.prototype._runTask = function (task) {
  23564. var _this = this;
  23565. task.run(this._scene, function () {
  23566. if (_this.onTaskSuccess) {
  23567. _this.onTaskSuccess(task);
  23568. }
  23569. _this._decreaseWaitingTasksCount();
  23570. }, function () {
  23571. if (_this.onTaskError) {
  23572. _this.onTaskError(task);
  23573. }
  23574. _this._decreaseWaitingTasksCount();
  23575. });
  23576. };
  23577. AssetsManager.prototype.reset = function () {
  23578. this._tasks = new Array();
  23579. return this;
  23580. };
  23581. AssetsManager.prototype.load = function () {
  23582. this._waitingTasksCount = this._tasks.length;
  23583. if (this._waitingTasksCount === 0) {
  23584. if (this.onFinish) {
  23585. this.onFinish(this._tasks);
  23586. }
  23587. return this;
  23588. }
  23589. if (this.useDefaultLoadingScreen) {
  23590. this._scene.getEngine().displayLoadingUI();
  23591. }
  23592. for (var index = 0; index < this._tasks.length; index++) {
  23593. var task = this._tasks[index];
  23594. this._runTask(task);
  23595. }
  23596. return this;
  23597. };
  23598. return AssetsManager;
  23599. })();
  23600. BABYLON.AssetsManager = AssetsManager;
  23601. })(BABYLON || (BABYLON = {}));
  23602. //# sourceMappingURL=babylon.assetsManager.js.map
  23603. var BABYLON;
  23604. (function (BABYLON) {
  23605. var VRDeviceOrientationCamera = (function (_super) {
  23606. __extends(VRDeviceOrientationCamera, _super);
  23607. function VRDeviceOrientationCamera(name, position, scene) {
  23608. _super.call(this, name, position, scene);
  23609. this._alpha = 0;
  23610. this._beta = 0;
  23611. this._gamma = 0;
  23612. }
  23613. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23614. this._alpha = +evt.alpha | 0;
  23615. this._beta = +evt.beta | 0;
  23616. this._gamma = +evt.gamma | 0;
  23617. if (this._gamma < 0) {
  23618. this._gamma = 90 + this._gamma;
  23619. } else {
  23620. // Incline it in the correct angle.
  23621. this._gamma = 270 - this._gamma;
  23622. }
  23623. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23624. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23625. this.rotation.z = this._beta / 180.0 * Math.PI;
  23626. };
  23627. return VRDeviceOrientationCamera;
  23628. })(BABYLON.OculusCamera);
  23629. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23630. })(BABYLON || (BABYLON = {}));
  23631. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23632. var BABYLON;
  23633. (function (BABYLON) {
  23634. var WebVRCamera = (function (_super) {
  23635. __extends(WebVRCamera, _super);
  23636. function WebVRCamera(name, position, scene) {
  23637. _super.call(this, name, position, scene);
  23638. this._hmdDevice = null;
  23639. this._sensorDevice = null;
  23640. this._cacheState = null;
  23641. this._cacheQuaternion = new BABYLON.Quaternion();
  23642. this._cacheRotation = BABYLON.Vector3.Zero();
  23643. this._vrEnabled = false;
  23644. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23645. }
  23646. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23647. var size = devices.length;
  23648. var i = 0;
  23649. // Reset devices.
  23650. this._sensorDevice = null;
  23651. this._hmdDevice = null;
  23652. while (i < size && this._hmdDevice === null) {
  23653. if (devices[i] instanceof HMDVRDevice) {
  23654. this._hmdDevice = devices[i];
  23655. }
  23656. i++;
  23657. }
  23658. i = 0;
  23659. while (i < size && this._sensorDevice === null) {
  23660. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23661. this._sensorDevice = devices[i];
  23662. }
  23663. i++;
  23664. }
  23665. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23666. };
  23667. WebVRCamera.prototype._update = function () {
  23668. if (this._vrEnabled) {
  23669. this._cacheState = this._sensorDevice.getState();
  23670. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23671. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23672. this.rotation.x = -this._cacheRotation.z;
  23673. this.rotation.y = -this._cacheRotation.y;
  23674. this.rotation.z = this._cacheRotation.x;
  23675. }
  23676. _super.prototype._update.call(this);
  23677. };
  23678. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23679. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23680. if (navigator.getVRDevices) {
  23681. navigator.getVRDevices().then(this._getWebVRDevices);
  23682. } else if (navigator.mozGetVRDevices) {
  23683. navigator.mozGetVRDevices(this._getWebVRDevices);
  23684. }
  23685. };
  23686. WebVRCamera.prototype.detachControl = function (element) {
  23687. _super.prototype.detachControl.call(this, element);
  23688. this._vrEnabled = false;
  23689. };
  23690. return WebVRCamera;
  23691. })(BABYLON.OculusCamera);
  23692. BABYLON.WebVRCamera = WebVRCamera;
  23693. })(BABYLON || (BABYLON = {}));
  23694. //# sourceMappingURL=babylon.webVRCamera.js.map
  23695. var BABYLON;
  23696. (function (BABYLON) {
  23697. // Standard optimizations
  23698. var SceneOptimization = (function () {
  23699. function SceneOptimization(priority) {
  23700. if (typeof priority === "undefined") { priority = 0; }
  23701. this.priority = priority;
  23702. this.apply = function (scene) {
  23703. return true;
  23704. };
  23705. }
  23706. return SceneOptimization;
  23707. })();
  23708. BABYLON.SceneOptimization = SceneOptimization;
  23709. var TextureOptimization = (function (_super) {
  23710. __extends(TextureOptimization, _super);
  23711. function TextureOptimization(priority, maximumSize) {
  23712. if (typeof priority === "undefined") { priority = 0; }
  23713. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23714. var _this = this;
  23715. _super.call(this, priority);
  23716. this.priority = priority;
  23717. this.maximumSize = maximumSize;
  23718. this.apply = function (scene) {
  23719. var allDone = true;
  23720. for (var index = 0; index < scene.textures.length; index++) {
  23721. var texture = scene.textures[index];
  23722. if (!texture.canRescale) {
  23723. continue;
  23724. }
  23725. var currentSize = texture.getSize();
  23726. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23727. if (maxDimension > _this.maximumSize) {
  23728. texture.scale(0.5);
  23729. allDone = false;
  23730. }
  23731. }
  23732. return allDone;
  23733. };
  23734. }
  23735. return TextureOptimization;
  23736. })(SceneOptimization);
  23737. BABYLON.TextureOptimization = TextureOptimization;
  23738. var HardwareScalingOptimization = (function (_super) {
  23739. __extends(HardwareScalingOptimization, _super);
  23740. function HardwareScalingOptimization(priority, maximumScale) {
  23741. if (typeof priority === "undefined") { priority = 0; }
  23742. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23743. var _this = this;
  23744. _super.call(this, priority);
  23745. this.priority = priority;
  23746. this.maximumScale = maximumScale;
  23747. this._currentScale = 1;
  23748. this.apply = function (scene) {
  23749. _this._currentScale++;
  23750. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23751. return _this._currentScale >= _this.maximumScale;
  23752. };
  23753. }
  23754. return HardwareScalingOptimization;
  23755. })(SceneOptimization);
  23756. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23757. var ShadowsOptimization = (function (_super) {
  23758. __extends(ShadowsOptimization, _super);
  23759. function ShadowsOptimization() {
  23760. _super.apply(this, arguments);
  23761. this.apply = function (scene) {
  23762. scene.shadowsEnabled = false;
  23763. return true;
  23764. };
  23765. }
  23766. return ShadowsOptimization;
  23767. })(SceneOptimization);
  23768. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23769. var PostProcessesOptimization = (function (_super) {
  23770. __extends(PostProcessesOptimization, _super);
  23771. function PostProcessesOptimization() {
  23772. _super.apply(this, arguments);
  23773. this.apply = function (scene) {
  23774. scene.postProcessesEnabled = false;
  23775. return true;
  23776. };
  23777. }
  23778. return PostProcessesOptimization;
  23779. })(SceneOptimization);
  23780. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23781. var LensFlaresOptimization = (function (_super) {
  23782. __extends(LensFlaresOptimization, _super);
  23783. function LensFlaresOptimization() {
  23784. _super.apply(this, arguments);
  23785. this.apply = function (scene) {
  23786. scene.lensFlaresEnabled = false;
  23787. return true;
  23788. };
  23789. }
  23790. return LensFlaresOptimization;
  23791. })(SceneOptimization);
  23792. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23793. var ParticlesOptimization = (function (_super) {
  23794. __extends(ParticlesOptimization, _super);
  23795. function ParticlesOptimization() {
  23796. _super.apply(this, arguments);
  23797. this.apply = function (scene) {
  23798. scene.particlesEnabled = false;
  23799. return true;
  23800. };
  23801. }
  23802. return ParticlesOptimization;
  23803. })(SceneOptimization);
  23804. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23805. var RenderTargetsOptimization = (function (_super) {
  23806. __extends(RenderTargetsOptimization, _super);
  23807. function RenderTargetsOptimization() {
  23808. _super.apply(this, arguments);
  23809. this.apply = function (scene) {
  23810. scene.renderTargetsEnabled = false;
  23811. return true;
  23812. };
  23813. }
  23814. return RenderTargetsOptimization;
  23815. })(SceneOptimization);
  23816. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23817. var MergeMeshesOptimization = (function (_super) {
  23818. __extends(MergeMeshesOptimization, _super);
  23819. function MergeMeshesOptimization() {
  23820. _super.apply(this, arguments);
  23821. var _this = this;
  23822. this._canBeMerged = function (abstractMesh) {
  23823. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23824. return false;
  23825. }
  23826. var mesh = abstractMesh;
  23827. if (!mesh.isVisible || !mesh.isEnabled()) {
  23828. return false;
  23829. }
  23830. if (mesh.instances.length > 0) {
  23831. return false;
  23832. }
  23833. if (mesh.skeleton || mesh.hasLODLevels) {
  23834. return false;
  23835. }
  23836. return true;
  23837. };
  23838. this.apply = function (scene) {
  23839. var globalPool = scene.meshes.slice(0);
  23840. var globalLength = globalPool.length;
  23841. for (var index = 0; index < globalLength; index++) {
  23842. var currentPool = new Array();
  23843. var current = globalPool[index];
  23844. // Checks
  23845. if (!_this._canBeMerged(current)) {
  23846. continue;
  23847. }
  23848. currentPool.push(current);
  23849. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  23850. var otherMesh = globalPool[subIndex];
  23851. if (!_this._canBeMerged(otherMesh)) {
  23852. continue;
  23853. }
  23854. if (otherMesh.material !== current.material) {
  23855. continue;
  23856. }
  23857. if (otherMesh.checkCollisions !== current.checkCollisions) {
  23858. continue;
  23859. }
  23860. currentPool.push(otherMesh);
  23861. globalLength--;
  23862. globalPool.splice(subIndex, 1);
  23863. subIndex--;
  23864. }
  23865. if (currentPool.length < 2) {
  23866. continue;
  23867. }
  23868. // Merge meshes
  23869. BABYLON.Mesh.MergeMeshes(currentPool);
  23870. }
  23871. return true;
  23872. };
  23873. }
  23874. return MergeMeshesOptimization;
  23875. })(SceneOptimization);
  23876. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  23877. // Options
  23878. var SceneOptimizerOptions = (function () {
  23879. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  23880. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  23881. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  23882. this.targetFrameRate = targetFrameRate;
  23883. this.trackerDuration = trackerDuration;
  23884. this.optimizations = new Array();
  23885. }
  23886. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  23887. var result = new SceneOptimizerOptions(targetFrameRate);
  23888. var priority = 0;
  23889. result.optimizations.push(new MergeMeshesOptimization(priority));
  23890. result.optimizations.push(new ShadowsOptimization(priority));
  23891. result.optimizations.push(new LensFlaresOptimization(priority));
  23892. // Next priority
  23893. priority++;
  23894. result.optimizations.push(new PostProcessesOptimization(priority));
  23895. result.optimizations.push(new ParticlesOptimization(priority));
  23896. // Next priority
  23897. priority++;
  23898. result.optimizations.push(new TextureOptimization(priority, 1024));
  23899. return result;
  23900. };
  23901. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  23902. var result = new SceneOptimizerOptions(targetFrameRate);
  23903. var priority = 0;
  23904. result.optimizations.push(new MergeMeshesOptimization(priority));
  23905. result.optimizations.push(new ShadowsOptimization(priority));
  23906. result.optimizations.push(new LensFlaresOptimization(priority));
  23907. // Next priority
  23908. priority++;
  23909. result.optimizations.push(new PostProcessesOptimization(priority));
  23910. result.optimizations.push(new ParticlesOptimization(priority));
  23911. // Next priority
  23912. priority++;
  23913. result.optimizations.push(new TextureOptimization(priority, 512));
  23914. // Next priority
  23915. priority++;
  23916. result.optimizations.push(new RenderTargetsOptimization(priority));
  23917. // Next priority
  23918. priority++;
  23919. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  23920. return result;
  23921. };
  23922. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  23923. var result = new SceneOptimizerOptions(targetFrameRate);
  23924. var priority = 0;
  23925. result.optimizations.push(new MergeMeshesOptimization(priority));
  23926. result.optimizations.push(new ShadowsOptimization(priority));
  23927. result.optimizations.push(new LensFlaresOptimization(priority));
  23928. // Next priority
  23929. priority++;
  23930. result.optimizations.push(new PostProcessesOptimization(priority));
  23931. result.optimizations.push(new ParticlesOptimization(priority));
  23932. // Next priority
  23933. priority++;
  23934. result.optimizations.push(new TextureOptimization(priority, 256));
  23935. // Next priority
  23936. priority++;
  23937. result.optimizations.push(new RenderTargetsOptimization(priority));
  23938. // Next priority
  23939. priority++;
  23940. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  23941. return result;
  23942. };
  23943. return SceneOptimizerOptions;
  23944. })();
  23945. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  23946. // Scene optimizer tool
  23947. var SceneOptimizer = (function () {
  23948. function SceneOptimizer() {
  23949. }
  23950. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  23951. // TODO: add an epsilon
  23952. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  23953. if (onSuccess) {
  23954. onSuccess();
  23955. }
  23956. return;
  23957. }
  23958. // Apply current level of optimizations
  23959. var allDone = true;
  23960. var noOptimizationApplied = true;
  23961. for (var index = 0; index < options.optimizations.length; index++) {
  23962. var optimization = options.optimizations[index];
  23963. if (optimization.priority === currentPriorityLevel) {
  23964. noOptimizationApplied = false;
  23965. allDone = allDone && optimization.apply(scene);
  23966. }
  23967. }
  23968. // If no optimization was applied, this is a failure :(
  23969. if (noOptimizationApplied) {
  23970. if (onFailure) {
  23971. onFailure();
  23972. }
  23973. return;
  23974. }
  23975. // If all optimizations were done, move to next level
  23976. if (allDone) {
  23977. currentPriorityLevel++;
  23978. }
  23979. // Let's the system running for a specific amount of time before checking FPS
  23980. scene.executeWhenReady(function () {
  23981. setTimeout(function () {
  23982. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  23983. }, options.trackerDuration);
  23984. });
  23985. };
  23986. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  23987. if (!options) {
  23988. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  23989. }
  23990. // Let's the system running for a specific amount of time before checking FPS
  23991. scene.executeWhenReady(function () {
  23992. setTimeout(function () {
  23993. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  23994. }, options.trackerDuration);
  23995. });
  23996. };
  23997. return SceneOptimizer;
  23998. })();
  23999. BABYLON.SceneOptimizer = SceneOptimizer;
  24000. })(BABYLON || (BABYLON = {}));
  24001. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24002. var BABYLON;
  24003. (function (BABYLON) {
  24004. (function (Internals) {
  24005. var MeshLODLevel = (function () {
  24006. function MeshLODLevel(distance, mesh) {
  24007. this.distance = distance;
  24008. this.mesh = mesh;
  24009. }
  24010. return MeshLODLevel;
  24011. })();
  24012. Internals.MeshLODLevel = MeshLODLevel;
  24013. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24014. var Internals = BABYLON.Internals;
  24015. })(BABYLON || (BABYLON = {}));
  24016. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24017. var BABYLON;
  24018. (function (BABYLON) {
  24019. var AudioEngine = (function () {
  24020. function AudioEngine() {
  24021. this.audioContext = null;
  24022. this.canUseWebAudio = false;
  24023. try {
  24024. if (typeof AudioContext !== 'undefined') {
  24025. this.audioContext = new AudioContext();
  24026. this.canUseWebAudio = true;
  24027. } else if (typeof webkitAudioContext !== 'undefined') {
  24028. this.audioContext = new webkitAudioContext();
  24029. this.canUseWebAudio = true;
  24030. }
  24031. } catch (e) {
  24032. this.canUseWebAudio = false;
  24033. }
  24034. // create a global volume gain node
  24035. if (this.canUseWebAudio) {
  24036. this.masterGain = this.audioContext.createGain();
  24037. this.masterGain.gain.value = 1;
  24038. this.masterGain.connect(this.audioContext.destination);
  24039. }
  24040. }
  24041. AudioEngine.prototype.getGlobalVolume = function () {
  24042. if (this.canUseWebAudio) {
  24043. return this.masterGain.gain.value;
  24044. } else {
  24045. return -1;
  24046. }
  24047. };
  24048. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24049. if (this.canUseWebAudio) {
  24050. this.masterGain.gain.value = newVolume;
  24051. }
  24052. };
  24053. return AudioEngine;
  24054. })();
  24055. BABYLON.AudioEngine = AudioEngine;
  24056. })(BABYLON || (BABYLON = {}));
  24057. //# sourceMappingURL=babylon.audioengine.js.map
  24058. var BABYLON;
  24059. (function (BABYLON) {
  24060. var Sound = (function () {
  24061. /**
  24062. * Create a sound and attach it to a scene
  24063. * @param name Name of your sound
  24064. * @param url Url to the sound to load async
  24065. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24066. * @param options Objects to provide with the current available options: autoplay, loop, distanceMax
  24067. */
  24068. function Sound(name, url, scene, readyToPlayCallback, options) {
  24069. var _this = this;
  24070. this.maxDistance = 20;
  24071. this.autoplay = false;
  24072. this.loop = false;
  24073. this.useBabylonJSAttenuation = true;
  24074. this._position = BABYLON.Vector3.Zero();
  24075. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24076. this._volume = 1;
  24077. this._isLoaded = false;
  24078. this._isReadyToPlay = false;
  24079. this._isPlaying = false;
  24080. this._isDirectional = false;
  24081. // Used if you'd like to create a directional sound.
  24082. // If not set, the sound will be omnidirectional
  24083. this._coneInnerAngle = null;
  24084. this._coneOuterAngle = null;
  24085. this._coneOuterGain = null;
  24086. this._name = name;
  24087. this._scene = scene;
  24088. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24089. this._readyToPlayCallback = readyToPlayCallback;
  24090. this._attenuationFunction = function (currentVolume, currentDistance, maxDistance) {
  24091. return currentVolume * (1 - currentDistance / maxDistance);
  24092. };
  24093. if (options) {
  24094. if (options.maxDistance) {
  24095. this.maxDistance = options.maxDistance;
  24096. }
  24097. if (options.autoplay) {
  24098. this.autoplay = options.autoplay;
  24099. }
  24100. if (options.loop) {
  24101. this.loop = options.loop;
  24102. }
  24103. if (options.volume) {
  24104. this._volume = options.volume;
  24105. }
  24106. if (options.useBabylonJSAttenuation) {
  24107. this.useBabylonJSAttenuation = options.useBabylonJSAttenuation;
  24108. }
  24109. }
  24110. if (this._audioEngine.canUseWebAudio) {
  24111. this._soundGain = this._audioEngine.audioContext.createGain();
  24112. this._soundGain.gain.value = this._volume;
  24113. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24114. this._soundPanner.connect(this._soundGain);
  24115. this._scene.mainSoundTrack.AddSound(this);
  24116. BABYLON.Tools.LoadFile(url, function (data) {
  24117. _this._soundLoaded(data);
  24118. }, null, null, true);
  24119. }
  24120. }
  24121. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24122. if (this._audioEngine.canUseWebAudio) {
  24123. this._soundGain.disconnect();
  24124. this._soundGain.connect(soundTrackAudioNode);
  24125. }
  24126. };
  24127. /**
  24128. * Transform this sound into a directional source
  24129. * @param coneInnerAngle Size of the inner cone in degree
  24130. * @param coneOuterAngle Size of the outer cone in degree
  24131. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24132. */
  24133. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24134. if (coneOuterAngle < coneInnerAngle) {
  24135. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24136. return;
  24137. }
  24138. this._coneInnerAngle = coneInnerAngle;
  24139. this._coneOuterAngle = coneOuterAngle;
  24140. this._coneOuterGain = coneOuterGain;
  24141. this._isDirectional = true;
  24142. if (this._isPlaying && this.loop) {
  24143. this.stop();
  24144. this.play();
  24145. }
  24146. };
  24147. Sound.prototype.setPosition = function (newPosition) {
  24148. this._position = newPosition;
  24149. if (this._isPlaying) {
  24150. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24151. }
  24152. };
  24153. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24154. this._localDirection = newLocalDirection;
  24155. if (this._connectedMesh && this._isPlaying) {
  24156. this._updateDirection();
  24157. }
  24158. };
  24159. Sound.prototype._updateDirection = function () {
  24160. var mat = this._connectedMesh.getWorldMatrix();
  24161. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24162. direction.normalize();
  24163. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24164. };
  24165. Sound.prototype.updateDistanceFromListener = function () {
  24166. if (this._connectedMesh) {
  24167. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24168. if (this.useBabylonJSAttenuation) {
  24169. if (distance < this.maxDistance) {
  24170. //this._soundGain.gain.value = this._volume * (1 - distance / this.maxDistance);
  24171. this._soundGain.gain.value = this._attenuationFunction(this._volume, distance, this.maxDistance);
  24172. } else {
  24173. this._soundGain.gain.value = 0;
  24174. }
  24175. }
  24176. }
  24177. };
  24178. Sound.prototype.setAttenuationFunction = function (callback) {
  24179. this._attenuationFunction = callback;
  24180. };
  24181. /**
  24182. * Play the sound
  24183. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24184. */
  24185. Sound.prototype.play = function (time) {
  24186. if (this._isReadyToPlay) {
  24187. try {
  24188. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24189. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24190. this._soundSource.buffer = this._audioBuffer;
  24191. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24192. if (this._isDirectional) {
  24193. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24194. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24195. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24196. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24197. }
  24198. this._soundSource.connect(this._soundPanner);
  24199. this._soundSource.loop = this.loop;
  24200. this._soundSource.start(startTime);
  24201. this._isPlaying = true;
  24202. } catch (ex) {
  24203. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24204. }
  24205. }
  24206. };
  24207. /**
  24208. * Stop the sound
  24209. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24210. */
  24211. Sound.prototype.stop = function (time) {
  24212. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24213. this._soundSource.stop(stopTime);
  24214. this._isPlaying = false;
  24215. };
  24216. Sound.prototype.pause = function () {
  24217. //this._soundSource.p
  24218. };
  24219. Sound.prototype.setVolume = function (newVolume) {
  24220. this._volume = newVolume;
  24221. };
  24222. Sound.prototype.getVolume = function () {
  24223. return this._volume;
  24224. };
  24225. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24226. var _this = this;
  24227. this._connectedMesh = meshToConnectTo;
  24228. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24229. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24230. });
  24231. };
  24232. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24233. this.setPosition(connectedMesh.position);
  24234. if (this._isDirectional && this._isPlaying) {
  24235. this._updateDirection();
  24236. }
  24237. };
  24238. Sound.prototype._soundLoaded = function (audioData) {
  24239. var _this = this;
  24240. this._isLoaded = true;
  24241. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24242. _this._audioBuffer = buffer;
  24243. _this._isReadyToPlay = true;
  24244. if (_this.autoplay) {
  24245. _this.play();
  24246. }
  24247. if (_this._readyToPlayCallback) {
  24248. _this._readyToPlayCallback();
  24249. }
  24250. }, function (error) {
  24251. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24252. });
  24253. };
  24254. return Sound;
  24255. })();
  24256. BABYLON.Sound = Sound;
  24257. })(BABYLON || (BABYLON = {}));
  24258. //# sourceMappingURL=babylon.sound.js.map
  24259. var BABYLON;
  24260. (function (BABYLON) {
  24261. var SoundTrack = (function () {
  24262. function SoundTrack(scene, options) {
  24263. this.id = -1;
  24264. this._isMainTrack = false;
  24265. this._scene = scene;
  24266. this._audioEngine = scene.getEngine().getAudioEngine();
  24267. this.soundCollection = new Array();
  24268. if (this._audioEngine.canUseWebAudio) {
  24269. this._trackGain = this._audioEngine.audioContext.createGain();
  24270. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24271. //this._trackConvolver.connect(this._trackGain);
  24272. this._trackGain.connect(this._audioEngine.masterGain);
  24273. if (options) {
  24274. if (options.volume) {
  24275. this._trackGain.gain.value = options.volume;
  24276. }
  24277. if (options.mainTrack) {
  24278. this._isMainTrack = options.mainTrack;
  24279. }
  24280. }
  24281. }
  24282. if (!this._isMainTrack) {
  24283. this._scene.soundTracks.push(this);
  24284. this.id = this._scene.soundTracks.length - 1;
  24285. }
  24286. }
  24287. SoundTrack.prototype.AddSound = function (sound) {
  24288. sound.connectToSoundTrackAudioNode(this._trackGain);
  24289. if (sound.soundTrackId) {
  24290. if (sound.soundTrackId === -1) {
  24291. this._scene.mainSoundTrack.RemoveSound(sound);
  24292. } else {
  24293. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24294. }
  24295. }
  24296. this.soundCollection.push(sound);
  24297. sound.soundTrackId = this.id;
  24298. };
  24299. SoundTrack.prototype.RemoveSound = function (sound) {
  24300. var index = this.soundCollection.indexOf(sound);
  24301. if (index !== -1) {
  24302. this.soundCollection.splice(index, 1);
  24303. }
  24304. };
  24305. SoundTrack.prototype.setVolume = function (newVolume) {
  24306. if (this._audioEngine.canUseWebAudio) {
  24307. this._trackGain.gain.value = newVolume;
  24308. }
  24309. };
  24310. return SoundTrack;
  24311. })();
  24312. BABYLON.SoundTrack = SoundTrack;
  24313. })(BABYLON || (BABYLON = {}));
  24314. //# sourceMappingURL=babylon.soundtrack.js.map
  24315. var BABYLON;
  24316. (function (BABYLON) {
  24317. var DebugLayer = (function () {
  24318. function DebugLayer(scene) {
  24319. var _this = this;
  24320. this._enabled = false;
  24321. this._labelsEnabled = false;
  24322. this._displayStatistics = true;
  24323. this._displayTree = false;
  24324. this._displayLogs = false;
  24325. this._identityMatrix = BABYLON.Matrix.Identity();
  24326. this.axisRatio = 0.02;
  24327. this.accentColor = "orange";
  24328. this._scene = scene;
  24329. this._syncPositions = function () {
  24330. var engine = _this._scene.getEngine();
  24331. var canvasRect = engine.getRenderingCanvasClientRect();
  24332. if (_this._showUI) {
  24333. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24334. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24335. _this._statsDiv.style.width = "300px";
  24336. _this._statsDiv.style.height = "360px";
  24337. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24338. _this._optionsDiv.style.left = "0px";
  24339. _this._optionsDiv.style.top = "10px";
  24340. _this._optionsDiv.style.width = "200px";
  24341. _this._optionsDiv.style.height = "auto";
  24342. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24343. _this._logDiv.style.left = "0px";
  24344. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24345. _this._logDiv.style.width = "600px";
  24346. _this._logDiv.style.height = "160px";
  24347. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24348. _this._treeDiv.style.top = "10px";
  24349. _this._treeDiv.style.width = "300px";
  24350. _this._treeDiv.style.height = "auto";
  24351. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24352. }
  24353. _this._globalDiv.style.left = canvasRect.left + "px";
  24354. _this._globalDiv.style.top = canvasRect.top + "px";
  24355. _this._drawingCanvas.style.left = "0px";
  24356. _this._drawingCanvas.style.top = "0px";
  24357. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24358. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24359. var devicePixelRatio = window.devicePixelRatio || 1;
  24360. var context = _this._drawingContext;
  24361. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24362. _this._ratio = devicePixelRatio / backingStoreRatio;
  24363. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24364. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24365. };
  24366. this._onCanvasClick = function (evt) {
  24367. _this._clickPosition = {
  24368. x: evt.clientX * _this._ratio,
  24369. y: evt.clientY * _this._ratio
  24370. };
  24371. };
  24372. this._syncData = function () {
  24373. if (_this._showUI) {
  24374. if (_this._displayStatistics) {
  24375. _this._displayStats();
  24376. _this._statsDiv.style.display = "";
  24377. } else {
  24378. _this._statsDiv.style.display = "none";
  24379. }
  24380. if (_this._displayLogs) {
  24381. _this._logDiv.style.display = "";
  24382. } else {
  24383. _this._logDiv.style.display = "none";
  24384. }
  24385. if (_this._displayTree) {
  24386. _this._treeDiv.style.display = "";
  24387. if (_this._needToRefreshMeshesTree) {
  24388. _this._needToRefreshMeshesTree = false;
  24389. _this._refreshMeshesTreeContent();
  24390. }
  24391. } else {
  24392. _this._treeDiv.style.display = "none";
  24393. }
  24394. }
  24395. if (_this._labelsEnabled || !_this._showUI) {
  24396. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24397. var engine = _this._scene.getEngine();
  24398. var viewport = _this._scene.activeCamera.viewport;
  24399. var globalViewport = viewport.toGlobal(engine);
  24400. // Meshes
  24401. var meshes = _this._scene.getActiveMeshes();
  24402. for (var index = 0; index < meshes.length; index++) {
  24403. var mesh = meshes.data[index];
  24404. var position = mesh.getBoundingInfo().boundingSphere.center;
  24405. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24406. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24407. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24408. }
  24409. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24410. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24411. mesh.renderOverlay = !mesh.renderOverlay;
  24412. }, function () {
  24413. return mesh.renderOverlay ? 'red' : 'black';
  24414. });
  24415. }
  24416. }
  24417. // Cameras
  24418. var cameras = _this._scene.cameras;
  24419. for (index = 0; index < cameras.length; index++) {
  24420. var camera = cameras[index];
  24421. if (camera === _this._scene.activeCamera) {
  24422. continue;
  24423. }
  24424. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24425. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24426. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24427. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24428. _this._scene.activeCamera = camera;
  24429. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24430. }, function () {
  24431. return "purple";
  24432. });
  24433. }
  24434. }
  24435. // Lights
  24436. var lights = _this._scene.lights;
  24437. for (index = 0; index < lights.length; index++) {
  24438. var light = lights[index];
  24439. if (light.position) {
  24440. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24441. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24442. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24443. light.setEnabled(!light.isEnabled());
  24444. }, function () {
  24445. return light.isEnabled() ? "orange" : "gray";
  24446. });
  24447. }
  24448. }
  24449. }
  24450. }
  24451. _this._clickPosition = undefined;
  24452. };
  24453. }
  24454. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24455. while (this._treeSubsetDiv.hasChildNodes()) {
  24456. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24457. }
  24458. // Add meshes
  24459. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24460. sortedArray.sort(function (a, b) {
  24461. if (a.name === b.name) {
  24462. return 0;
  24463. }
  24464. return (a.name > b.name) ? 1 : -1;
  24465. });
  24466. for (var index = 0; index < sortedArray.length; index++) {
  24467. var mesh = sortedArray[index];
  24468. if (!mesh.isEnabled()) {
  24469. continue;
  24470. }
  24471. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24472. m.isVisible = element.checked;
  24473. }, mesh);
  24474. }
  24475. };
  24476. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24477. this._drawingContext.beginPath();
  24478. this._drawingContext.moveTo(zero.x, zero.y);
  24479. this._drawingContext.lineTo(unit.x, unit.y);
  24480. this._drawingContext.strokeStyle = color;
  24481. this._drawingContext.lineWidth = 4;
  24482. this._drawingContext.stroke();
  24483. this._drawingContext.font = "normal 14px Segoe UI";
  24484. this._drawingContext.fillStyle = color;
  24485. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24486. };
  24487. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24488. var position = mesh.getBoundingInfo().boundingSphere.center;
  24489. var worldMatrix = mesh.getWorldMatrix();
  24490. 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());
  24491. var unit = (unprojectedVector.subtract(position)).length();
  24492. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24493. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24494. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24495. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24496. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24497. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24498. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24499. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24500. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24501. };
  24502. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24503. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24504. this._drawingContext.font = "normal 12px Segoe UI";
  24505. var textMetrics = this._drawingContext.measureText(text);
  24506. var centerX = projectedPosition.x - textMetrics.width / 2;
  24507. var centerY = projectedPosition.y;
  24508. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24509. onClick();
  24510. }
  24511. this._drawingContext.beginPath();
  24512. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24513. this._drawingContext.fillStyle = getFillStyle();
  24514. this._drawingContext.globalAlpha = 0.5;
  24515. this._drawingContext.fill();
  24516. this._drawingContext.globalAlpha = 1.0;
  24517. this._drawingContext.strokeStyle = '#FFFFFF';
  24518. this._drawingContext.lineWidth = 1;
  24519. this._drawingContext.stroke();
  24520. this._drawingContext.fillStyle = "#FFFFFF";
  24521. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24522. this._drawingContext.beginPath();
  24523. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24524. this._drawingContext.fill();
  24525. }
  24526. };
  24527. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24528. if (!this._clickPosition) {
  24529. return false;
  24530. }
  24531. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24532. return false;
  24533. }
  24534. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24535. return false;
  24536. }
  24537. return true;
  24538. };
  24539. DebugLayer.prototype.isVisible = function () {
  24540. return this._enabled;
  24541. };
  24542. DebugLayer.prototype.hide = function () {
  24543. if (!this._enabled) {
  24544. return;
  24545. }
  24546. this._enabled = false;
  24547. var engine = this._scene.getEngine();
  24548. this._scene.unregisterAfterRender(this._syncData);
  24549. document.body.removeChild(this._globalDiv);
  24550. window.removeEventListener("resize", this._syncPositions);
  24551. this._scene.forceShowBoundingBoxes = false;
  24552. this._scene.forceWireframe = false;
  24553. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24554. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24555. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24556. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24557. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24558. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24559. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24560. this._scene.shadowsEnabled = true;
  24561. this._scene.particlesEnabled = true;
  24562. this._scene.postProcessesEnabled = true;
  24563. this._scene.collisionsEnabled = true;
  24564. this._scene.lightsEnabled = true;
  24565. this._scene.texturesEnabled = true;
  24566. this._scene.lensFlaresEnabled = true;
  24567. this._scene.proceduralTexturesEnabled = true;
  24568. this._scene.renderTargetsEnabled = true;
  24569. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24570. };
  24571. DebugLayer.prototype.show = function (showUI) {
  24572. if (typeof showUI === "undefined") { showUI = true; }
  24573. if (this._enabled) {
  24574. return;
  24575. }
  24576. this._enabled = true;
  24577. this._showUI = showUI;
  24578. var engine = this._scene.getEngine();
  24579. this._globalDiv = document.createElement("div");
  24580. document.body.appendChild(this._globalDiv);
  24581. this._generateDOMelements();
  24582. window.addEventListener("resize", this._syncPositions);
  24583. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24584. this._syncPositions();
  24585. this._scene.registerAfterRender(this._syncData);
  24586. };
  24587. DebugLayer.prototype._clearLabels = function () {
  24588. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24589. for (var index = 0; index < this._scene.meshes.length; index++) {
  24590. var mesh = this._scene.meshes[index];
  24591. mesh.renderOverlay = false;
  24592. }
  24593. };
  24594. DebugLayer.prototype._generateheader = function (root, text) {
  24595. var header = document.createElement("div");
  24596. header.innerHTML = text + "&nbsp;";
  24597. header.style.textAlign = "right";
  24598. header.style.width = "100%";
  24599. header.style.color = "white";
  24600. header.style.backgroundColor = "Black";
  24601. header.style.padding = "5px 5px 4px 0px";
  24602. header.style.marginLeft = "-5px";
  24603. header.style.fontWeight = "bold";
  24604. root.appendChild(header);
  24605. };
  24606. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24607. var label = document.createElement("label");
  24608. label.innerHTML = title;
  24609. label.style.color = color;
  24610. root.appendChild(label);
  24611. root.appendChild(document.createElement("br"));
  24612. };
  24613. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24614. if (typeof tag === "undefined") { tag = null; }
  24615. var label = document.createElement("label");
  24616. var boundingBoxesCheckbox = document.createElement("input");
  24617. boundingBoxesCheckbox.type = "checkbox";
  24618. boundingBoxesCheckbox.checked = initialState;
  24619. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24620. task(evt.target, tag);
  24621. });
  24622. label.appendChild(boundingBoxesCheckbox);
  24623. var container = document.createElement("span");
  24624. var leftPart = document.createElement("span");
  24625. var rightPart = document.createElement("span");
  24626. rightPart.style.cssFloat = "right";
  24627. leftPart.innerHTML = leftTitle;
  24628. rightPart.innerHTML = rightTitle;
  24629. rightPart.style.fontSize = "12px";
  24630. rightPart.style.maxWidth = "200px";
  24631. container.appendChild(leftPart);
  24632. container.appendChild(rightPart);
  24633. label.appendChild(container);
  24634. root.appendChild(label);
  24635. root.appendChild(document.createElement("br"));
  24636. };
  24637. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24638. if (typeof tag === "undefined") { tag = null; }
  24639. var label = document.createElement("label");
  24640. var boundingBoxesCheckbox = document.createElement("input");
  24641. boundingBoxesCheckbox.type = "checkbox";
  24642. boundingBoxesCheckbox.checked = initialState;
  24643. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24644. task(evt.target, tag);
  24645. });
  24646. label.appendChild(boundingBoxesCheckbox);
  24647. label.appendChild(document.createTextNode(title));
  24648. root.appendChild(label);
  24649. root.appendChild(document.createElement("br"));
  24650. };
  24651. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24652. if (typeof tag === "undefined") { tag = null; }
  24653. var label = document.createElement("label");
  24654. var boundingBoxesRadio = document.createElement("input");
  24655. boundingBoxesRadio.type = "radio";
  24656. boundingBoxesRadio.name = name;
  24657. boundingBoxesRadio.checked = initialState;
  24658. boundingBoxesRadio.addEventListener("change", function (evt) {
  24659. task(evt.target, tag);
  24660. });
  24661. label.appendChild(boundingBoxesRadio);
  24662. label.appendChild(document.createTextNode(title));
  24663. root.appendChild(label);
  24664. root.appendChild(document.createElement("br"));
  24665. };
  24666. DebugLayer.prototype._generateDOMelements = function () {
  24667. var _this = this;
  24668. this._globalDiv.id = "DebugLayer";
  24669. this._globalDiv.style.position = "absolute";
  24670. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24671. this._globalDiv.style.fontSize = "14px";
  24672. this._globalDiv.style.color = "white";
  24673. // Drawing canvas
  24674. this._drawingCanvas = document.createElement("canvas");
  24675. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24676. this._drawingCanvas.style.position = "absolute";
  24677. this._drawingCanvas.style.pointerEvents = "none";
  24678. this._drawingContext = this._drawingCanvas.getContext("2d");
  24679. this._globalDiv.appendChild(this._drawingCanvas);
  24680. if (this._showUI) {
  24681. var background = "rgba(128, 128, 128, 0.4)";
  24682. var border = "rgb(180, 180, 180) solid 1px";
  24683. // Stats
  24684. this._statsDiv = document.createElement("div");
  24685. this._statsDiv.id = "DebugLayerStats";
  24686. this._statsDiv.style.border = border;
  24687. this._statsDiv.style.position = "absolute";
  24688. this._statsDiv.style.background = background;
  24689. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24690. this._statsDiv.style.pointerEvents = "none";
  24691. this._statsDiv.style.overflowY = "auto";
  24692. this._generateheader(this._statsDiv, "STATISTICS");
  24693. this._statsSubsetDiv = document.createElement("div");
  24694. this._statsSubsetDiv.style.paddingTop = "5px";
  24695. this._statsSubsetDiv.style.paddingBottom = "5px";
  24696. this._statsDiv.appendChild(this._statsSubsetDiv);
  24697. // Tree
  24698. this._treeDiv = document.createElement("div");
  24699. this._treeDiv.id = "DebugLayerTree";
  24700. this._treeDiv.style.border = border;
  24701. this._treeDiv.style.position = "absolute";
  24702. this._treeDiv.style.background = background;
  24703. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24704. this._treeDiv.style.display = "none";
  24705. this._generateheader(this._treeDiv, "MESHES TREE");
  24706. this._treeSubsetDiv = document.createElement("div");
  24707. this._treeSubsetDiv.style.paddingTop = "5px";
  24708. this._treeSubsetDiv.style.paddingRight = "5px";
  24709. this._treeSubsetDiv.style.overflowY = "auto";
  24710. this._treeSubsetDiv.style.maxHeight = "300px";
  24711. this._treeDiv.appendChild(this._treeSubsetDiv);
  24712. this._needToRefreshMeshesTree = true;
  24713. // Logs
  24714. this._logDiv = document.createElement("div");
  24715. this._logDiv.style.border = border;
  24716. this._logDiv.id = "DebugLayerLogs";
  24717. this._logDiv.style.position = "absolute";
  24718. this._logDiv.style.background = background;
  24719. this._logDiv.style.padding = "0px 0px 0px 5px";
  24720. this._logDiv.style.display = "none";
  24721. this._generateheader(this._logDiv, "LOGS");
  24722. this._logSubsetDiv = document.createElement("div");
  24723. this._logSubsetDiv.style.height = "127px";
  24724. this._logSubsetDiv.style.paddingTop = "5px";
  24725. this._logSubsetDiv.style.overflowY = "auto";
  24726. this._logSubsetDiv.style.fontSize = "12px";
  24727. this._logSubsetDiv.style.fontFamily = "consolas";
  24728. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24729. this._logDiv.appendChild(this._logSubsetDiv);
  24730. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24731. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24732. };
  24733. // Options
  24734. this._optionsDiv = document.createElement("div");
  24735. this._optionsDiv.id = "DebugLayerOptions";
  24736. this._optionsDiv.style.border = border;
  24737. this._optionsDiv.style.position = "absolute";
  24738. this._optionsDiv.style.background = background;
  24739. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24740. this._optionsDiv.style.overflowY = "auto";
  24741. this._generateheader(this._optionsDiv, "OPTIONS");
  24742. this._optionsSubsetDiv = document.createElement("div");
  24743. this._optionsSubsetDiv.style.paddingTop = "5px";
  24744. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24745. this._optionsSubsetDiv.style.overflowY = "auto";
  24746. this._optionsSubsetDiv.style.maxHeight = "200px";
  24747. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24748. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24749. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24750. _this._displayStatistics = element.checked;
  24751. });
  24752. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24753. _this._displayLogs = element.checked;
  24754. });
  24755. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24756. _this._displayTree = element.checked;
  24757. _this._needToRefreshMeshesTree = true;
  24758. });
  24759. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24760. _this._scene.forceShowBoundingBoxes = element.checked;
  24761. });
  24762. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24763. _this._labelsEnabled = element.checked;
  24764. if (!_this._labelsEnabled) {
  24765. _this._clearLabels();
  24766. }
  24767. });
  24768. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24769. if (element.checked) {
  24770. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24771. } else {
  24772. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24773. }
  24774. });
  24775. ;
  24776. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24777. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24778. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24779. if (element.checked) {
  24780. _this._scene.forceWireframe = false;
  24781. _this._scene.forcePointsCloud = false;
  24782. }
  24783. });
  24784. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  24785. if (element.checked) {
  24786. _this._scene.forceWireframe = true;
  24787. _this._scene.forcePointsCloud = false;
  24788. }
  24789. });
  24790. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  24791. if (element.checked) {
  24792. _this._scene.forceWireframe = false;
  24793. _this._scene.forcePointsCloud = true;
  24794. }
  24795. });
  24796. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24797. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  24798. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  24799. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  24800. });
  24801. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  24802. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  24803. });
  24804. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  24805. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  24806. });
  24807. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  24808. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  24809. });
  24810. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  24811. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  24812. });
  24813. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  24814. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  24815. });
  24816. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  24817. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  24818. });
  24819. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  24820. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  24821. });
  24822. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24823. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  24824. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  24825. _this._scene.animationsEnabled = element.checked;
  24826. });
  24827. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  24828. _this._scene.collisionsEnabled = element.checked;
  24829. });
  24830. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  24831. _this._scene.fogEnabled = element.checked;
  24832. });
  24833. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  24834. _this._scene.lensFlaresEnabled = element.checked;
  24835. });
  24836. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  24837. _this._scene.lightsEnabled = element.checked;
  24838. });
  24839. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  24840. _this._scene.particlesEnabled = element.checked;
  24841. });
  24842. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  24843. _this._scene.postProcessesEnabled = element.checked;
  24844. });
  24845. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  24846. _this._scene.proceduralTexturesEnabled = element.checked;
  24847. });
  24848. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  24849. _this._scene.renderTargetsEnabled = element.checked;
  24850. });
  24851. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  24852. _this._scene.shadowsEnabled = element.checked;
  24853. });
  24854. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  24855. _this._scene.skeletonsEnabled = element.checked;
  24856. });
  24857. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  24858. _this._scene.texturesEnabled = element.checked;
  24859. });
  24860. this._globalDiv.appendChild(this._statsDiv);
  24861. this._globalDiv.appendChild(this._logDiv);
  24862. this._globalDiv.appendChild(this._optionsDiv);
  24863. this._globalDiv.appendChild(this._treeDiv);
  24864. }
  24865. };
  24866. DebugLayer.prototype._displayStats = function () {
  24867. var scene = this._scene;
  24868. var engine = scene.getEngine();
  24869. 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>";
  24870. };
  24871. return DebugLayer;
  24872. })();
  24873. BABYLON.DebugLayer = DebugLayer;
  24874. })(BABYLON || (BABYLON = {}));
  24875. //# sourceMappingURL=babylon.debugLayer.js.map
  24876. var BABYLON;
  24877. (function (BABYLON) {
  24878. var RawTexture = (function (_super) {
  24879. __extends(RawTexture, _super);
  24880. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  24881. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24882. if (typeof invertY === "undefined") { invertY = false; }
  24883. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24884. _super.call(this, null, scene, !generateMipMaps, invertY);
  24885. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  24886. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24887. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24888. }
  24889. // Statics
  24890. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24891. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24892. if (typeof invertY === "undefined") { invertY = false; }
  24893. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24894. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  24895. };
  24896. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24897. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24898. if (typeof invertY === "undefined") { invertY = false; }
  24899. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24900. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  24901. };
  24902. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24903. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24904. if (typeof invertY === "undefined") { invertY = false; }
  24905. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24906. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  24907. };
  24908. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24909. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24910. if (typeof invertY === "undefined") { invertY = false; }
  24911. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24912. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  24913. };
  24914. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24915. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24916. if (typeof invertY === "undefined") { invertY = false; }
  24917. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24918. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  24919. };
  24920. return RawTexture;
  24921. })(BABYLON.Texture);
  24922. BABYLON.RawTexture = RawTexture;
  24923. })(BABYLON || (BABYLON = {}));
  24924. //# sourceMappingURL=babylon.rawTexture.js.map
  24925. var BABYLON;
  24926. (function (BABYLON) {
  24927. var IndexedVector2 = (function (_super) {
  24928. __extends(IndexedVector2, _super);
  24929. function IndexedVector2(original, index) {
  24930. _super.call(this, original.x, original.y);
  24931. this.index = index;
  24932. }
  24933. return IndexedVector2;
  24934. })(BABYLON.Vector2);
  24935. var PolygonPoints = (function () {
  24936. function PolygonPoints() {
  24937. this.elements = new Array();
  24938. }
  24939. PolygonPoints.prototype.add = function (originalPoints) {
  24940. var _this = this;
  24941. var result = new Array();
  24942. originalPoints.forEach(function (point) {
  24943. if (result.length == 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y))) {
  24944. var newPoint = new IndexedVector2(point, _this.elements.length);
  24945. result.push(newPoint);
  24946. _this.elements.push(newPoint);
  24947. }
  24948. });
  24949. return result;
  24950. };
  24951. PolygonPoints.prototype.computeBounds = function () {
  24952. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  24953. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  24954. this.elements.forEach(function (point) {
  24955. // x
  24956. if (point.x < lmin.x) {
  24957. lmin.x = point.x;
  24958. } else if (point.x > lmax.x) {
  24959. lmax.x = point.x;
  24960. }
  24961. // y
  24962. if (point.y < lmin.y) {
  24963. lmin.y = point.y;
  24964. } else if (point.y > lmax.y) {
  24965. lmax.y = point.y;
  24966. }
  24967. });
  24968. return {
  24969. min: lmin,
  24970. max: lmax,
  24971. width: lmax.x - lmin.x,
  24972. height: lmax.y - lmin.y
  24973. };
  24974. };
  24975. return PolygonPoints;
  24976. })();
  24977. var Polygon = (function () {
  24978. function Polygon() {
  24979. }
  24980. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  24981. return [
  24982. new BABYLON.Vector2(xmin, ymin),
  24983. new BABYLON.Vector2(xmax, ymin),
  24984. new BABYLON.Vector2(xmax, ymax),
  24985. new BABYLON.Vector2(xmin, ymax)
  24986. ];
  24987. };
  24988. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  24989. if (typeof cx === "undefined") { cx = 0; }
  24990. if (typeof cy === "undefined") { cy = 0; }
  24991. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  24992. var result = new Array();
  24993. var angle = 0;
  24994. var increment = (Math.PI * 2) / numberOfSides;
  24995. for (var i = 0; i < numberOfSides; i++) {
  24996. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  24997. angle -= increment;
  24998. }
  24999. return result;
  25000. };
  25001. Polygon.Parse = function (input) {
  25002. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25003. return (!isNaN(val));
  25004. });
  25005. var i, result = [];
  25006. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25007. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25008. }
  25009. return result;
  25010. };
  25011. Polygon.StartingAt = function (x, y) {
  25012. return BABYLON.Path.StartingAt(x, y);
  25013. };
  25014. return Polygon;
  25015. })();
  25016. BABYLON.Polygon = Polygon;
  25017. var PolygonMeshBuilder = (function () {
  25018. function PolygonMeshBuilder(name, contours, scene) {
  25019. this.name = name;
  25020. this.scene = scene;
  25021. this._points = new PolygonPoints();
  25022. if (!("poly2tri" in window)) {
  25023. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25024. }
  25025. this._swctx = new poly2tri.SweepContext(this._points.add(contours));
  25026. }
  25027. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25028. this._swctx.addHole(this._points.add(hole));
  25029. return this;
  25030. };
  25031. PolygonMeshBuilder.prototype.build = function (updatable) {
  25032. if (typeof updatable === "undefined") { updatable = false; }
  25033. var result = new BABYLON.Mesh(this.name, this.scene);
  25034. var normals = [];
  25035. var positions = [];
  25036. var uvs = [];
  25037. var bounds = this._points.computeBounds();
  25038. this._points.elements.forEach(function (p) {
  25039. normals.push(0, 1.0, 0);
  25040. positions.push(p.x, 0, p.y);
  25041. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25042. });
  25043. var indices = [];
  25044. this._swctx.triangulate();
  25045. this._swctx.getTriangles().forEach(function (triangle) {
  25046. triangle.getPoints().forEach(function (point) {
  25047. indices.push(point.index);
  25048. });
  25049. });
  25050. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25051. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25052. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25053. result.setIndices(indices);
  25054. return result;
  25055. };
  25056. return PolygonMeshBuilder;
  25057. })();
  25058. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25059. })(BABYLON || (BABYLON = {}));
  25060. //# sourceMappingURL=babylon.polygonMesh.js.map