babylon.2.0-alpha.debug.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637
  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. Color4.prototype.copyFrom = function (source) {
  188. this.r = source.r;
  189. this.g = source.g;
  190. this.b = source.b;
  191. this.a = source.a;
  192. };
  193. // Statics
  194. Color4.Lerp = function (left, right, amount) {
  195. var result = new Color4(0, 0, 0, 0);
  196. Color4.LerpToRef(left, right, amount, result);
  197. return result;
  198. };
  199. Color4.LerpToRef = function (left, right, amount, result) {
  200. result.r = left.r + (right.r - left.r) * amount;
  201. result.g = left.g + (right.g - left.g) * amount;
  202. result.b = left.b + (right.b - left.b) * amount;
  203. result.a = left.a + (right.a - left.a) * amount;
  204. };
  205. Color4.FromArray = function (array, offset) {
  206. if (typeof offset === "undefined") { offset = 0; }
  207. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  208. };
  209. Color4.FromInts = function (r, g, b, a) {
  210. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  211. };
  212. return Color4;
  213. })();
  214. BABYLON.Color4 = Color4;
  215. var Vector2 = (function () {
  216. function Vector2(x, y) {
  217. this.x = x;
  218. this.y = y;
  219. }
  220. Vector2.prototype.toString = function () {
  221. return "{X: " + this.x + " Y:" + this.y + "}";
  222. };
  223. // Operators
  224. Vector2.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.x;
  229. array[index + 1] = this.y;
  230. };
  231. Vector2.prototype.asArray = function () {
  232. var result = [];
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. Vector2.prototype.copyFrom = function (source) {
  237. this.x = source.x;
  238. this.y = source.y;
  239. };
  240. Vector2.prototype.copyFromFloats = function (x, y) {
  241. this.x = x;
  242. this.y = y;
  243. };
  244. Vector2.prototype.add = function (otherVector) {
  245. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  246. };
  247. Vector2.prototype.addVector3 = function (otherVector) {
  248. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  249. };
  250. Vector2.prototype.subtract = function (otherVector) {
  251. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  252. };
  253. Vector2.prototype.subtractInPlace = function (otherVector) {
  254. this.x -= otherVector.x;
  255. this.y -= otherVector.y;
  256. };
  257. Vector2.prototype.multiplyInPlace = function (otherVector) {
  258. this.x *= otherVector.x;
  259. this.y *= otherVector.y;
  260. };
  261. Vector2.prototype.multiply = function (otherVector) {
  262. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  263. };
  264. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  265. result.x = this.x * otherVector.x;
  266. result.y = this.y * otherVector.y;
  267. };
  268. Vector2.prototype.multiplyByFloats = function (x, y) {
  269. return new Vector2(this.x * x, this.y * y);
  270. };
  271. Vector2.prototype.divide = function (otherVector) {
  272. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  273. };
  274. Vector2.prototype.divideToRef = function (otherVector, result) {
  275. result.x = this.x / otherVector.x;
  276. result.y = this.y / otherVector.y;
  277. };
  278. Vector2.prototype.negate = function () {
  279. return new Vector2(-this.x, -this.y);
  280. };
  281. Vector2.prototype.scaleInPlace = function (scale) {
  282. this.x *= scale;
  283. this.y *= scale;
  284. return this;
  285. };
  286. Vector2.prototype.scale = function (scale) {
  287. return new Vector2(this.x * scale, this.y * scale);
  288. };
  289. Vector2.prototype.equals = function (otherVector) {
  290. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  291. };
  292. // Properties
  293. Vector2.prototype.length = function () {
  294. return Math.sqrt(this.x * this.x + this.y * this.y);
  295. };
  296. Vector2.prototype.lengthSquared = function () {
  297. return (this.x * this.x + this.y * this.y);
  298. };
  299. // Methods
  300. Vector2.prototype.normalize = function () {
  301. var len = this.length();
  302. if (len === 0)
  303. return this;
  304. var num = 1.0 / len;
  305. this.x *= num;
  306. this.y *= num;
  307. return this;
  308. };
  309. Vector2.prototype.clone = function () {
  310. return new Vector2(this.x, this.y);
  311. };
  312. // Statics
  313. Vector2.Zero = function () {
  314. return new Vector2(0, 0);
  315. };
  316. Vector2.FromArray = function (array, offset) {
  317. if (!offset) {
  318. offset = 0;
  319. }
  320. return new Vector2(array[offset], array[offset + 1]);
  321. };
  322. Vector2.FromArrayToRef = function (array, offset, result) {
  323. result.x = array[offset];
  324. result.y = array[offset + 1];
  325. };
  326. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  327. var squared = amount * amount;
  328. var cubed = amount * squared;
  329. 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));
  330. 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));
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Clamp = function (value, min, max) {
  334. var x = value.x;
  335. x = (x > max.x) ? max.x : x;
  336. x = (x < min.x) ? min.x : x;
  337. var y = value.y;
  338. y = (y > max.y) ? max.y : y;
  339. y = (y < min.y) ? min.y : y;
  340. return new Vector2(x, y);
  341. };
  342. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  347. var part3 = (cubed - (2.0 * squared)) + amount;
  348. var part4 = cubed - squared;
  349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Lerp = function (start, end, amount) {
  354. var x = start.x + ((end.x - start.x) * amount);
  355. var y = start.y + ((end.y - start.y) * amount);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Dot = function (left, right) {
  359. return left.x * right.x + left.y * right.y;
  360. };
  361. Vector2.Normalize = function (vector) {
  362. var newVector = vector.clone();
  363. newVector.normalize();
  364. return newVector;
  365. };
  366. Vector2.Minimize = function (left, right) {
  367. var x = (left.x < right.x) ? left.x : right.x;
  368. var y = (left.y < right.y) ? left.y : right.y;
  369. return new Vector2(x, y);
  370. };
  371. Vector2.Maximize = function (left, right) {
  372. var x = (left.x > right.x) ? left.x : right.x;
  373. var y = (left.y > right.y) ? left.y : right.y;
  374. return new Vector2(x, y);
  375. };
  376. Vector2.Transform = function (vector, transformation) {
  377. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  378. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  379. return new Vector2(x, y);
  380. };
  381. Vector2.Distance = function (value1, value2) {
  382. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  383. };
  384. Vector2.DistanceSquared = function (value1, value2) {
  385. var x = value1.x - value2.x;
  386. var y = value1.y - value2.y;
  387. return (x * x) + (y * y);
  388. };
  389. return Vector2;
  390. })();
  391. BABYLON.Vector2 = Vector2;
  392. var Vector3 = (function () {
  393. function Vector3(x, y, z) {
  394. this.x = x;
  395. this.y = y;
  396. this.z = z;
  397. }
  398. Vector3.prototype.toString = function () {
  399. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  400. };
  401. // Operators
  402. Vector3.prototype.asArray = function () {
  403. var result = [];
  404. this.toArray(result, 0);
  405. return result;
  406. };
  407. Vector3.prototype.toArray = function (array, index) {
  408. if (index === undefined) {
  409. index = 0;
  410. }
  411. array[index] = this.x;
  412. array[index + 1] = this.y;
  413. array[index + 2] = this.z;
  414. };
  415. Vector3.prototype.addInPlace = function (otherVector) {
  416. this.x += otherVector.x;
  417. this.y += otherVector.y;
  418. this.z += otherVector.z;
  419. };
  420. Vector3.prototype.add = function (otherVector) {
  421. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  422. };
  423. Vector3.prototype.addToRef = function (otherVector, result) {
  424. result.x = this.x + otherVector.x;
  425. result.y = this.y + otherVector.y;
  426. result.z = this.z + otherVector.z;
  427. };
  428. Vector3.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. this.z -= otherVector.z;
  432. };
  433. Vector3.prototype.subtract = function (otherVector) {
  434. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  435. };
  436. Vector3.prototype.subtractToRef = function (otherVector, result) {
  437. result.x = this.x - otherVector.x;
  438. result.y = this.y - otherVector.y;
  439. result.z = this.z - otherVector.z;
  440. };
  441. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  442. return new Vector3(this.x - x, this.y - y, this.z - z);
  443. };
  444. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  445. result.x = this.x - x;
  446. result.y = this.y - y;
  447. result.z = this.z - z;
  448. };
  449. Vector3.prototype.negate = function () {
  450. return new Vector3(-this.x, -this.y, -this.z);
  451. };
  452. Vector3.prototype.scaleInPlace = function (scale) {
  453. this.x *= scale;
  454. this.y *= scale;
  455. this.z *= scale;
  456. return this;
  457. };
  458. Vector3.prototype.scale = function (scale) {
  459. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  460. };
  461. Vector3.prototype.scaleToRef = function (scale, result) {
  462. result.x = this.x * scale;
  463. result.y = this.y * scale;
  464. result.z = this.z * scale;
  465. };
  466. Vector3.prototype.equals = function (otherVector) {
  467. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  468. };
  469. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  470. 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;
  471. };
  472. Vector3.prototype.equalsToFloats = function (x, y, z) {
  473. return this.x === x && this.y === y && this.z === z;
  474. };
  475. Vector3.prototype.multiplyInPlace = function (otherVector) {
  476. this.x *= otherVector.x;
  477. this.y *= otherVector.y;
  478. this.z *= otherVector.z;
  479. };
  480. Vector3.prototype.multiply = function (otherVector) {
  481. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  482. };
  483. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  484. result.x = this.x * otherVector.x;
  485. result.y = this.y * otherVector.y;
  486. result.z = this.z * otherVector.z;
  487. };
  488. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  489. return new Vector3(this.x * x, this.y * y, this.z * z);
  490. };
  491. Vector3.prototype.divide = function (otherVector) {
  492. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  493. };
  494. Vector3.prototype.divideToRef = function (otherVector, result) {
  495. result.x = this.x / otherVector.x;
  496. result.y = this.y / otherVector.y;
  497. result.z = this.z / otherVector.z;
  498. };
  499. Vector3.prototype.MinimizeInPlace = function (other) {
  500. if (other.x < this.x)
  501. this.x = other.x;
  502. if (other.y < this.y)
  503. this.y = other.y;
  504. if (other.z < this.z)
  505. this.z = other.z;
  506. };
  507. Vector3.prototype.MaximizeInPlace = function (other) {
  508. if (other.x > this.x)
  509. this.x = other.x;
  510. if (other.y > this.y)
  511. this.y = other.y;
  512. if (other.z > this.z)
  513. this.z = other.z;
  514. };
  515. // Properties
  516. Vector3.prototype.length = function () {
  517. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  518. };
  519. Vector3.prototype.lengthSquared = function () {
  520. return (this.x * this.x + this.y * this.y + this.z * this.z);
  521. };
  522. // Methods
  523. Vector3.prototype.normalize = function () {
  524. var len = this.length();
  525. if (len === 0)
  526. return this;
  527. var num = 1.0 / len;
  528. this.x *= num;
  529. this.y *= num;
  530. this.z *= num;
  531. return this;
  532. };
  533. Vector3.prototype.clone = function () {
  534. return new Vector3(this.x, this.y, this.z);
  535. };
  536. Vector3.prototype.copyFrom = function (source) {
  537. this.x = source.x;
  538. this.y = source.y;
  539. this.z = source.z;
  540. };
  541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  542. this.x = x;
  543. this.y = y;
  544. this.z = z;
  545. };
  546. // Statics
  547. Vector3.FromArray = function (array, offset) {
  548. if (!offset) {
  549. offset = 0;
  550. }
  551. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  552. };
  553. Vector3.FromArrayToRef = function (array, offset, result) {
  554. result.x = array[offset];
  555. result.y = array[offset + 1];
  556. result.z = array[offset + 2];
  557. };
  558. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  559. result.x = array[offset];
  560. result.y = array[offset + 1];
  561. result.z = array[offset + 2];
  562. };
  563. Vector3.FromFloatsToRef = function (x, y, z, result) {
  564. result.x = x;
  565. result.y = y;
  566. result.z = z;
  567. };
  568. Vector3.Zero = function () {
  569. return new Vector3(0, 0, 0);
  570. };
  571. Vector3.Up = function () {
  572. return new Vector3(0, 1.0, 0);
  573. };
  574. Vector3.TransformCoordinates = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  580. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  581. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  582. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  583. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  584. result.x = x / w;
  585. result.y = y / w;
  586. result.z = z / w;
  587. };
  588. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  589. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  590. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  591. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  592. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  593. result.x = rx / rw;
  594. result.y = ry / rw;
  595. result.z = rz / rw;
  596. };
  597. Vector3.TransformNormal = function (vector, transformation) {
  598. var result = Vector3.Zero();
  599. Vector3.TransformNormalToRef(vector, transformation, result);
  600. return result;
  601. };
  602. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  603. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  604. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  605. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  606. };
  607. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  608. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  609. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  610. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  611. };
  612. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  613. var squared = amount * amount;
  614. var cubed = amount * squared;
  615. 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));
  616. 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));
  617. 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));
  618. return new Vector3(x, y, z);
  619. };
  620. Vector3.Clamp = function (value, min, max) {
  621. var x = value.x;
  622. x = (x > max.x) ? max.x : x;
  623. x = (x < min.x) ? min.x : x;
  624. var y = value.y;
  625. y = (y > max.y) ? max.y : y;
  626. y = (y < min.y) ? min.y : y;
  627. var z = value.z;
  628. z = (z > max.z) ? max.z : z;
  629. z = (z < min.z) ? min.z : z;
  630. return new Vector3(x, y, z);
  631. };
  632. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  633. var squared = amount * amount;
  634. var cubed = amount * squared;
  635. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  636. var part2 = (-2.0 * cubed) + (3.0 * squared);
  637. var part3 = (cubed - (2.0 * squared)) + amount;
  638. var part4 = cubed - squared;
  639. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  640. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  641. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Lerp = function (start, end, amount) {
  645. var x = start.x + ((end.x - start.x) * amount);
  646. var y = start.y + ((end.y - start.y) * amount);
  647. var z = start.z + ((end.z - start.z) * amount);
  648. return new Vector3(x, y, z);
  649. };
  650. Vector3.Dot = function (left, right) {
  651. return (left.x * right.x + left.y * right.y + left.z * right.z);
  652. };
  653. Vector3.Cross = function (left, right) {
  654. var result = Vector3.Zero();
  655. Vector3.CrossToRef(left, right, result);
  656. return result;
  657. };
  658. Vector3.CrossToRef = function (left, right, result) {
  659. result.x = left.y * right.z - left.z * right.y;
  660. result.y = left.z * right.x - left.x * right.z;
  661. result.z = left.x * right.y - left.y * right.x;
  662. };
  663. Vector3.Normalize = function (vector) {
  664. var result = Vector3.Zero();
  665. Vector3.NormalizeToRef(vector, result);
  666. return result;
  667. };
  668. Vector3.NormalizeToRef = function (vector, result) {
  669. result.copyFrom(vector);
  670. result.normalize();
  671. };
  672. Vector3.Project = function (vector, world, transform, viewport) {
  673. var cw = viewport.width;
  674. var ch = viewport.height;
  675. var cx = viewport.x;
  676. var cy = viewport.y;
  677. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  678. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  679. return Vector3.TransformCoordinates(vector, finalMatrix);
  680. };
  681. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  682. var matrix = world.multiply(transform);
  683. matrix.invert();
  684. source.x = source.x / viewportWidth * 2 - 1;
  685. source.y = -(source.y / viewportHeight * 2 - 1);
  686. var vector = Vector3.TransformCoordinates(source, matrix);
  687. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  688. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  689. vector = vector.scale(1.0 / num);
  690. }
  691. return vector;
  692. };
  693. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  694. var matrix = world.multiply(view).multiply(projection);
  695. matrix.invert();
  696. source.x = source.x / viewportWidth * 2 - 1;
  697. source.y = -(source.y / viewportHeight * 2 - 1);
  698. var vector = Vector3.TransformCoordinates(source, matrix);
  699. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  700. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  701. vector = vector.scale(1.0 / num);
  702. }
  703. return vector;
  704. };
  705. Vector3.Minimize = function (left, right) {
  706. var min = left.clone();
  707. min.MinimizeInPlace(right);
  708. return min;
  709. };
  710. Vector3.Maximize = function (left, right) {
  711. var max = left.clone();
  712. max.MaximizeInPlace(right);
  713. return max;
  714. };
  715. Vector3.Distance = function (value1, value2) {
  716. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  717. };
  718. Vector3.DistanceSquared = function (value1, value2) {
  719. var x = value1.x - value2.x;
  720. var y = value1.y - value2.y;
  721. var z = value1.z - value2.z;
  722. return (x * x) + (y * y) + (z * z);
  723. };
  724. Vector3.Center = function (value1, value2) {
  725. var center = value1.add(value2);
  726. center.scaleInPlace(0.5);
  727. return center;
  728. };
  729. return Vector3;
  730. })();
  731. BABYLON.Vector3 = Vector3;
  732. //Vector4 class created for EulerAngle class conversion to Quaternion
  733. var Vector4 = (function () {
  734. function Vector4(x, y, z, w) {
  735. this.x = x;
  736. this.y = y;
  737. this.z = z;
  738. this.w = w;
  739. }
  740. Vector4.prototype.toString = function () {
  741. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  742. };
  743. // Operators
  744. Vector4.prototype.asArray = function () {
  745. var result = [];
  746. this.toArray(result, 0);
  747. return result;
  748. };
  749. Vector4.prototype.toArray = function (array, index) {
  750. if (index === undefined) {
  751. index = 0;
  752. }
  753. array[index] = this.x;
  754. array[index + 1] = this.y;
  755. array[index + 2] = this.z;
  756. array[index + 3] = this.w;
  757. };
  758. Vector4.prototype.addInPlace = function (otherVector) {
  759. this.x += otherVector.x;
  760. this.y += otherVector.y;
  761. this.z += otherVector.z;
  762. this.w += otherVector.w;
  763. };
  764. Vector4.prototype.add = function (otherVector) {
  765. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  766. };
  767. Vector4.prototype.addToRef = function (otherVector, result) {
  768. result.x = this.x + otherVector.x;
  769. result.y = this.y + otherVector.y;
  770. result.z = this.z + otherVector.z;
  771. result.w = this.w + otherVector.w;
  772. };
  773. Vector4.prototype.subtractInPlace = function (otherVector) {
  774. this.x -= otherVector.x;
  775. this.y -= otherVector.y;
  776. this.z -= otherVector.z;
  777. this.w -= otherVector.w;
  778. };
  779. Vector4.prototype.subtract = function (otherVector) {
  780. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  781. };
  782. Vector4.prototype.subtractToRef = function (otherVector, result) {
  783. result.x = this.x - otherVector.x;
  784. result.y = this.y - otherVector.y;
  785. result.z = this.z - otherVector.z;
  786. result.w = this.w - otherVector.w;
  787. };
  788. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  789. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  790. };
  791. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  792. result.x = this.x - x;
  793. result.y = this.y - y;
  794. result.z = this.z - z;
  795. result.w = this.w - w;
  796. };
  797. Vector4.prototype.negate = function () {
  798. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  799. };
  800. Vector4.prototype.scaleInPlace = function (scale) {
  801. this.x *= scale;
  802. this.y *= scale;
  803. this.z *= scale;
  804. this.w *= scale;
  805. return this;
  806. };
  807. Vector4.prototype.scale = function (scale) {
  808. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  809. };
  810. Vector4.prototype.scaleToRef = function (scale, result) {
  811. result.x = this.x * scale;
  812. result.y = this.y * scale;
  813. result.z = this.z * scale;
  814. result.w = this.w * scale;
  815. };
  816. Vector4.prototype.equals = function (otherVector) {
  817. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  818. };
  819. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  820. 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;
  821. };
  822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  823. return this.x === x && this.y === y && this.z === z && this.w === w;
  824. };
  825. Vector4.prototype.multiplyInPlace = function (otherVector) {
  826. this.x *= otherVector.x;
  827. this.y *= otherVector.y;
  828. this.z *= otherVector.z;
  829. this.w *= otherVector.w;
  830. };
  831. Vector4.prototype.multiply = function (otherVector) {
  832. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  833. };
  834. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  835. result.x = this.x * otherVector.x;
  836. result.y = this.y * otherVector.y;
  837. result.z = this.z * otherVector.z;
  838. result.w = this.w * otherVector.w;
  839. };
  840. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  841. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  842. };
  843. Vector4.prototype.divide = function (otherVector) {
  844. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  845. };
  846. Vector4.prototype.divideToRef = function (otherVector, result) {
  847. result.x = this.x / otherVector.x;
  848. result.y = this.y / otherVector.y;
  849. result.z = this.z / otherVector.z;
  850. result.w = this.w / otherVector.w;
  851. };
  852. Vector4.prototype.MinimizeInPlace = function (other) {
  853. if (other.x < this.x)
  854. this.x = other.x;
  855. if (other.y < this.y)
  856. this.y = other.y;
  857. if (other.z < this.z)
  858. this.z = other.z;
  859. if (other.w < this.w)
  860. this.w = other.w;
  861. };
  862. Vector4.prototype.MaximizeInPlace = function (other) {
  863. if (other.x > this.x)
  864. this.x = other.x;
  865. if (other.y > this.y)
  866. this.y = other.y;
  867. if (other.z > this.z)
  868. this.z = other.z;
  869. if (other.w > this.w)
  870. this.w = other.w;
  871. };
  872. // Properties
  873. Vector4.prototype.length = function () {
  874. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  875. };
  876. Vector4.prototype.lengthSquared = function () {
  877. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  878. };
  879. // Methods
  880. Vector4.prototype.normalize = function () {
  881. var len = this.length();
  882. if (len === 0)
  883. return this;
  884. var num = 1.0 / len;
  885. this.x *= num;
  886. this.y *= num;
  887. this.z *= num;
  888. this.w *= num;
  889. return this;
  890. };
  891. Vector4.prototype.clone = function () {
  892. return new Vector4(this.x, this.y, this.z, this.w);
  893. };
  894. Vector4.prototype.copyFrom = function (source) {
  895. this.x = source.x;
  896. this.y = source.y;
  897. this.z = source.z;
  898. this.w = source.w;
  899. };
  900. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  901. this.x = x;
  902. this.y = y;
  903. this.z = z;
  904. this.w = w;
  905. };
  906. // Statics
  907. Vector4.FromArray = function (array, offset) {
  908. if (!offset) {
  909. offset = 0;
  910. }
  911. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  912. };
  913. Vector4.FromArrayToRef = 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.FromFloatArrayToRef = function (array, offset, result) {
  920. result.x = array[offset];
  921. result.y = array[offset + 1];
  922. result.z = array[offset + 2];
  923. result.w = array[offset + 3];
  924. };
  925. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  926. result.x = x;
  927. result.y = y;
  928. result.z = z;
  929. result.w = w;
  930. };
  931. Vector4.Zero = function () {
  932. return new Vector4(0, 0, 0, 0);
  933. };
  934. Vector4.Normalize = function (vector) {
  935. var result = Vector4.Zero();
  936. Vector4.NormalizeToRef(vector, result);
  937. return result;
  938. };
  939. Vector4.NormalizeToRef = function (vector, result) {
  940. result.copyFrom(vector);
  941. result.normalize();
  942. };
  943. Vector4.Minimize = function (left, right) {
  944. var min = left.clone();
  945. min.MinimizeInPlace(right);
  946. return min;
  947. };
  948. Vector4.Maximize = function (left, right) {
  949. var max = left.clone();
  950. max.MaximizeInPlace(right);
  951. return max;
  952. };
  953. Vector4.Distance = function (value1, value2) {
  954. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  955. };
  956. Vector4.DistanceSquared = function (value1, value2) {
  957. var x = value1.x - value2.x;
  958. var y = value1.y - value2.y;
  959. var z = value1.z - value2.z;
  960. var w = value1.w - value2.w;
  961. return (x * x) + (y * y) + (z * z) + (w * w);
  962. };
  963. Vector4.Center = function (value1, value2) {
  964. var center = value1.add(value2);
  965. center.scaleInPlace(0.5);
  966. return center;
  967. };
  968. return Vector4;
  969. })();
  970. BABYLON.Vector4 = Vector4;
  971. var Quaternion = (function () {
  972. function Quaternion(x, y, z, w) {
  973. if (typeof x === "undefined") { x = 0; }
  974. if (typeof y === "undefined") { y = 0; }
  975. if (typeof z === "undefined") { z = 0; }
  976. if (typeof w === "undefined") { w = 1; }
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Quaternion.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  984. };
  985. Quaternion.prototype.asArray = function () {
  986. return [this.x, this.y, this.z, this.w];
  987. };
  988. Quaternion.prototype.equals = function (otherQuaternion) {
  989. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  990. };
  991. Quaternion.prototype.clone = function () {
  992. return new Quaternion(this.x, this.y, this.z, this.w);
  993. };
  994. Quaternion.prototype.copyFrom = function (other) {
  995. this.x = other.x;
  996. this.y = other.y;
  997. this.z = other.z;
  998. this.w = other.w;
  999. };
  1000. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1001. this.x = x;
  1002. this.y = y;
  1003. this.z = z;
  1004. this.w = w;
  1005. };
  1006. Quaternion.prototype.add = function (other) {
  1007. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1008. };
  1009. Quaternion.prototype.subtract = function (other) {
  1010. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1011. };
  1012. Quaternion.prototype.scale = function (value) {
  1013. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1014. };
  1015. Quaternion.prototype.multiply = function (q1) {
  1016. var result = new Quaternion(0, 0, 0, 1.0);
  1017. this.multiplyToRef(q1, result);
  1018. return result;
  1019. };
  1020. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1021. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1022. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1023. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1024. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1025. };
  1026. Quaternion.prototype.length = function () {
  1027. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1028. };
  1029. Quaternion.prototype.normalize = function () {
  1030. var length = 1.0 / this.length();
  1031. this.x *= length;
  1032. this.y *= length;
  1033. this.z *= length;
  1034. this.w *= length;
  1035. };
  1036. Quaternion.prototype.toEulerAngles = function () {
  1037. var result = Vector3.Zero();
  1038. this.toEulerAnglesToRef(result);
  1039. return result;
  1040. };
  1041. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1042. //result is an EulerAngles in the in the z-x-z convention
  1043. var qx = this.x;
  1044. var qy = this.y;
  1045. var qz = this.z;
  1046. var qw = this.w;
  1047. var qxy = qx * qy;
  1048. var qxz = qx * qz;
  1049. var qwy = qw * qy;
  1050. var qwz = qw * qz;
  1051. var qwx = qw * qx;
  1052. var qyz = qy * qz;
  1053. var sqx = qx * qx;
  1054. var sqy = qy * qy;
  1055. var determinant = sqx + sqy;
  1056. if (determinant !== 0.000 && determinant !== 1.000) {
  1057. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1058. result.y = Math.acos(1 - 2 * determinant);
  1059. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1060. } else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. 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)
  1065. } else {
  1066. 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)
  1067. result.y = Math.PI;
  1068. result.z = 0.0;
  1069. }
  1070. }
  1071. };
  1072. Quaternion.prototype.toRotationMatrix = function (result) {
  1073. var xx = this.x * this.x;
  1074. var yy = this.y * this.y;
  1075. var zz = this.z * this.z;
  1076. var xy = this.x * this.y;
  1077. var zw = this.z * this.w;
  1078. var zx = this.z * this.x;
  1079. var yw = this.y * this.w;
  1080. var yz = this.y * this.z;
  1081. var xw = this.x * this.w;
  1082. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1083. result.m[1] = 2.0 * (xy + zw);
  1084. result.m[2] = 2.0 * (zx - yw);
  1085. result.m[3] = 0;
  1086. result.m[4] = 2.0 * (xy - zw);
  1087. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1088. result.m[6] = 2.0 * (yz + xw);
  1089. result.m[7] = 0;
  1090. result.m[8] = 2.0 * (zx + yw);
  1091. result.m[9] = 2.0 * (yz - xw);
  1092. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1093. result.m[11] = 0;
  1094. result.m[12] = 0;
  1095. result.m[13] = 0;
  1096. result.m[14] = 0;
  1097. result.m[15] = 1.0;
  1098. };
  1099. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1100. var data = matrix.m;
  1101. var m11 = data[0], m12 = data[4], m13 = data[8];
  1102. var m21 = data[1], m22 = data[5], m23 = data[9];
  1103. var m31 = data[2], m32 = data[6], m33 = data[10];
  1104. var trace = m11 + m22 + m33;
  1105. var s;
  1106. if (trace > 0) {
  1107. s = 0.5 / Math.sqrt(trace + 1.0);
  1108. this.w = 0.25 / s;
  1109. this.x = (m32 - m23) * s;
  1110. this.y = (m13 - m31) * s;
  1111. this.z = (m21 - m12) * s;
  1112. return;
  1113. }
  1114. if (m11 > m22 && m11 > m33) {
  1115. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1116. this.w = (m32 - m23) / s;
  1117. this.x = 0.25 * s;
  1118. this.y = (m12 + m21) / s;
  1119. this.z = (m13 + m31) / s;
  1120. return;
  1121. }
  1122. if (m22 > m33) {
  1123. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1124. this.w = (m13 - m31) / s;
  1125. this.x = (m12 + m21) / s;
  1126. this.y = 0.25 * s;
  1127. this.z = (m23 + m32) / s;
  1128. return;
  1129. }
  1130. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1131. this.w = (m21 - m12) / s;
  1132. this.x = (m13 + m31) / s;
  1133. this.y = (m23 + m32) / s;
  1134. this.z = 0.25 * s;
  1135. };
  1136. // Statics
  1137. Quaternion.Inverse = function (q) {
  1138. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1139. };
  1140. Quaternion.RotationAxis = function (axis, angle) {
  1141. var result = new Quaternion();
  1142. var sin = Math.sin(angle / 2);
  1143. result.w = Math.cos(angle / 2);
  1144. result.x = axis.x * sin;
  1145. result.y = axis.y * sin;
  1146. result.z = axis.z * sin;
  1147. return result;
  1148. };
  1149. Quaternion.FromArray = function (array, offset) {
  1150. if (!offset) {
  1151. offset = 0;
  1152. }
  1153. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1154. };
  1155. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1156. var result = new Quaternion();
  1157. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1158. return result;
  1159. };
  1160. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1161. var halfRoll = roll * 0.5;
  1162. var halfPitch = pitch * 0.5;
  1163. var halfYaw = yaw * 0.5;
  1164. var sinRoll = Math.sin(halfRoll);
  1165. var cosRoll = Math.cos(halfRoll);
  1166. var sinPitch = Math.sin(halfPitch);
  1167. var cosPitch = Math.cos(halfPitch);
  1168. var sinYaw = Math.sin(halfYaw);
  1169. var cosYaw = Math.cos(halfYaw);
  1170. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1171. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1172. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1173. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1174. };
  1175. Quaternion.Slerp = function (left, right, amount) {
  1176. var num2;
  1177. var num3;
  1178. var num = amount;
  1179. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1180. var flag = false;
  1181. if (num4 < 0) {
  1182. flag = true;
  1183. num4 = -num4;
  1184. }
  1185. if (num4 > 0.999999) {
  1186. num3 = 1 - num;
  1187. num2 = flag ? -num : num;
  1188. } else {
  1189. var num5 = Math.acos(num4);
  1190. var num6 = (1.0 / Math.sin(num5));
  1191. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1192. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1193. }
  1194. 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));
  1195. };
  1196. return Quaternion;
  1197. })();
  1198. BABYLON.Quaternion = Quaternion;
  1199. var Matrix = (function () {
  1200. function Matrix() {
  1201. this.m = new Float32Array(16);
  1202. }
  1203. // Properties
  1204. Matrix.prototype.isIdentity = function () {
  1205. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1206. return false;
  1207. 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)
  1208. return false;
  1209. return true;
  1210. };
  1211. Matrix.prototype.determinant = function () {
  1212. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1213. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1214. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1215. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1216. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1217. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1218. 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))));
  1219. };
  1220. // Methods
  1221. Matrix.prototype.toArray = function () {
  1222. return this.m;
  1223. };
  1224. Matrix.prototype.asArray = function () {
  1225. return this.toArray();
  1226. };
  1227. Matrix.prototype.invert = function () {
  1228. this.invertToRef(this);
  1229. };
  1230. Matrix.prototype.invertToRef = function (other) {
  1231. var l1 = this.m[0];
  1232. var l2 = this.m[1];
  1233. var l3 = this.m[2];
  1234. var l4 = this.m[3];
  1235. var l5 = this.m[4];
  1236. var l6 = this.m[5];
  1237. var l7 = this.m[6];
  1238. var l8 = this.m[7];
  1239. var l9 = this.m[8];
  1240. var l10 = this.m[9];
  1241. var l11 = this.m[10];
  1242. var l12 = this.m[11];
  1243. var l13 = this.m[12];
  1244. var l14 = this.m[13];
  1245. var l15 = this.m[14];
  1246. var l16 = this.m[15];
  1247. var l17 = (l11 * l16) - (l12 * l15);
  1248. var l18 = (l10 * l16) - (l12 * l14);
  1249. var l19 = (l10 * l15) - (l11 * l14);
  1250. var l20 = (l9 * l16) - (l12 * l13);
  1251. var l21 = (l9 * l15) - (l11 * l13);
  1252. var l22 = (l9 * l14) - (l10 * l13);
  1253. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1254. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1255. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1256. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1257. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1258. var l28 = (l7 * l16) - (l8 * l15);
  1259. var l29 = (l6 * l16) - (l8 * l14);
  1260. var l30 = (l6 * l15) - (l7 * l14);
  1261. var l31 = (l5 * l16) - (l8 * l13);
  1262. var l32 = (l5 * l15) - (l7 * l13);
  1263. var l33 = (l5 * l14) - (l6 * l13);
  1264. var l34 = (l7 * l12) - (l8 * l11);
  1265. var l35 = (l6 * l12) - (l8 * l10);
  1266. var l36 = (l6 * l11) - (l7 * l10);
  1267. var l37 = (l5 * l12) - (l8 * l9);
  1268. var l38 = (l5 * l11) - (l7 * l9);
  1269. var l39 = (l5 * l10) - (l6 * l9);
  1270. other.m[0] = l23 * l27;
  1271. other.m[4] = l24 * l27;
  1272. other.m[8] = l25 * l27;
  1273. other.m[12] = l26 * l27;
  1274. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1275. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1276. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1277. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1278. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1279. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1280. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1281. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1282. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1283. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1284. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1285. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1286. };
  1287. Matrix.prototype.setTranslation = function (vector3) {
  1288. this.m[12] = vector3.x;
  1289. this.m[13] = vector3.y;
  1290. this.m[14] = vector3.z;
  1291. };
  1292. Matrix.prototype.multiply = function (other) {
  1293. var result = new Matrix();
  1294. this.multiplyToRef(other, result);
  1295. return result;
  1296. };
  1297. Matrix.prototype.copyFrom = function (other) {
  1298. for (var index = 0; index < 16; index++) {
  1299. this.m[index] = other.m[index];
  1300. }
  1301. };
  1302. Matrix.prototype.copyToArray = function (array, offset) {
  1303. if (typeof offset === "undefined") { offset = 0; }
  1304. for (var index = 0; index < 16; index++) {
  1305. array[offset + index] = this.m[index];
  1306. }
  1307. };
  1308. Matrix.prototype.multiplyToRef = function (other, result) {
  1309. this.multiplyToArray(other, result.m, 0);
  1310. };
  1311. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1312. var tm0 = this.m[0];
  1313. var tm1 = this.m[1];
  1314. var tm2 = this.m[2];
  1315. var tm3 = this.m[3];
  1316. var tm4 = this.m[4];
  1317. var tm5 = this.m[5];
  1318. var tm6 = this.m[6];
  1319. var tm7 = this.m[7];
  1320. var tm8 = this.m[8];
  1321. var tm9 = this.m[9];
  1322. var tm10 = this.m[10];
  1323. var tm11 = this.m[11];
  1324. var tm12 = this.m[12];
  1325. var tm13 = this.m[13];
  1326. var tm14 = this.m[14];
  1327. var tm15 = this.m[15];
  1328. var om0 = other.m[0];
  1329. var om1 = other.m[1];
  1330. var om2 = other.m[2];
  1331. var om3 = other.m[3];
  1332. var om4 = other.m[4];
  1333. var om5 = other.m[5];
  1334. var om6 = other.m[6];
  1335. var om7 = other.m[7];
  1336. var om8 = other.m[8];
  1337. var om9 = other.m[9];
  1338. var om10 = other.m[10];
  1339. var om11 = other.m[11];
  1340. var om12 = other.m[12];
  1341. var om13 = other.m[13];
  1342. var om14 = other.m[14];
  1343. var om15 = other.m[15];
  1344. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1345. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1346. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1347. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1348. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1349. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1350. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1351. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1352. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1353. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1354. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1355. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1356. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1357. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1358. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1359. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1360. };
  1361. Matrix.prototype.equals = function (value) {
  1362. 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]);
  1363. };
  1364. Matrix.prototype.clone = function () {
  1365. 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]);
  1366. };
  1367. // Statics
  1368. Matrix.FromArray = function (array, offset) {
  1369. var result = new Matrix();
  1370. if (!offset) {
  1371. offset = 0;
  1372. }
  1373. Matrix.FromArrayToRef(array, offset, result);
  1374. return result;
  1375. };
  1376. Matrix.FromArrayToRef = function (array, offset, result) {
  1377. for (var index = 0; index < 16; index++) {
  1378. result.m[index] = array[index + offset];
  1379. }
  1380. };
  1381. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1382. result.m[0] = initialM11;
  1383. result.m[1] = initialM12;
  1384. result.m[2] = initialM13;
  1385. result.m[3] = initialM14;
  1386. result.m[4] = initialM21;
  1387. result.m[5] = initialM22;
  1388. result.m[6] = initialM23;
  1389. result.m[7] = initialM24;
  1390. result.m[8] = initialM31;
  1391. result.m[9] = initialM32;
  1392. result.m[10] = initialM33;
  1393. result.m[11] = initialM34;
  1394. result.m[12] = initialM41;
  1395. result.m[13] = initialM42;
  1396. result.m[14] = initialM43;
  1397. result.m[15] = initialM44;
  1398. };
  1399. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1400. var result = new Matrix();
  1401. result.m[0] = initialM11;
  1402. result.m[1] = initialM12;
  1403. result.m[2] = initialM13;
  1404. result.m[3] = initialM14;
  1405. result.m[4] = initialM21;
  1406. result.m[5] = initialM22;
  1407. result.m[6] = initialM23;
  1408. result.m[7] = initialM24;
  1409. result.m[8] = initialM31;
  1410. result.m[9] = initialM32;
  1411. result.m[10] = initialM33;
  1412. result.m[11] = initialM34;
  1413. result.m[12] = initialM41;
  1414. result.m[13] = initialM42;
  1415. result.m[14] = initialM43;
  1416. result.m[15] = initialM44;
  1417. return result;
  1418. };
  1419. Matrix.Identity = function () {
  1420. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1421. };
  1422. Matrix.IdentityToRef = function (result) {
  1423. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1424. };
  1425. Matrix.Zero = function () {
  1426. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1427. };
  1428. Matrix.RotationX = function (angle) {
  1429. var result = new Matrix();
  1430. Matrix.RotationXToRef(angle, result);
  1431. return result;
  1432. };
  1433. Matrix.Invert = function (source) {
  1434. var result = new Matrix();
  1435. source.invertToRef(result);
  1436. return result;
  1437. };
  1438. Matrix.RotationXToRef = function (angle, result) {
  1439. var s = Math.sin(angle);
  1440. var c = Math.cos(angle);
  1441. result.m[0] = 1.0;
  1442. result.m[15] = 1.0;
  1443. result.m[5] = c;
  1444. result.m[10] = c;
  1445. result.m[9] = -s;
  1446. result.m[6] = s;
  1447. result.m[1] = 0;
  1448. result.m[2] = 0;
  1449. result.m[3] = 0;
  1450. result.m[4] = 0;
  1451. result.m[7] = 0;
  1452. result.m[8] = 0;
  1453. result.m[11] = 0;
  1454. result.m[12] = 0;
  1455. result.m[13] = 0;
  1456. result.m[14] = 0;
  1457. };
  1458. Matrix.RotationY = function (angle) {
  1459. var result = new Matrix();
  1460. Matrix.RotationYToRef(angle, result);
  1461. return result;
  1462. };
  1463. Matrix.RotationYToRef = function (angle, result) {
  1464. var s = Math.sin(angle);
  1465. var c = Math.cos(angle);
  1466. result.m[5] = 1.0;
  1467. result.m[15] = 1.0;
  1468. result.m[0] = c;
  1469. result.m[2] = -s;
  1470. result.m[8] = s;
  1471. result.m[10] = c;
  1472. result.m[1] = 0;
  1473. result.m[3] = 0;
  1474. result.m[4] = 0;
  1475. result.m[6] = 0;
  1476. result.m[7] = 0;
  1477. result.m[9] = 0;
  1478. result.m[11] = 0;
  1479. result.m[12] = 0;
  1480. result.m[13] = 0;
  1481. result.m[14] = 0;
  1482. };
  1483. Matrix.RotationZ = function (angle) {
  1484. var result = new Matrix();
  1485. Matrix.RotationZToRef(angle, result);
  1486. return result;
  1487. };
  1488. Matrix.RotationZToRef = function (angle, result) {
  1489. var s = Math.sin(angle);
  1490. var c = Math.cos(angle);
  1491. result.m[10] = 1.0;
  1492. result.m[15] = 1.0;
  1493. result.m[0] = c;
  1494. result.m[1] = s;
  1495. result.m[4] = -s;
  1496. result.m[5] = c;
  1497. result.m[2] = 0;
  1498. result.m[3] = 0;
  1499. result.m[6] = 0;
  1500. result.m[7] = 0;
  1501. result.m[8] = 0;
  1502. result.m[9] = 0;
  1503. result.m[11] = 0;
  1504. result.m[12] = 0;
  1505. result.m[13] = 0;
  1506. result.m[14] = 0;
  1507. };
  1508. Matrix.RotationAxis = function (axis, angle) {
  1509. var s = Math.sin(-angle);
  1510. var c = Math.cos(-angle);
  1511. var c1 = 1 - c;
  1512. axis.normalize();
  1513. var result = Matrix.Zero();
  1514. result.m[0] = (axis.x * axis.x) * c1 + c;
  1515. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1516. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1517. result.m[3] = 0.0;
  1518. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1519. result.m[5] = (axis.y * axis.y) * c1 + c;
  1520. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1521. result.m[7] = 0.0;
  1522. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1523. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1524. result.m[10] = (axis.z * axis.z) * c1 + c;
  1525. result.m[11] = 0.0;
  1526. result.m[15] = 1.0;
  1527. return result;
  1528. };
  1529. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1530. var result = new Matrix();
  1531. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1532. return result;
  1533. };
  1534. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1535. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1536. this._tempQuaternion.toRotationMatrix(result);
  1537. };
  1538. Matrix.Scaling = function (x, y, z) {
  1539. var result = Matrix.Zero();
  1540. Matrix.ScalingToRef(x, y, z, result);
  1541. return result;
  1542. };
  1543. Matrix.ScalingToRef = function (x, y, z, result) {
  1544. result.m[0] = x;
  1545. result.m[1] = 0;
  1546. result.m[2] = 0;
  1547. result.m[3] = 0;
  1548. result.m[4] = 0;
  1549. result.m[5] = y;
  1550. result.m[6] = 0;
  1551. result.m[7] = 0;
  1552. result.m[8] = 0;
  1553. result.m[9] = 0;
  1554. result.m[10] = z;
  1555. result.m[11] = 0;
  1556. result.m[12] = 0;
  1557. result.m[13] = 0;
  1558. result.m[14] = 0;
  1559. result.m[15] = 1.0;
  1560. };
  1561. Matrix.Translation = function (x, y, z) {
  1562. var result = Matrix.Identity();
  1563. Matrix.TranslationToRef(x, y, z, result);
  1564. return result;
  1565. };
  1566. Matrix.TranslationToRef = function (x, y, z, result) {
  1567. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1568. };
  1569. Matrix.LookAtLH = function (eye, target, up) {
  1570. var result = Matrix.Zero();
  1571. Matrix.LookAtLHToRef(eye, target, up, result);
  1572. return result;
  1573. };
  1574. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1575. // Z axis
  1576. target.subtractToRef(eye, this._zAxis);
  1577. this._zAxis.normalize();
  1578. // X axis
  1579. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1580. this._xAxis.normalize();
  1581. // Y axis
  1582. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1583. this._yAxis.normalize();
  1584. // Eye angles
  1585. var ex = -Vector3.Dot(this._xAxis, eye);
  1586. var ey = -Vector3.Dot(this._yAxis, eye);
  1587. var ez = -Vector3.Dot(this._zAxis, eye);
  1588. 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);
  1589. };
  1590. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1591. var hw = 2.0 / width;
  1592. var hh = 2.0 / height;
  1593. var id = 1.0 / (zfar - znear);
  1594. var nid = znear / (znear - zfar);
  1595. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1596. };
  1597. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1598. var matrix = Matrix.Zero();
  1599. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1600. return matrix;
  1601. };
  1602. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1603. result.m[0] = 2.0 / (right - left);
  1604. result.m[1] = result.m[2] = result.m[3] = 0;
  1605. result.m[5] = 2.0 / (top - bottom);
  1606. result.m[4] = result.m[6] = result.m[7] = 0;
  1607. result.m[10] = -1.0 / (znear - zfar);
  1608. result.m[8] = result.m[9] = result.m[11] = 0;
  1609. result.m[12] = (left + right) / (left - right);
  1610. result.m[13] = (top + bottom) / (bottom - top);
  1611. result.m[14] = znear / (znear - zfar);
  1612. result.m[15] = 1.0;
  1613. };
  1614. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1615. var matrix = Matrix.Zero();
  1616. matrix.m[0] = (2.0 * znear) / width;
  1617. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1618. matrix.m[5] = (2.0 * znear) / height;
  1619. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1620. matrix.m[10] = -zfar / (znear - zfar);
  1621. matrix.m[8] = matrix.m[9] = 0.0;
  1622. matrix.m[11] = 1.0;
  1623. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1624. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1625. return matrix;
  1626. };
  1627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1628. var matrix = Matrix.Zero();
  1629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1630. return matrix;
  1631. };
  1632. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1633. var tan = 1.0 / (Math.tan(fov * 0.5));
  1634. result.m[0] = tan / aspect;
  1635. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1636. result.m[5] = tan;
  1637. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1638. result.m[8] = result.m[9] = 0.0;
  1639. result.m[10] = -zfar / (znear - zfar);
  1640. result.m[11] = 1.0;
  1641. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1642. result.m[14] = (znear * zfar) / (znear - zfar);
  1643. };
  1644. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1645. var cw = viewport.width;
  1646. var ch = viewport.height;
  1647. var cx = viewport.x;
  1648. var cy = viewport.y;
  1649. 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);
  1650. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1651. };
  1652. Matrix.Transpose = function (matrix) {
  1653. var result = new Matrix();
  1654. result.m[0] = matrix.m[0];
  1655. result.m[1] = matrix.m[4];
  1656. result.m[2] = matrix.m[8];
  1657. result.m[3] = matrix.m[12];
  1658. result.m[4] = matrix.m[1];
  1659. result.m[5] = matrix.m[5];
  1660. result.m[6] = matrix.m[9];
  1661. result.m[7] = matrix.m[13];
  1662. result.m[8] = matrix.m[2];
  1663. result.m[9] = matrix.m[6];
  1664. result.m[10] = matrix.m[10];
  1665. result.m[11] = matrix.m[14];
  1666. result.m[12] = matrix.m[3];
  1667. result.m[13] = matrix.m[7];
  1668. result.m[14] = matrix.m[11];
  1669. result.m[15] = matrix.m[15];
  1670. return result;
  1671. };
  1672. Matrix.Reflection = function (plane) {
  1673. var matrix = new Matrix();
  1674. Matrix.ReflectionToRef(plane, matrix);
  1675. return matrix;
  1676. };
  1677. Matrix.ReflectionToRef = function (plane, result) {
  1678. plane.normalize();
  1679. var x = plane.normal.x;
  1680. var y = plane.normal.y;
  1681. var z = plane.normal.z;
  1682. var temp = -2 * x;
  1683. var temp2 = -2 * y;
  1684. var temp3 = -2 * z;
  1685. result.m[0] = (temp * x) + 1;
  1686. result.m[1] = temp2 * x;
  1687. result.m[2] = temp3 * x;
  1688. result.m[3] = 0.0;
  1689. result.m[4] = temp * y;
  1690. result.m[5] = (temp2 * y) + 1;
  1691. result.m[6] = temp3 * y;
  1692. result.m[7] = 0.0;
  1693. result.m[8] = temp * z;
  1694. result.m[9] = temp2 * z;
  1695. result.m[10] = (temp3 * z) + 1;
  1696. result.m[11] = 0.0;
  1697. result.m[12] = temp * plane.d;
  1698. result.m[13] = temp2 * plane.d;
  1699. result.m[14] = temp3 * plane.d;
  1700. result.m[15] = 1.0;
  1701. };
  1702. Matrix._tempQuaternion = new Quaternion();
  1703. Matrix._xAxis = Vector3.Zero();
  1704. Matrix._yAxis = Vector3.Zero();
  1705. Matrix._zAxis = Vector3.Zero();
  1706. return Matrix;
  1707. })();
  1708. BABYLON.Matrix = Matrix;
  1709. var Plane = (function () {
  1710. function Plane(a, b, c, d) {
  1711. this.normal = new Vector3(a, b, c);
  1712. this.d = d;
  1713. }
  1714. Plane.prototype.asArray = function () {
  1715. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1716. };
  1717. // Methods
  1718. Plane.prototype.clone = function () {
  1719. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1720. };
  1721. Plane.prototype.normalize = function () {
  1722. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1723. var magnitude = 0;
  1724. if (norm !== 0) {
  1725. magnitude = 1.0 / norm;
  1726. }
  1727. this.normal.x *= magnitude;
  1728. this.normal.y *= magnitude;
  1729. this.normal.z *= magnitude;
  1730. this.d *= magnitude;
  1731. };
  1732. Plane.prototype.transform = function (transformation) {
  1733. var transposedMatrix = Matrix.Transpose(transformation);
  1734. var x = this.normal.x;
  1735. var y = this.normal.y;
  1736. var z = this.normal.z;
  1737. var d = this.d;
  1738. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1739. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1740. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1741. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1742. return new Plane(normalX, normalY, normalZ, finalD);
  1743. };
  1744. Plane.prototype.dotCoordinate = function (point) {
  1745. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1746. };
  1747. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1748. var x1 = point2.x - point1.x;
  1749. var y1 = point2.y - point1.y;
  1750. var z1 = point2.z - point1.z;
  1751. var x2 = point3.x - point1.x;
  1752. var y2 = point3.y - point1.y;
  1753. var z2 = point3.z - point1.z;
  1754. var yz = (y1 * z2) - (z1 * y2);
  1755. var xz = (z1 * x2) - (x1 * z2);
  1756. var xy = (x1 * y2) - (y1 * x2);
  1757. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1758. var invPyth;
  1759. if (pyth !== 0) {
  1760. invPyth = 1.0 / pyth;
  1761. } else {
  1762. invPyth = 0;
  1763. }
  1764. this.normal.x = yz * invPyth;
  1765. this.normal.y = xz * invPyth;
  1766. this.normal.z = xy * invPyth;
  1767. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1768. };
  1769. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1770. var dot = Vector3.Dot(this.normal, direction);
  1771. return (dot <= epsilon);
  1772. };
  1773. Plane.prototype.signedDistanceTo = function (point) {
  1774. return Vector3.Dot(point, this.normal) + this.d;
  1775. };
  1776. // Statics
  1777. Plane.FromArray = function (array) {
  1778. return new Plane(array[0], array[1], array[2], array[3]);
  1779. };
  1780. Plane.FromPoints = function (point1, point2, point3) {
  1781. var result = new Plane(0, 0, 0, 0);
  1782. result.copyFromPoints(point1, point2, point3);
  1783. return result;
  1784. };
  1785. Plane.FromPositionAndNormal = function (origin, normal) {
  1786. var result = new Plane(0, 0, 0, 0);
  1787. normal.normalize();
  1788. result.normal = normal;
  1789. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1790. return result;
  1791. };
  1792. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1793. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1794. return Vector3.Dot(point, normal) + d;
  1795. };
  1796. return Plane;
  1797. })();
  1798. BABYLON.Plane = Plane;
  1799. var Viewport = (function () {
  1800. function Viewport(x, y, width, height) {
  1801. this.x = x;
  1802. this.y = y;
  1803. this.width = width;
  1804. this.height = height;
  1805. }
  1806. Viewport.prototype.toGlobal = function (engine) {
  1807. var width = engine.getRenderWidth();
  1808. var height = engine.getRenderHeight();
  1809. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1810. };
  1811. return Viewport;
  1812. })();
  1813. BABYLON.Viewport = Viewport;
  1814. var Frustum = (function () {
  1815. function Frustum() {
  1816. }
  1817. Frustum.GetPlanes = function (transform) {
  1818. var frustumPlanes = [];
  1819. for (var index = 0; index < 6; index++) {
  1820. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1821. }
  1822. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1823. return frustumPlanes;
  1824. };
  1825. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1826. // Near
  1827. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1828. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1829. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1830. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1831. frustumPlanes[0].normalize();
  1832. // Far
  1833. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1834. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1835. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1836. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1837. frustumPlanes[1].normalize();
  1838. // Left
  1839. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1840. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1841. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1842. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1843. frustumPlanes[2].normalize();
  1844. // Right
  1845. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1846. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1847. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1848. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1849. frustumPlanes[3].normalize();
  1850. // Top
  1851. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1852. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1853. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1854. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1855. frustumPlanes[4].normalize();
  1856. // Bottom
  1857. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1858. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1859. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1860. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1861. frustumPlanes[5].normalize();
  1862. };
  1863. return Frustum;
  1864. })();
  1865. BABYLON.Frustum = Frustum;
  1866. var Ray = (function () {
  1867. function Ray(origin, direction, length) {
  1868. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1869. this.origin = origin;
  1870. this.direction = direction;
  1871. this.length = length;
  1872. }
  1873. // Methods
  1874. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1875. var d = 0.0;
  1876. var maxValue = Number.MAX_VALUE;
  1877. if (Math.abs(this.direction.x) < 0.0000001) {
  1878. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1879. return false;
  1880. }
  1881. } else {
  1882. var inv = 1.0 / this.direction.x;
  1883. var min = (minimum.x - this.origin.x) * inv;
  1884. var max = (maximum.x - this.origin.x) * inv;
  1885. if (max === -Infinity) {
  1886. max = Infinity;
  1887. }
  1888. if (min > max) {
  1889. var temp = min;
  1890. min = max;
  1891. max = temp;
  1892. }
  1893. d = Math.max(min, d);
  1894. maxValue = Math.min(max, maxValue);
  1895. if (d > maxValue) {
  1896. return false;
  1897. }
  1898. }
  1899. if (Math.abs(this.direction.y) < 0.0000001) {
  1900. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1901. return false;
  1902. }
  1903. } else {
  1904. inv = 1.0 / this.direction.y;
  1905. min = (minimum.y - this.origin.y) * inv;
  1906. max = (maximum.y - this.origin.y) * inv;
  1907. if (max === -Infinity) {
  1908. max = Infinity;
  1909. }
  1910. if (min > max) {
  1911. temp = min;
  1912. min = max;
  1913. max = temp;
  1914. }
  1915. d = Math.max(min, d);
  1916. maxValue = Math.min(max, maxValue);
  1917. if (d > maxValue) {
  1918. return false;
  1919. }
  1920. }
  1921. if (Math.abs(this.direction.z) < 0.0000001) {
  1922. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1923. return false;
  1924. }
  1925. } else {
  1926. inv = 1.0 / this.direction.z;
  1927. min = (minimum.z - this.origin.z) * inv;
  1928. max = (maximum.z - this.origin.z) * inv;
  1929. if (max === -Infinity) {
  1930. max = Infinity;
  1931. }
  1932. if (min > max) {
  1933. temp = min;
  1934. min = max;
  1935. max = temp;
  1936. }
  1937. d = Math.max(min, d);
  1938. maxValue = Math.min(max, maxValue);
  1939. if (d > maxValue) {
  1940. return false;
  1941. }
  1942. }
  1943. return true;
  1944. };
  1945. Ray.prototype.intersectsBox = function (box) {
  1946. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1947. };
  1948. Ray.prototype.intersectsSphere = function (sphere) {
  1949. var x = sphere.center.x - this.origin.x;
  1950. var y = sphere.center.y - this.origin.y;
  1951. var z = sphere.center.z - this.origin.z;
  1952. var pyth = (x * x) + (y * y) + (z * z);
  1953. var rr = sphere.radius * sphere.radius;
  1954. if (pyth <= rr) {
  1955. return true;
  1956. }
  1957. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1958. if (dot < 0.0) {
  1959. return false;
  1960. }
  1961. var temp = pyth - (dot * dot);
  1962. return temp <= rr;
  1963. };
  1964. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1965. if (!this._edge1) {
  1966. this._edge1 = Vector3.Zero();
  1967. this._edge2 = Vector3.Zero();
  1968. this._pvec = Vector3.Zero();
  1969. this._tvec = Vector3.Zero();
  1970. this._qvec = Vector3.Zero();
  1971. }
  1972. vertex1.subtractToRef(vertex0, this._edge1);
  1973. vertex2.subtractToRef(vertex0, this._edge2);
  1974. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1975. var det = Vector3.Dot(this._edge1, this._pvec);
  1976. if (det === 0) {
  1977. return null;
  1978. }
  1979. var invdet = 1 / det;
  1980. this.origin.subtractToRef(vertex0, this._tvec);
  1981. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1982. if (bu < 0 || bu > 1.0) {
  1983. return null;
  1984. }
  1985. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1986. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1987. if (bv < 0 || bu + bv > 1.0) {
  1988. return null;
  1989. }
  1990. //check if the distance is longer than the predefined length.
  1991. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1992. if (distance > this.length) {
  1993. return null;
  1994. }
  1995. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1996. };
  1997. // Statics
  1998. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1999. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2000. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2001. var direction = end.subtract(start);
  2002. direction.normalize();
  2003. return new Ray(start, direction);
  2004. };
  2005. /**
  2006. * 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
  2007. * transformed to the given world matrix.
  2008. * @param origin The origin point
  2009. * @param end The end point
  2010. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2011. */
  2012. Ray.CreateNewFromTo = function (origin, end, world) {
  2013. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2014. var direction = end.subtract(origin);
  2015. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2016. direction.normalize();
  2017. return Ray.Transform(new Ray(origin, direction, length), world);
  2018. };
  2019. Ray.Transform = function (ray, matrix) {
  2020. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2021. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2022. return new Ray(newOrigin, newDirection, ray.length);
  2023. };
  2024. return Ray;
  2025. })();
  2026. BABYLON.Ray = Ray;
  2027. (function (Space) {
  2028. Space[Space["LOCAL"] = 0] = "LOCAL";
  2029. Space[Space["WORLD"] = 1] = "WORLD";
  2030. })(BABYLON.Space || (BABYLON.Space = {}));
  2031. var Space = BABYLON.Space;
  2032. var Axis = (function () {
  2033. function Axis() {
  2034. }
  2035. Axis.X = new Vector3(1, 0, 0);
  2036. Axis.Y = new Vector3(0, 1, 0);
  2037. Axis.Z = new Vector3(0, 0, 1);
  2038. return Axis;
  2039. })();
  2040. BABYLON.Axis = Axis;
  2041. ;
  2042. var BezierCurve = (function () {
  2043. function BezierCurve() {
  2044. }
  2045. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2046. // Extract X (which is equal to time here)
  2047. var f0 = 1 - 3 * x2 + 3 * x1;
  2048. var f1 = 3 * x2 - 6 * x1;
  2049. var f2 = 3 * x1;
  2050. var refinedT = t;
  2051. for (var i = 0; i < 5; i++) {
  2052. var refinedT2 = refinedT * refinedT;
  2053. var refinedT3 = refinedT2 * refinedT;
  2054. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2055. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2056. refinedT -= (x - t) * slope;
  2057. refinedT = Math.min(1, Math.max(0, refinedT));
  2058. }
  2059. // Resolve cubic bezier for the given x
  2060. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2061. };
  2062. return BezierCurve;
  2063. })();
  2064. BABYLON.BezierCurve = BezierCurve;
  2065. (function (Orientation) {
  2066. Orientation[Orientation["CW"] = 0] = "CW";
  2067. Orientation[Orientation["CCW"] = 1] = "CCW";
  2068. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2069. var Orientation = BABYLON.Orientation;
  2070. var Angle = (function () {
  2071. function Angle(radians) {
  2072. var _this = this;
  2073. this.degrees = function () {
  2074. return _this._radians * 180 / Math.PI;
  2075. };
  2076. this.radians = function () {
  2077. return _this._radians;
  2078. };
  2079. this._radians = radians;
  2080. if (this._radians < 0)
  2081. this._radians += (2 * Math.PI);
  2082. }
  2083. Angle.BetweenTwoPoints = function (a, b) {
  2084. var delta = b.subtract(a);
  2085. var theta = Math.atan2(delta.y, delta.x);
  2086. return new Angle(theta);
  2087. };
  2088. Angle.FromRadians = function (radians) {
  2089. return new Angle(radians);
  2090. };
  2091. Angle.FromDegrees = function (degrees) {
  2092. return new Angle(degrees * Math.PI / 180);
  2093. };
  2094. return Angle;
  2095. })();
  2096. BABYLON.Angle = Angle;
  2097. var Arc2 = (function () {
  2098. function Arc2(startPoint, midPoint, endPoint) {
  2099. this.startPoint = startPoint;
  2100. this.midPoint = midPoint;
  2101. this.endPoint = endPoint;
  2102. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2103. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2104. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2105. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2106. 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);
  2107. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2108. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2109. var a1 = this.startAngle.degrees();
  2110. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2111. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2112. // angles correction
  2113. if (a2 - a1 > +180.0)
  2114. a2 -= 360.0;
  2115. if (a2 - a1 < -180.0)
  2116. a2 += 360.0;
  2117. if (a3 - a2 > +180.0)
  2118. a3 -= 360.0;
  2119. if (a3 - a2 < -180.0)
  2120. a3 += 360.0;
  2121. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2122. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2123. }
  2124. return Arc2;
  2125. })();
  2126. BABYLON.Arc2 = Arc2;
  2127. var PathCursor = (function () {
  2128. function PathCursor(path) {
  2129. this.path = path;
  2130. this._onchange = new Array();
  2131. this.value = 0;
  2132. this.animations = new Array();
  2133. }
  2134. PathCursor.prototype.getPoint = function () {
  2135. var point = this.path.getPointAtLengthPosition(this.value);
  2136. return new Vector3(point.x, 0, point.y);
  2137. };
  2138. PathCursor.prototype.moveAhead = function (step) {
  2139. if (typeof step === "undefined") { step = 0.002; }
  2140. this.move(step);
  2141. };
  2142. PathCursor.prototype.moveBack = function (step) {
  2143. if (typeof step === "undefined") { step = 0.002; }
  2144. this.move(-step);
  2145. };
  2146. PathCursor.prototype.move = function (step) {
  2147. if (Math.abs(step) > 1) {
  2148. throw "step size should be less than 1.";
  2149. }
  2150. this.value += step;
  2151. this.ensureLimits();
  2152. this.raiseOnChange();
  2153. };
  2154. PathCursor.prototype.ensureLimits = function () {
  2155. while (this.value > 1) {
  2156. this.value -= 1;
  2157. }
  2158. while (this.value < 0) {
  2159. this.value += 1;
  2160. }
  2161. };
  2162. // used by animation engine
  2163. PathCursor.prototype.markAsDirty = function (propertyName) {
  2164. this.ensureLimits();
  2165. this.raiseOnChange();
  2166. };
  2167. PathCursor.prototype.raiseOnChange = function () {
  2168. var _this = this;
  2169. this._onchange.forEach(function (f) {
  2170. return f(_this);
  2171. });
  2172. };
  2173. PathCursor.prototype.onchange = function (f) {
  2174. this._onchange.push(f);
  2175. };
  2176. return PathCursor;
  2177. })();
  2178. BABYLON.PathCursor = PathCursor;
  2179. var Path2 = (function () {
  2180. function Path2(x, y) {
  2181. this._points = [];
  2182. this._length = 0;
  2183. this.closed = false;
  2184. this._points.push(new Vector2(x, y));
  2185. }
  2186. Path2.prototype.addLineTo = function (x, y) {
  2187. if (closed) {
  2188. BABYLON.Tools.Error("cannot add lines to closed paths");
  2189. return this;
  2190. }
  2191. var newPoint = new Vector2(x, y);
  2192. var previousPoint = this._points[this._points.length - 1];
  2193. this._points.push(newPoint);
  2194. this._length += newPoint.subtract(previousPoint).length();
  2195. return this;
  2196. };
  2197. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2198. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2199. if (closed) {
  2200. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2201. return this;
  2202. }
  2203. var startPoint = this._points[this._points.length - 1];
  2204. var midPoint = new Vector2(midX, midY);
  2205. var endPoint = new Vector2(endX, endY);
  2206. var arc = new Arc2(startPoint, midPoint, endPoint);
  2207. var increment = arc.angle.radians() / numberOfSegments;
  2208. if (arc.orientation === 0 /* CW */)
  2209. increment *= -1;
  2210. var currentAngle = arc.startAngle.radians() + increment;
  2211. for (var i = 0; i < numberOfSegments; i++) {
  2212. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2213. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2214. this.addLineTo(x, y);
  2215. currentAngle += increment;
  2216. }
  2217. return this;
  2218. };
  2219. Path2.prototype.close = function () {
  2220. this.closed = true;
  2221. return this;
  2222. };
  2223. Path2.prototype.length = function () {
  2224. var result = this._length;
  2225. if (!this.closed) {
  2226. var lastPoint = this._points[this._points.length - 1];
  2227. var firstPoint = this._points[0];
  2228. result += (firstPoint.subtract(lastPoint).length());
  2229. }
  2230. return result;
  2231. };
  2232. Path2.prototype.getPoints = function () {
  2233. return this._points;
  2234. };
  2235. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2236. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2237. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2238. return;
  2239. }
  2240. var lengthPosition = normalizedLengthPosition * this.length();
  2241. var previousOffset = 0;
  2242. for (var i = 0; i < this._points.length; i++) {
  2243. var j = (i + 1) % this._points.length;
  2244. var a = this._points[i];
  2245. var b = this._points[j];
  2246. var bToA = b.subtract(a);
  2247. var nextOffset = (bToA.length() + previousOffset);
  2248. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2249. var dir = bToA.normalize();
  2250. var localOffset = lengthPosition - previousOffset;
  2251. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2252. }
  2253. previousOffset = nextOffset;
  2254. }
  2255. BABYLON.Tools.Error("internal error");
  2256. };
  2257. Path2.StartingAt = function (x, y) {
  2258. return new Path2(x, y);
  2259. };
  2260. return Path2;
  2261. })();
  2262. BABYLON.Path2 = Path2;
  2263. })(BABYLON || (BABYLON = {}));
  2264. //# sourceMappingURL=babylon.math.js.map
  2265. var BABYLON;
  2266. (function (BABYLON) {
  2267. // Screenshots
  2268. var screenshotCanvas;
  2269. var cloneValue = function (source, destinationObject) {
  2270. if (!source)
  2271. return null;
  2272. if (source instanceof BABYLON.Mesh) {
  2273. return null;
  2274. }
  2275. if (source instanceof BABYLON.SubMesh) {
  2276. return source.clone(destinationObject);
  2277. } else if (source.clone) {
  2278. return source.clone();
  2279. }
  2280. return null;
  2281. };
  2282. var Tools = (function () {
  2283. function Tools() {
  2284. }
  2285. Tools.GetFilename = function (path) {
  2286. var index = path.lastIndexOf("/");
  2287. if (index < 0)
  2288. return path;
  2289. return path.substring(index + 1);
  2290. };
  2291. Tools.GetDOMTextContent = function (element) {
  2292. var result = "";
  2293. var child = element.firstChild;
  2294. while (child) {
  2295. if (child.nodeType == 3) {
  2296. result += child.textContent;
  2297. }
  2298. child = child.nextSibling;
  2299. }
  2300. return result;
  2301. };
  2302. Tools.ToDegrees = function (angle) {
  2303. return angle * 180 / Math.PI;
  2304. };
  2305. Tools.ToRadians = function (angle) {
  2306. return angle * Math.PI / 180;
  2307. };
  2308. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2309. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2310. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2311. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2312. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2313. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2314. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2315. }
  2316. return {
  2317. minimum: minimum,
  2318. maximum: maximum
  2319. };
  2320. };
  2321. Tools.ExtractMinAndMax = function (positions, start, count) {
  2322. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2323. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2324. for (var index = start; index < start + count; index++) {
  2325. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2326. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2327. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2328. }
  2329. return {
  2330. minimum: minimum,
  2331. maximum: maximum
  2332. };
  2333. };
  2334. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2335. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2336. return undefined;
  2337. return Array.isArray(obj) ? obj : [obj];
  2338. };
  2339. // Misc.
  2340. Tools.GetPointerPrefix = function () {
  2341. var eventPrefix = "pointer";
  2342. // Check if hand.js is referenced or if the browser natively supports pointer events
  2343. if (!navigator.pointerEnabled) {
  2344. eventPrefix = "mouse";
  2345. }
  2346. return eventPrefix;
  2347. };
  2348. Tools.QueueNewFrame = function (func) {
  2349. if (window.requestAnimationFrame)
  2350. window.requestAnimationFrame(func);
  2351. else if (window.msRequestAnimationFrame)
  2352. window.msRequestAnimationFrame(func);
  2353. else if (window.webkitRequestAnimationFrame)
  2354. window.webkitRequestAnimationFrame(func);
  2355. else if (window.mozRequestAnimationFrame)
  2356. window.mozRequestAnimationFrame(func);
  2357. else if (window.oRequestAnimationFrame)
  2358. window.oRequestAnimationFrame(func);
  2359. else {
  2360. window.setTimeout(func, 16);
  2361. }
  2362. };
  2363. Tools.RequestFullscreen = function (element) {
  2364. if (element.requestFullscreen)
  2365. element.requestFullscreen();
  2366. else if (element.msRequestFullscreen)
  2367. element.msRequestFullscreen();
  2368. else if (element.webkitRequestFullscreen)
  2369. element.webkitRequestFullscreen();
  2370. else if (element.mozRequestFullScreen)
  2371. element.mozRequestFullScreen();
  2372. };
  2373. Tools.ExitFullscreen = function () {
  2374. if (document.exitFullscreen) {
  2375. document.exitFullscreen();
  2376. } else if (document.mozCancelFullScreen) {
  2377. document.mozCancelFullScreen();
  2378. } else if (document.webkitCancelFullScreen) {
  2379. document.webkitCancelFullScreen();
  2380. } else if (document.msCancelFullScreen) {
  2381. document.msCancelFullScreen();
  2382. }
  2383. };
  2384. // External files
  2385. Tools.CleanUrl = function (url) {
  2386. url = url.replace(/#/mg, "%23");
  2387. return url;
  2388. };
  2389. Tools.LoadImage = function (url, onload, onerror, database) {
  2390. url = Tools.CleanUrl(url);
  2391. var img = new Image();
  2392. if (url.substr(0, 5) != "data:")
  2393. img.crossOrigin = 'anonymous';
  2394. img.onload = function () {
  2395. onload(img);
  2396. };
  2397. img.onerror = function (err) {
  2398. onerror(img, err);
  2399. };
  2400. var noIndexedDB = function () {
  2401. img.src = url;
  2402. };
  2403. var loadFromIndexedDB = function () {
  2404. database.loadImageFromDB(url, img);
  2405. };
  2406. //ANY database to do!
  2407. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2408. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2409. } else {
  2410. if (url.indexOf("file:") === -1) {
  2411. noIndexedDB();
  2412. } else {
  2413. try {
  2414. var textureName = url.substring(5);
  2415. var blobURL;
  2416. try {
  2417. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2418. } catch (ex) {
  2419. // Chrome doesn't support oneTimeOnly parameter
  2420. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2421. }
  2422. img.src = blobURL;
  2423. } catch (e) {
  2424. Tools.Log("Error while trying to load texture: " + textureName);
  2425. img.src = null;
  2426. }
  2427. }
  2428. }
  2429. return img;
  2430. };
  2431. //ANY
  2432. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2433. url = Tools.CleanUrl(url);
  2434. var noIndexedDB = function () {
  2435. var request = new XMLHttpRequest();
  2436. var loadUrl = Tools.BaseUrl + url;
  2437. request.open('GET', loadUrl, true);
  2438. if (useArrayBuffer) {
  2439. request.responseType = "arraybuffer";
  2440. }
  2441. request.onprogress = progressCallBack;
  2442. request.onreadystatechange = function () {
  2443. if (request.readyState == 4) {
  2444. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2445. callback(!useArrayBuffer ? request.responseText : request.response);
  2446. } else {
  2447. if (onError) {
  2448. onError();
  2449. } else {
  2450. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2451. }
  2452. }
  2453. }
  2454. };
  2455. request.send(null);
  2456. };
  2457. var loadFromIndexedDB = function () {
  2458. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2459. };
  2460. if (url.indexOf("file:") !== -1) {
  2461. var fileName = url.substring(5);
  2462. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2463. } else {
  2464. // Caching all files
  2465. if (database && database.enableSceneOffline) {
  2466. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2467. } else {
  2468. noIndexedDB();
  2469. }
  2470. }
  2471. };
  2472. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2473. var reader = new FileReader();
  2474. reader.onload = function (e) {
  2475. callback(e.target.result);
  2476. };
  2477. reader.onprogress = progressCallback;
  2478. reader.readAsDataURL(fileToLoad);
  2479. };
  2480. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2481. var reader = new FileReader();
  2482. reader.onload = function (e) {
  2483. callback(e.target.result);
  2484. };
  2485. reader.onprogress = progressCallBack;
  2486. if (!useArrayBuffer) {
  2487. // Asynchronous read
  2488. reader.readAsText(fileToLoad);
  2489. } else {
  2490. reader.readAsArrayBuffer(fileToLoad);
  2491. }
  2492. };
  2493. // Misc.
  2494. Tools.Clamp = function (value, min, max) {
  2495. if (typeof min === "undefined") { min = 0; }
  2496. if (typeof max === "undefined") { max = 1; }
  2497. return Math.min(max, Math.max(min, value));
  2498. };
  2499. Tools.Format = function (value, decimals) {
  2500. if (typeof decimals === "undefined") { decimals = 2; }
  2501. return value.toFixed(decimals);
  2502. };
  2503. Tools.CheckExtends = function (v, min, max) {
  2504. if (v.x < min.x)
  2505. min.x = v.x;
  2506. if (v.y < min.y)
  2507. min.y = v.y;
  2508. if (v.z < min.z)
  2509. min.z = v.z;
  2510. if (v.x > max.x)
  2511. max.x = v.x;
  2512. if (v.y > max.y)
  2513. max.y = v.y;
  2514. if (v.z > max.z)
  2515. max.z = v.z;
  2516. };
  2517. Tools.WithinEpsilon = function (a, b, epsilon) {
  2518. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2519. var num = a - b;
  2520. return -epsilon <= num && num <= epsilon;
  2521. };
  2522. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2523. for (var prop in source) {
  2524. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2525. continue;
  2526. }
  2527. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2528. continue;
  2529. }
  2530. var sourceValue = source[prop];
  2531. var typeOfSourceValue = typeof sourceValue;
  2532. if (typeOfSourceValue == "function") {
  2533. continue;
  2534. }
  2535. if (typeOfSourceValue == "object") {
  2536. if (sourceValue instanceof Array) {
  2537. destination[prop] = [];
  2538. if (sourceValue.length > 0) {
  2539. if (typeof sourceValue[0] == "object") {
  2540. for (var index = 0; index < sourceValue.length; index++) {
  2541. var clonedValue = cloneValue(sourceValue[index], destination);
  2542. if (destination[prop].indexOf(clonedValue) === -1) {
  2543. destination[prop].push(clonedValue);
  2544. }
  2545. }
  2546. } else {
  2547. destination[prop] = sourceValue.slice(0);
  2548. }
  2549. }
  2550. } else {
  2551. destination[prop] = cloneValue(sourceValue, destination);
  2552. }
  2553. } else {
  2554. destination[prop] = sourceValue;
  2555. }
  2556. }
  2557. };
  2558. Tools.IsEmpty = function (obj) {
  2559. for (var i in obj) {
  2560. return false;
  2561. }
  2562. return true;
  2563. };
  2564. Tools.RegisterTopRootEvents = function (events) {
  2565. for (var index = 0; index < events.length; index++) {
  2566. var event = events[index];
  2567. window.addEventListener(event.name, event.handler, false);
  2568. try {
  2569. if (window.parent) {
  2570. window.parent.addEventListener(event.name, event.handler, false);
  2571. }
  2572. } catch (e) {
  2573. // Silently fails...
  2574. }
  2575. }
  2576. };
  2577. Tools.UnregisterTopRootEvents = function (events) {
  2578. for (var index = 0; index < events.length; index++) {
  2579. var event = events[index];
  2580. window.removeEventListener(event.name, event.handler);
  2581. try {
  2582. if (window.parent) {
  2583. window.parent.removeEventListener(event.name, event.handler);
  2584. }
  2585. } catch (e) {
  2586. // Silently fails...
  2587. }
  2588. }
  2589. };
  2590. Tools.CreateScreenshot = function (engine, camera, size) {
  2591. var width;
  2592. var height;
  2593. var scene = camera.getScene();
  2594. var previousCamera = null;
  2595. if (scene.activeCamera !== camera) {
  2596. previousCamera = scene.activeCamera;
  2597. scene.activeCamera = camera;
  2598. }
  2599. //If a precision value is specified
  2600. if (size.precision) {
  2601. width = Math.round(engine.getRenderWidth() * size.precision);
  2602. height = Math.round(width / engine.getAspectRatio(camera));
  2603. size = { width: width, height: height };
  2604. } else if (size.width && size.height) {
  2605. width = size.width;
  2606. height = size.height;
  2607. } else if (size.width && !size.height) {
  2608. width = size.width;
  2609. height = Math.round(width / engine.getAspectRatio(camera));
  2610. size = { width: width, height: height };
  2611. } else if (size.height && !size.width) {
  2612. height = size.height;
  2613. width = Math.round(height * engine.getAspectRatio(camera));
  2614. size = { width: width, height: height };
  2615. } else if (!isNaN(size)) {
  2616. height = size;
  2617. width = size;
  2618. } else {
  2619. Tools.Error("Invalid 'size' parameter !");
  2620. return;
  2621. }
  2622. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2623. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2624. texture.renderList = engine.scenes[0].meshes;
  2625. texture.onAfterRender = function () {
  2626. // Read the contents of the framebuffer
  2627. var numberOfChannelsByLine = width * 4;
  2628. var halfHeight = height / 2;
  2629. //Reading datas from WebGL
  2630. var data = engine.readPixels(0, 0, width, height);
  2631. for (var i = 0; i < halfHeight; i++) {
  2632. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2633. var currentCell = j + i * numberOfChannelsByLine;
  2634. var targetLine = height - i - 1;
  2635. var targetCell = j + targetLine * numberOfChannelsByLine;
  2636. var temp = data[currentCell];
  2637. data[currentCell] = data[targetCell];
  2638. data[targetCell] = temp;
  2639. }
  2640. }
  2641. // Create a 2D canvas to store the result
  2642. if (!screenshotCanvas) {
  2643. screenshotCanvas = document.createElement('canvas');
  2644. }
  2645. screenshotCanvas.width = width;
  2646. screenshotCanvas.height = height;
  2647. var context = screenshotCanvas.getContext('2d');
  2648. // Copy the pixels to a 2D canvas
  2649. var imageData = context.createImageData(width, height);
  2650. imageData.data.set(data);
  2651. context.putImageData(imageData, 0, 0);
  2652. var base64Image = screenshotCanvas.toDataURL();
  2653. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2654. if (("download" in document.createElement("a"))) {
  2655. var a = window.document.createElement("a");
  2656. a.href = base64Image;
  2657. var date = new Date();
  2658. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2659. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2660. window.document.body.appendChild(a);
  2661. a.addEventListener("click", function () {
  2662. a.parentElement.removeChild(a);
  2663. });
  2664. a.click();
  2665. //Or opening a new tab with the image if it is not possible to automatically start download.
  2666. } else {
  2667. var newWindow = window.open("");
  2668. var img = newWindow.document.createElement("img");
  2669. img.src = base64Image;
  2670. newWindow.document.body.appendChild(img);
  2671. }
  2672. };
  2673. texture.render(true);
  2674. texture.dispose();
  2675. if (previousCamera) {
  2676. scene.activeCamera = previousCamera;
  2677. }
  2678. };
  2679. // XHR response validator for local file scenario
  2680. Tools.ValidateXHRData = function (xhr, dataType) {
  2681. if (typeof dataType === "undefined") { dataType = 7; }
  2682. try {
  2683. if (dataType & 1) {
  2684. if (xhr.responseText && xhr.responseText.length > 0) {
  2685. return true;
  2686. } else if (dataType === 1) {
  2687. return false;
  2688. }
  2689. }
  2690. if (dataType & 2) {
  2691. // Check header width and height since there is no "TGA" magic number
  2692. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2693. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2694. return true;
  2695. } else if (dataType === 2) {
  2696. return false;
  2697. }
  2698. }
  2699. if (dataType & 4) {
  2700. // Check for the "DDS" magic number
  2701. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2702. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2703. return true;
  2704. } else {
  2705. return false;
  2706. }
  2707. }
  2708. } catch (e) {
  2709. // Global protection
  2710. }
  2711. return false;
  2712. };
  2713. Object.defineProperty(Tools, "NoneLogLevel", {
  2714. get: function () {
  2715. return Tools._NoneLogLevel;
  2716. },
  2717. enumerable: true,
  2718. configurable: true
  2719. });
  2720. Object.defineProperty(Tools, "MessageLogLevel", {
  2721. get: function () {
  2722. return Tools._MessageLogLevel;
  2723. },
  2724. enumerable: true,
  2725. configurable: true
  2726. });
  2727. Object.defineProperty(Tools, "WarningLogLevel", {
  2728. get: function () {
  2729. return Tools._WarningLogLevel;
  2730. },
  2731. enumerable: true,
  2732. configurable: true
  2733. });
  2734. Object.defineProperty(Tools, "ErrorLogLevel", {
  2735. get: function () {
  2736. return Tools._ErrorLogLevel;
  2737. },
  2738. enumerable: true,
  2739. configurable: true
  2740. });
  2741. Object.defineProperty(Tools, "AllLogLevel", {
  2742. get: function () {
  2743. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2744. },
  2745. enumerable: true,
  2746. configurable: true
  2747. });
  2748. Tools._AddLogEntry = function (entry) {
  2749. Tools._LogCache = entry + Tools._LogCache;
  2750. if (Tools.OnNewCacheEntry) {
  2751. Tools.OnNewCacheEntry(entry);
  2752. }
  2753. };
  2754. Tools._FormatMessage = function (message) {
  2755. var padStr = function (i) {
  2756. return (i < 10) ? "0" + i : "" + i;
  2757. };
  2758. var date = new Date();
  2759. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2760. };
  2761. Tools._LogDisabled = function (message) {
  2762. // nothing to do
  2763. };
  2764. Tools._LogEnabled = function (message) {
  2765. var formattedMessage = Tools._FormatMessage(message);
  2766. console.log("BJS - " + formattedMessage);
  2767. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2768. Tools._AddLogEntry(entry);
  2769. };
  2770. Tools._WarnDisabled = function (message) {
  2771. // nothing to do
  2772. };
  2773. Tools._WarnEnabled = function (message) {
  2774. var formattedMessage = Tools._FormatMessage(message);
  2775. console.warn("BJS - " + formattedMessage);
  2776. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2777. Tools._AddLogEntry(entry);
  2778. };
  2779. Tools._ErrorDisabled = function (message) {
  2780. // nothing to do
  2781. };
  2782. Tools._ErrorEnabled = function (message) {
  2783. var formattedMessage = Tools._FormatMessage(message);
  2784. console.error("BJS - " + formattedMessage);
  2785. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2786. Tools._AddLogEntry(entry);
  2787. };
  2788. Object.defineProperty(Tools, "LogCache", {
  2789. get: function () {
  2790. return Tools._LogCache;
  2791. },
  2792. enumerable: true,
  2793. configurable: true
  2794. });
  2795. Object.defineProperty(Tools, "LogLevels", {
  2796. set: function (level) {
  2797. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2798. Tools.Log = Tools._LogEnabled;
  2799. } else {
  2800. Tools.Log = Tools._LogDisabled;
  2801. }
  2802. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2803. Tools.Warn = Tools._WarnEnabled;
  2804. } else {
  2805. Tools.Warn = Tools._WarnDisabled;
  2806. }
  2807. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2808. Tools.Error = Tools._ErrorEnabled;
  2809. } else {
  2810. Tools.Error = Tools._ErrorDisabled;
  2811. }
  2812. },
  2813. enumerable: true,
  2814. configurable: true
  2815. });
  2816. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2817. get: function () {
  2818. return Tools._PerformanceNoneLogLevel;
  2819. },
  2820. enumerable: true,
  2821. configurable: true
  2822. });
  2823. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2824. get: function () {
  2825. return Tools._PerformanceUserMarkLogLevel;
  2826. },
  2827. enumerable: true,
  2828. configurable: true
  2829. });
  2830. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2831. get: function () {
  2832. return Tools._PerformanceConsoleLogLevel;
  2833. },
  2834. enumerable: true,
  2835. configurable: true
  2836. });
  2837. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2838. set: function (level) {
  2839. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2840. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2841. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2842. return;
  2843. }
  2844. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2845. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2846. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2847. return;
  2848. }
  2849. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2850. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2851. },
  2852. enumerable: true,
  2853. configurable: true
  2854. });
  2855. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2856. };
  2857. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2858. };
  2859. Tools._StartUserMark = function (counterName, condition) {
  2860. if (typeof condition === "undefined") { condition = true; }
  2861. if (!condition || !Tools._performance.mark) {
  2862. return;
  2863. }
  2864. Tools._performance.mark(counterName + "-Begin");
  2865. };
  2866. Tools._EndUserMark = function (counterName, condition) {
  2867. if (typeof condition === "undefined") { condition = true; }
  2868. if (!condition || !Tools._performance.mark) {
  2869. return;
  2870. }
  2871. Tools._performance.mark(counterName + "-End");
  2872. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2873. };
  2874. Tools._StartPerformanceConsole = function (counterName, condition) {
  2875. if (typeof condition === "undefined") { condition = true; }
  2876. if (!condition) {
  2877. return;
  2878. }
  2879. Tools._StartUserMark(counterName, condition);
  2880. if (console.time) {
  2881. console.time(counterName);
  2882. }
  2883. };
  2884. Tools._EndPerformanceConsole = function (counterName, condition) {
  2885. if (typeof condition === "undefined") { condition = true; }
  2886. if (!condition) {
  2887. return;
  2888. }
  2889. Tools._EndUserMark(counterName, condition);
  2890. if (console.time) {
  2891. console.timeEnd(counterName);
  2892. }
  2893. };
  2894. Object.defineProperty(Tools, "Now", {
  2895. get: function () {
  2896. if (window.performance && window.performance.now) {
  2897. return window.performance.now();
  2898. }
  2899. return new Date().getTime();
  2900. },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. // Deprecated
  2905. Tools.GetFps = function () {
  2906. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2907. return 0;
  2908. };
  2909. Tools.BaseUrl = "";
  2910. Tools.GetExponantOfTwo = function (value, max) {
  2911. var count = 1;
  2912. do {
  2913. count *= 2;
  2914. } while(count < value);
  2915. if (count > max)
  2916. count = max;
  2917. return count;
  2918. };
  2919. Tools._NoneLogLevel = 0;
  2920. Tools._MessageLogLevel = 1;
  2921. Tools._WarningLogLevel = 2;
  2922. Tools._ErrorLogLevel = 4;
  2923. Tools._LogCache = "";
  2924. Tools.Log = Tools._LogEnabled;
  2925. Tools.Warn = Tools._WarnEnabled;
  2926. Tools.Error = Tools._ErrorEnabled;
  2927. Tools._PerformanceNoneLogLevel = 0;
  2928. Tools._PerformanceUserMarkLogLevel = 1;
  2929. Tools._PerformanceConsoleLogLevel = 2;
  2930. Tools._performance = window.performance;
  2931. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2932. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2933. return Tools;
  2934. })();
  2935. BABYLON.Tools = Tools;
  2936. /**
  2937. * An implementation of a loop for asynchronous functions.
  2938. */
  2939. var AsyncLoop = (function () {
  2940. /**
  2941. * Constroctor.
  2942. * @param iterations the number of iterations.
  2943. * @param _fn the function to run each iteration
  2944. * @param _successCallback the callback that will be called upon succesful execution
  2945. * @param offset starting offset.
  2946. */
  2947. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  2948. if (typeof offset === "undefined") { offset = 0; }
  2949. this.iterations = iterations;
  2950. this._fn = _fn;
  2951. this._successCallback = _successCallback;
  2952. this.index = offset - 1;
  2953. this._done = false;
  2954. }
  2955. /**
  2956. * Execute the next iteration. Must be called after the last iteration was finished.
  2957. */
  2958. AsyncLoop.prototype.executeNext = function () {
  2959. if (!this._done) {
  2960. if (this.index < this.iterations) {
  2961. ++this.index;
  2962. this._fn(this);
  2963. } else {
  2964. this.breakLoop();
  2965. }
  2966. }
  2967. };
  2968. /**
  2969. * Break the loop and run the success callback.
  2970. */
  2971. AsyncLoop.prototype.breakLoop = function () {
  2972. this._done = true;
  2973. this._successCallback();
  2974. };
  2975. /**
  2976. * Helper function
  2977. */
  2978. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  2979. if (typeof offset === "undefined") { offset = 0; }
  2980. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  2981. loop.executeNext();
  2982. return loop;
  2983. };
  2984. /**
  2985. * A for-loop that will run a given number of iterations synchronous and the rest async.
  2986. * @param iterations total number of iterations
  2987. * @param syncedIterations number of synchronous iterations in each async iteration.
  2988. * @param fn the function to call each iteration.
  2989. * @param callback a success call back that will be called when iterating stops.
  2990. * @param breakFunction a break condition (optional)
  2991. * @param timeout timeout settings for the setTimeout function. default - 0.
  2992. * @constructor
  2993. */
  2994. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  2995. if (typeof timeout === "undefined") { timeout = 0; }
  2996. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  2997. if (breakFunction && breakFunction())
  2998. loop.breakLoop();
  2999. else {
  3000. setTimeout(function () {
  3001. for (var i = 0; i < syncedIterations; ++i) {
  3002. var iteration = (loop.index * syncedIterations) + i;
  3003. if (iteration >= iterations)
  3004. break;
  3005. fn(iteration);
  3006. if (breakFunction && breakFunction()) {
  3007. loop.breakLoop();
  3008. break;
  3009. }
  3010. }
  3011. loop.executeNext();
  3012. }, timeout);
  3013. }
  3014. }, callback);
  3015. };
  3016. return AsyncLoop;
  3017. })();
  3018. BABYLON.AsyncLoop = AsyncLoop;
  3019. })(BABYLON || (BABYLON = {}));
  3020. //# sourceMappingURL=babylon.tools.js.map
  3021. var BABYLON;
  3022. (function (BABYLON) {
  3023. var _DepthCullingState = (function () {
  3024. function _DepthCullingState() {
  3025. this._isDepthTestDirty = false;
  3026. this._isDepthMaskDirty = false;
  3027. this._isDepthFuncDirty = false;
  3028. this._isCullFaceDirty = false;
  3029. this._isCullDirty = false;
  3030. }
  3031. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3032. get: function () {
  3033. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3034. },
  3035. enumerable: true,
  3036. configurable: true
  3037. });
  3038. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3039. get: function () {
  3040. return this._cullFace;
  3041. },
  3042. set: function (value) {
  3043. if (this._cullFace === value) {
  3044. return;
  3045. }
  3046. this._cullFace = value;
  3047. this._isCullFaceDirty = true;
  3048. },
  3049. enumerable: true,
  3050. configurable: true
  3051. });
  3052. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3053. get: function () {
  3054. return this._cull;
  3055. },
  3056. set: function (value) {
  3057. if (this._cull === value) {
  3058. return;
  3059. }
  3060. this._cull = value;
  3061. this._isCullDirty = true;
  3062. },
  3063. enumerable: true,
  3064. configurable: true
  3065. });
  3066. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3067. get: function () {
  3068. return this._depthFunc;
  3069. },
  3070. set: function (value) {
  3071. if (this._depthFunc === value) {
  3072. return;
  3073. }
  3074. this._depthFunc = value;
  3075. this._isDepthFuncDirty = true;
  3076. },
  3077. enumerable: true,
  3078. configurable: true
  3079. });
  3080. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3081. get: function () {
  3082. return this._depthMask;
  3083. },
  3084. set: function (value) {
  3085. if (this._depthMask === value) {
  3086. return;
  3087. }
  3088. this._depthMask = value;
  3089. this._isDepthMaskDirty = true;
  3090. },
  3091. enumerable: true,
  3092. configurable: true
  3093. });
  3094. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3095. get: function () {
  3096. return this._depthTest;
  3097. },
  3098. set: function (value) {
  3099. if (this._depthTest === value) {
  3100. return;
  3101. }
  3102. this._depthTest = value;
  3103. this._isDepthTestDirty = true;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. _DepthCullingState.prototype.reset = function () {
  3109. this._depthMask = true;
  3110. this._depthTest = true;
  3111. this._depthFunc = null;
  3112. this._cull = null;
  3113. this._cullFace = null;
  3114. this._isDepthTestDirty = true;
  3115. this._isDepthMaskDirty = true;
  3116. this._isDepthFuncDirty = false;
  3117. this._isCullFaceDirty = false;
  3118. this._isCullDirty = false;
  3119. };
  3120. _DepthCullingState.prototype.apply = function (gl) {
  3121. if (!this.isDirty) {
  3122. return;
  3123. }
  3124. // Cull
  3125. if (this._isCullDirty) {
  3126. if (this.cull) {
  3127. gl.enable(gl.CULL_FACE);
  3128. } else {
  3129. gl.disable(gl.CULL_FACE);
  3130. }
  3131. this._isCullDirty = false;
  3132. }
  3133. // Cull face
  3134. if (this._isCullFaceDirty) {
  3135. gl.cullFace(this.cullFace);
  3136. this._isCullFaceDirty = false;
  3137. }
  3138. // Depth mask
  3139. if (this._isDepthMaskDirty) {
  3140. gl.depthMask(this.depthMask);
  3141. this._isDepthMaskDirty = false;
  3142. }
  3143. // Depth test
  3144. if (this._isDepthTestDirty) {
  3145. if (this.depthTest) {
  3146. gl.enable(gl.DEPTH_TEST);
  3147. } else {
  3148. gl.disable(gl.DEPTH_TEST);
  3149. }
  3150. this._isDepthTestDirty = false;
  3151. }
  3152. // Depth func
  3153. if (this._isDepthFuncDirty) {
  3154. gl.depthFunc(this.depthFunc);
  3155. this._isDepthFuncDirty = false;
  3156. }
  3157. };
  3158. return _DepthCullingState;
  3159. })();
  3160. BABYLON._DepthCullingState = _DepthCullingState;
  3161. var _AlphaState = (function () {
  3162. function _AlphaState() {
  3163. this._isAlphaBlendDirty = false;
  3164. this._isBlendFunctionParametersDirty = false;
  3165. this._alphaBlend = false;
  3166. this._blendFunctionParameters = new Array(4);
  3167. }
  3168. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3169. get: function () {
  3170. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3176. get: function () {
  3177. return this._alphaBlend;
  3178. },
  3179. set: function (value) {
  3180. if (this._alphaBlend === value) {
  3181. return;
  3182. }
  3183. this._alphaBlend = value;
  3184. this._isAlphaBlendDirty = true;
  3185. },
  3186. enumerable: true,
  3187. configurable: true
  3188. });
  3189. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3190. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3191. return;
  3192. }
  3193. this._blendFunctionParameters[0] = value0;
  3194. this._blendFunctionParameters[1] = value1;
  3195. this._blendFunctionParameters[2] = value2;
  3196. this._blendFunctionParameters[3] = value3;
  3197. this._isBlendFunctionParametersDirty = true;
  3198. };
  3199. _AlphaState.prototype.reset = function () {
  3200. this._alphaBlend = false;
  3201. this._blendFunctionParameters[0] = null;
  3202. this._blendFunctionParameters[1] = null;
  3203. this._blendFunctionParameters[2] = null;
  3204. this._blendFunctionParameters[3] = null;
  3205. this._isAlphaBlendDirty = true;
  3206. this._isBlendFunctionParametersDirty = false;
  3207. };
  3208. _AlphaState.prototype.apply = function (gl) {
  3209. if (!this.isDirty) {
  3210. return;
  3211. }
  3212. // Alpha blend
  3213. if (this._isAlphaBlendDirty) {
  3214. if (this._alphaBlend) {
  3215. gl.enable(gl.BLEND);
  3216. } else {
  3217. gl.disable(gl.BLEND);
  3218. }
  3219. this._isAlphaBlendDirty = false;
  3220. }
  3221. // Alpha function
  3222. if (this._isBlendFunctionParametersDirty) {
  3223. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3224. this._isBlendFunctionParametersDirty = false;
  3225. }
  3226. };
  3227. return _AlphaState;
  3228. })();
  3229. BABYLON._AlphaState = _AlphaState;
  3230. var compileShader = function (gl, source, type, defines) {
  3231. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3232. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3233. gl.compileShader(shader);
  3234. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3235. throw new Error(gl.getShaderInfoLog(shader));
  3236. }
  3237. return shader;
  3238. };
  3239. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3240. var magFilter = gl.NEAREST;
  3241. var minFilter = gl.NEAREST;
  3242. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3243. magFilter = gl.LINEAR;
  3244. if (generateMipMaps) {
  3245. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3246. } else {
  3247. minFilter = gl.LINEAR;
  3248. }
  3249. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3250. magFilter = gl.LINEAR;
  3251. if (generateMipMaps) {
  3252. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3253. } else {
  3254. minFilter = gl.LINEAR;
  3255. }
  3256. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3257. magFilter = gl.NEAREST;
  3258. if (generateMipMaps) {
  3259. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3260. } else {
  3261. minFilter = gl.NEAREST;
  3262. }
  3263. }
  3264. return {
  3265. min: minFilter,
  3266. mag: magFilter
  3267. };
  3268. };
  3269. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3270. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3271. var engine = scene.getEngine();
  3272. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3273. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3274. gl.bindTexture(gl.TEXTURE_2D, texture);
  3275. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3276. processFunction(potWidth, potHeight);
  3277. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3280. if (!noMipmap && !isCompressed) {
  3281. gl.generateMipmap(gl.TEXTURE_2D);
  3282. }
  3283. gl.bindTexture(gl.TEXTURE_2D, null);
  3284. engine._activeTexturesCache = [];
  3285. texture._baseWidth = width;
  3286. texture._baseHeight = height;
  3287. texture._width = potWidth;
  3288. texture._height = potHeight;
  3289. texture.isReady = true;
  3290. texture.samplingMode = samplingMode;
  3291. scene._removePendingData(texture);
  3292. };
  3293. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3294. var onload = function () {
  3295. loadedImages[index] = img;
  3296. loadedImages._internalCount++;
  3297. scene._removePendingData(img);
  3298. if (loadedImages._internalCount === 6) {
  3299. onfinish(loadedImages);
  3300. }
  3301. };
  3302. var onerror = function () {
  3303. scene._removePendingData(img);
  3304. };
  3305. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3306. scene._addPendingData(img);
  3307. };
  3308. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3309. var loadedImages = [];
  3310. loadedImages._internalCount = 0;
  3311. for (var index = 0; index < 6; index++) {
  3312. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3313. }
  3314. };
  3315. var EngineCapabilities = (function () {
  3316. function EngineCapabilities() {
  3317. }
  3318. return EngineCapabilities;
  3319. })();
  3320. BABYLON.EngineCapabilities = EngineCapabilities;
  3321. var Engine = (function () {
  3322. function Engine(canvas, antialias, options) {
  3323. var _this = this;
  3324. // Public members
  3325. this.isFullscreen = false;
  3326. this.isPointerLock = false;
  3327. this.cullBackFaces = true;
  3328. this.renderEvenInBackground = true;
  3329. this.scenes = new Array();
  3330. this._windowIsBackground = false;
  3331. this._loadingDivBackgroundColor = "black";
  3332. this._drawCalls = 0;
  3333. this._renderingQueueLaunched = false;
  3334. this._activeRenderLoops = [];
  3335. // FPS
  3336. this.fpsRange = 60;
  3337. this.previousFramesDuration = [];
  3338. this.fps = 60;
  3339. this.deltaTime = 0;
  3340. // States
  3341. this._depthCullingState = new _DepthCullingState();
  3342. this._alphaState = new _AlphaState();
  3343. this._alphaMode = Engine.ALPHA_DISABLE;
  3344. // Cache
  3345. this._loadedTexturesCache = new Array();
  3346. this._activeTexturesCache = new Array();
  3347. this._compiledEffects = {};
  3348. this._uintIndicesCurrentlySet = false;
  3349. this._renderingCanvas = canvas;
  3350. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3351. options = options || {};
  3352. options.antialias = antialias;
  3353. try {
  3354. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3355. } catch (e) {
  3356. throw new Error("WebGL not supported");
  3357. }
  3358. if (!this._gl) {
  3359. throw new Error("WebGL not supported");
  3360. }
  3361. this._onBlur = function () {
  3362. _this._windowIsBackground = true;
  3363. };
  3364. this._onFocus = function () {
  3365. _this._windowIsBackground = false;
  3366. };
  3367. window.addEventListener("blur", this._onBlur);
  3368. window.addEventListener("focus", this._onFocus);
  3369. // Textures
  3370. this._workingCanvas = document.createElement("canvas");
  3371. this._workingContext = this._workingCanvas.getContext("2d");
  3372. // Viewport
  3373. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3374. this.resize();
  3375. // Caps
  3376. this._caps = new EngineCapabilities();
  3377. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3378. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3379. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3380. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3381. // Infos
  3382. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3383. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3384. if (rendererInfo != null) {
  3385. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3386. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3387. }
  3388. if (!this._glVendor) {
  3389. this._glVendor = "Unknown vendor";
  3390. }
  3391. if (!this._glRenderer) {
  3392. this._glRenderer = "Unknown renderer";
  3393. }
  3394. // Extensions
  3395. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3396. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3397. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3398. 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');
  3399. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3400. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3401. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3402. // Depth buffer
  3403. this.setDepthBuffer(true);
  3404. this.setDepthFunctionToLessOrEqual();
  3405. this.setDepthWrite(true);
  3406. // Fullscreen
  3407. this._onFullscreenChange = function () {
  3408. if (document.fullscreen !== undefined) {
  3409. _this.isFullscreen = document.fullscreen;
  3410. } else if (document.mozFullScreen !== undefined) {
  3411. _this.isFullscreen = document.mozFullScreen;
  3412. } else if (document.webkitIsFullScreen !== undefined) {
  3413. _this.isFullscreen = document.webkitIsFullScreen;
  3414. } else if (document.msIsFullScreen !== undefined) {
  3415. _this.isFullscreen = document.msIsFullScreen;
  3416. }
  3417. // Pointer lock
  3418. if (_this.isFullscreen && _this._pointerLockRequested) {
  3419. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3420. if (canvas.requestPointerLock) {
  3421. canvas.requestPointerLock();
  3422. }
  3423. }
  3424. };
  3425. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3426. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3427. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3428. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3429. // Pointer lock
  3430. this._onPointerLockChange = function () {
  3431. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3432. };
  3433. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3434. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3435. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3436. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3437. this._audioEngine = new BABYLON.AudioEngine();
  3438. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3439. }
  3440. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3441. get: function () {
  3442. return Engine._ALPHA_DISABLE;
  3443. },
  3444. enumerable: true,
  3445. configurable: true
  3446. });
  3447. Object.defineProperty(Engine, "ALPHA_ADD", {
  3448. get: function () {
  3449. return Engine._ALPHA_ADD;
  3450. },
  3451. enumerable: true,
  3452. configurable: true
  3453. });
  3454. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3455. get: function () {
  3456. return Engine._ALPHA_COMBINE;
  3457. },
  3458. enumerable: true,
  3459. configurable: true
  3460. });
  3461. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3462. get: function () {
  3463. return Engine._DELAYLOADSTATE_NONE;
  3464. },
  3465. enumerable: true,
  3466. configurable: true
  3467. });
  3468. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3469. get: function () {
  3470. return Engine._DELAYLOADSTATE_LOADED;
  3471. },
  3472. enumerable: true,
  3473. configurable: true
  3474. });
  3475. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3476. get: function () {
  3477. return Engine._DELAYLOADSTATE_LOADING;
  3478. },
  3479. enumerable: true,
  3480. configurable: true
  3481. });
  3482. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3483. get: function () {
  3484. return Engine._DELAYLOADSTATE_NOTLOADED;
  3485. },
  3486. enumerable: true,
  3487. configurable: true
  3488. });
  3489. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3490. get: function () {
  3491. return Engine._TEXTUREFORMAT_ALPHA;
  3492. },
  3493. enumerable: true,
  3494. configurable: true
  3495. });
  3496. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3497. get: function () {
  3498. return Engine._TEXTUREFORMAT_LUMINANCE;
  3499. },
  3500. enumerable: true,
  3501. configurable: true
  3502. });
  3503. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3504. get: function () {
  3505. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3506. },
  3507. enumerable: true,
  3508. configurable: true
  3509. });
  3510. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3511. get: function () {
  3512. return Engine._TEXTUREFORMAT_RGB;
  3513. },
  3514. enumerable: true,
  3515. configurable: true
  3516. });
  3517. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3518. get: function () {
  3519. return Engine._TEXTUREFORMAT_RGBA;
  3520. },
  3521. enumerable: true,
  3522. configurable: true
  3523. });
  3524. Object.defineProperty(Engine, "Version", {
  3525. get: function () {
  3526. return "2.0.0";
  3527. },
  3528. enumerable: true,
  3529. configurable: true
  3530. });
  3531. Engine.prototype.getGlInfo = function () {
  3532. return {
  3533. vendor: this._glVendor,
  3534. renderer: this._glRenderer,
  3535. version: this._glVersion
  3536. };
  3537. };
  3538. Engine.prototype.getAudioEngine = function () {
  3539. return this._audioEngine;
  3540. };
  3541. Engine.prototype.getAspectRatio = function (camera) {
  3542. var viewport = camera.viewport;
  3543. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3544. };
  3545. Engine.prototype.getRenderWidth = function () {
  3546. if (this._currentRenderTarget) {
  3547. return this._currentRenderTarget._width;
  3548. }
  3549. return this._renderingCanvas.width;
  3550. };
  3551. Engine.prototype.getRenderHeight = function () {
  3552. if (this._currentRenderTarget) {
  3553. return this._currentRenderTarget._height;
  3554. }
  3555. return this._renderingCanvas.height;
  3556. };
  3557. Engine.prototype.getRenderingCanvas = function () {
  3558. return this._renderingCanvas;
  3559. };
  3560. Engine.prototype.getRenderingCanvasClientRect = function () {
  3561. return this._renderingCanvas.getBoundingClientRect();
  3562. };
  3563. Engine.prototype.setHardwareScalingLevel = function (level) {
  3564. this._hardwareScalingLevel = level;
  3565. this.resize();
  3566. };
  3567. Engine.prototype.getHardwareScalingLevel = function () {
  3568. return this._hardwareScalingLevel;
  3569. };
  3570. Engine.prototype.getLoadedTexturesCache = function () {
  3571. return this._loadedTexturesCache;
  3572. };
  3573. Engine.prototype.getCaps = function () {
  3574. return this._caps;
  3575. };
  3576. Object.defineProperty(Engine.prototype, "drawCalls", {
  3577. get: function () {
  3578. return this._drawCalls;
  3579. },
  3580. enumerable: true,
  3581. configurable: true
  3582. });
  3583. // Methods
  3584. Engine.prototype.resetDrawCalls = function () {
  3585. this._drawCalls = 0;
  3586. };
  3587. Engine.prototype.setDepthFunctionToGreater = function () {
  3588. this._depthCullingState.depthFunc = this._gl.GREATER;
  3589. };
  3590. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3591. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3592. };
  3593. Engine.prototype.setDepthFunctionToLess = function () {
  3594. this._depthCullingState.depthFunc = this._gl.LESS;
  3595. };
  3596. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3597. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3598. };
  3599. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3600. if (!renderFunction) {
  3601. this._activeRenderLoops = [];
  3602. return;
  3603. }
  3604. var index = this._activeRenderLoops.indexOf(renderFunction);
  3605. if (index >= 0) {
  3606. this._activeRenderLoops.splice(index, 1);
  3607. }
  3608. };
  3609. Engine.prototype._renderLoop = function () {
  3610. var _this = this;
  3611. var shouldRender = true;
  3612. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3613. shouldRender = false;
  3614. }
  3615. if (shouldRender) {
  3616. // Start new frame
  3617. this.beginFrame();
  3618. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3619. var renderFunction = this._activeRenderLoops[index];
  3620. renderFunction();
  3621. }
  3622. // Present
  3623. this.endFrame();
  3624. }
  3625. if (this._activeRenderLoops.length > 0) {
  3626. // Register new frame
  3627. BABYLON.Tools.QueueNewFrame(function () {
  3628. _this._renderLoop();
  3629. });
  3630. } else {
  3631. this._renderingQueueLaunched = false;
  3632. }
  3633. };
  3634. Engine.prototype.runRenderLoop = function (renderFunction) {
  3635. var _this = this;
  3636. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3637. return;
  3638. }
  3639. this._activeRenderLoops.push(renderFunction);
  3640. if (!this._renderingQueueLaunched) {
  3641. this._renderingQueueLaunched = true;
  3642. BABYLON.Tools.QueueNewFrame(function () {
  3643. _this._renderLoop();
  3644. });
  3645. }
  3646. };
  3647. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3648. if (this.isFullscreen) {
  3649. BABYLON.Tools.ExitFullscreen();
  3650. } else {
  3651. this._pointerLockRequested = requestPointerLock;
  3652. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3653. }
  3654. };
  3655. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3656. this.applyStates();
  3657. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3658. if (this._depthCullingState.depthMask) {
  3659. this._gl.clearDepth(1.0);
  3660. }
  3661. var mode = 0;
  3662. if (backBuffer)
  3663. mode |= this._gl.COLOR_BUFFER_BIT;
  3664. if (depthStencil && this._depthCullingState.depthMask)
  3665. mode |= this._gl.DEPTH_BUFFER_BIT;
  3666. this._gl.clear(mode);
  3667. };
  3668. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3669. var width = requiredWidth || this._renderingCanvas.width;
  3670. var height = requiredHeight || this._renderingCanvas.height;
  3671. var x = viewport.x || 0;
  3672. var y = viewport.y || 0;
  3673. this._cachedViewport = viewport;
  3674. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3675. };
  3676. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3677. this._cachedViewport = null;
  3678. this._gl.viewport(x, y, width, height);
  3679. };
  3680. Engine.prototype.beginFrame = function () {
  3681. this._measureFps();
  3682. };
  3683. Engine.prototype.endFrame = function () {
  3684. this.flushFramebuffer();
  3685. };
  3686. Engine.prototype.resize = function () {
  3687. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3688. };
  3689. Engine.prototype.setSize = function (width, height) {
  3690. this._renderingCanvas.width = width;
  3691. this._renderingCanvas.height = height;
  3692. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3693. };
  3694. Engine.prototype.bindFramebuffer = function (texture) {
  3695. this._currentRenderTarget = texture;
  3696. var gl = this._gl;
  3697. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3698. this._gl.viewport(0, 0, texture._width, texture._height);
  3699. this.wipeCaches();
  3700. };
  3701. Engine.prototype.unBindFramebuffer = function (texture) {
  3702. this._currentRenderTarget = null;
  3703. if (texture.generateMipMaps) {
  3704. var gl = this._gl;
  3705. gl.bindTexture(gl.TEXTURE_2D, texture);
  3706. gl.generateMipmap(gl.TEXTURE_2D);
  3707. gl.bindTexture(gl.TEXTURE_2D, null);
  3708. }
  3709. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3710. };
  3711. Engine.prototype.flushFramebuffer = function () {
  3712. // this._gl.flush();
  3713. };
  3714. Engine.prototype.restoreDefaultFramebuffer = function () {
  3715. this._currentRenderTarget = null;
  3716. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3717. this.setViewport(this._cachedViewport);
  3718. this.wipeCaches();
  3719. };
  3720. // VBOs
  3721. Engine.prototype._resetVertexBufferBinding = function () {
  3722. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3723. this._cachedVertexBuffers = null;
  3724. };
  3725. Engine.prototype.createVertexBuffer = function (vertices) {
  3726. var vbo = this._gl.createBuffer();
  3727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3728. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3729. this._resetVertexBufferBinding();
  3730. vbo.references = 1;
  3731. return vbo;
  3732. };
  3733. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3734. var vbo = this._gl.createBuffer();
  3735. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3736. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3737. this._resetVertexBufferBinding();
  3738. vbo.references = 1;
  3739. return vbo;
  3740. };
  3741. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3742. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3743. if (offset === undefined) {
  3744. offset = 0;
  3745. }
  3746. if (vertices instanceof Float32Array) {
  3747. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3748. } else {
  3749. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3750. }
  3751. this._resetVertexBufferBinding();
  3752. };
  3753. Engine.prototype._resetIndexBufferBinding = function () {
  3754. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3755. this._cachedIndexBuffer = null;
  3756. };
  3757. Engine.prototype.createIndexBuffer = function (indices) {
  3758. var vbo = this._gl.createBuffer();
  3759. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3760. // Check for 32 bits indices
  3761. var arrayBuffer;
  3762. var need32Bits = false;
  3763. if (this._caps.uintIndices) {
  3764. for (var index = 0; index < indices.length; index++) {
  3765. if (indices[index] > 65535) {
  3766. need32Bits = true;
  3767. break;
  3768. }
  3769. }
  3770. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3771. } else {
  3772. arrayBuffer = new Uint16Array(indices);
  3773. }
  3774. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3775. this._resetIndexBufferBinding();
  3776. vbo.references = 1;
  3777. vbo.is32Bits = need32Bits;
  3778. return vbo;
  3779. };
  3780. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3781. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3782. this._cachedVertexBuffers = vertexBuffer;
  3783. this._cachedEffectForVertexBuffers = effect;
  3784. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3785. var offset = 0;
  3786. for (var index = 0; index < vertexDeclaration.length; index++) {
  3787. var order = effect.getAttributeLocation(index);
  3788. if (order >= 0) {
  3789. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3790. }
  3791. offset += vertexDeclaration[index] * 4;
  3792. }
  3793. }
  3794. if (this._cachedIndexBuffer !== indexBuffer) {
  3795. this._cachedIndexBuffer = indexBuffer;
  3796. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3797. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3798. }
  3799. };
  3800. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3801. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3802. this._cachedVertexBuffers = vertexBuffers;
  3803. this._cachedEffectForVertexBuffers = effect;
  3804. var attributes = effect.getAttributesNames();
  3805. for (var index = 0; index < attributes.length; index++) {
  3806. var order = effect.getAttributeLocation(index);
  3807. if (order >= 0) {
  3808. var vertexBuffer = vertexBuffers[attributes[index]];
  3809. if (!vertexBuffer) {
  3810. continue;
  3811. }
  3812. var stride = vertexBuffer.getStrideSize();
  3813. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3814. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3815. }
  3816. }
  3817. }
  3818. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3819. this._cachedIndexBuffer = indexBuffer;
  3820. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3821. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3822. }
  3823. };
  3824. Engine.prototype._releaseBuffer = function (buffer) {
  3825. buffer.references--;
  3826. if (buffer.references === 0) {
  3827. this._gl.deleteBuffer(buffer);
  3828. return true;
  3829. }
  3830. return false;
  3831. };
  3832. Engine.prototype.createInstancesBuffer = function (capacity) {
  3833. var buffer = this._gl.createBuffer();
  3834. buffer.capacity = capacity;
  3835. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3836. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3837. return buffer;
  3838. };
  3839. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3840. this._gl.deleteBuffer(buffer);
  3841. };
  3842. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3845. for (var index = 0; index < 4; index++) {
  3846. var offsetLocation = offsetLocations[index];
  3847. this._gl.enableVertexAttribArray(offsetLocation);
  3848. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3849. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3850. }
  3851. };
  3852. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3853. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3854. for (var index = 0; index < 4; index++) {
  3855. var offsetLocation = offsetLocations[index];
  3856. this._gl.disableVertexAttribArray(offsetLocation);
  3857. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3858. }
  3859. };
  3860. Engine.prototype.applyStates = function () {
  3861. this._depthCullingState.apply(this._gl);
  3862. this._alphaState.apply(this._gl);
  3863. };
  3864. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3865. // Apply states
  3866. this.applyStates();
  3867. this._drawCalls++;
  3868. // Render
  3869. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3870. if (instancesCount) {
  3871. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3872. return;
  3873. }
  3874. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3875. };
  3876. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3877. // Apply states
  3878. this.applyStates();
  3879. this._drawCalls++;
  3880. if (instancesCount) {
  3881. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3882. return;
  3883. }
  3884. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3885. };
  3886. // Shaders
  3887. Engine.prototype._releaseEffect = function (effect) {
  3888. if (this._compiledEffects[effect._key]) {
  3889. delete this._compiledEffects[effect._key];
  3890. if (effect.getProgram()) {
  3891. this._gl.deleteProgram(effect.getProgram());
  3892. }
  3893. }
  3894. };
  3895. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3896. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3897. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3898. var name = vertex + "+" + fragment + "@" + defines;
  3899. if (this._compiledEffects[name]) {
  3900. return this._compiledEffects[name];
  3901. }
  3902. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3903. effect._key = name;
  3904. this._compiledEffects[name] = effect;
  3905. return effect;
  3906. };
  3907. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3908. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3909. if (typeof samplers === "undefined") { samplers = []; }
  3910. if (typeof defines === "undefined") { defines = ""; }
  3911. return this.createEffect({
  3912. vertex: "particles",
  3913. fragmentElement: fragmentName
  3914. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3915. };
  3916. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3917. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3918. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3919. var shaderProgram = this._gl.createProgram();
  3920. this._gl.attachShader(shaderProgram, vertexShader);
  3921. this._gl.attachShader(shaderProgram, fragmentShader);
  3922. this._gl.linkProgram(shaderProgram);
  3923. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3924. if (!linked) {
  3925. var error = this._gl.getProgramInfoLog(shaderProgram);
  3926. if (error) {
  3927. throw new Error(error);
  3928. }
  3929. }
  3930. this._gl.deleteShader(vertexShader);
  3931. this._gl.deleteShader(fragmentShader);
  3932. return shaderProgram;
  3933. };
  3934. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3935. var results = [];
  3936. for (var index = 0; index < uniformsNames.length; index++) {
  3937. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3938. }
  3939. return results;
  3940. };
  3941. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3942. var results = [];
  3943. for (var index = 0; index < attributesNames.length; index++) {
  3944. try {
  3945. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3946. } catch (e) {
  3947. results.push(-1);
  3948. }
  3949. }
  3950. return results;
  3951. };
  3952. Engine.prototype.enableEffect = function (effect) {
  3953. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3954. if (effect && effect.onBind) {
  3955. effect.onBind(effect);
  3956. }
  3957. return;
  3958. }
  3959. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3960. // Use program
  3961. this._gl.useProgram(effect.getProgram());
  3962. for (var i in this._vertexAttribArrays) {
  3963. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3964. continue;
  3965. }
  3966. this._vertexAttribArrays[i] = false;
  3967. this._gl.disableVertexAttribArray(i);
  3968. }
  3969. var attributesCount = effect.getAttributesCount();
  3970. for (var index = 0; index < attributesCount; index++) {
  3971. // Attributes
  3972. var order = effect.getAttributeLocation(index);
  3973. if (order >= 0) {
  3974. this._vertexAttribArrays[order] = true;
  3975. this._gl.enableVertexAttribArray(order);
  3976. }
  3977. }
  3978. this._currentEffect = effect;
  3979. if (effect.onBind) {
  3980. effect.onBind(effect);
  3981. }
  3982. };
  3983. Engine.prototype.setArray = function (uniform, array) {
  3984. if (!uniform)
  3985. return;
  3986. this._gl.uniform1fv(uniform, array);
  3987. };
  3988. Engine.prototype.setMatrices = function (uniform, matrices) {
  3989. if (!uniform)
  3990. return;
  3991. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3992. };
  3993. Engine.prototype.setMatrix = function (uniform, matrix) {
  3994. if (!uniform)
  3995. return;
  3996. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3997. };
  3998. Engine.prototype.setFloat = function (uniform, value) {
  3999. if (!uniform)
  4000. return;
  4001. this._gl.uniform1f(uniform, value);
  4002. };
  4003. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4004. if (!uniform)
  4005. return;
  4006. this._gl.uniform2f(uniform, x, y);
  4007. };
  4008. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4009. if (!uniform)
  4010. return;
  4011. this._gl.uniform3f(uniform, x, y, z);
  4012. };
  4013. Engine.prototype.setBool = function (uniform, bool) {
  4014. if (!uniform)
  4015. return;
  4016. this._gl.uniform1i(uniform, bool);
  4017. };
  4018. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4019. if (!uniform)
  4020. return;
  4021. this._gl.uniform4f(uniform, x, y, z, w);
  4022. };
  4023. Engine.prototype.setColor3 = function (uniform, color3) {
  4024. if (!uniform)
  4025. return;
  4026. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4027. };
  4028. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4029. if (!uniform)
  4030. return;
  4031. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4032. };
  4033. // States
  4034. Engine.prototype.setState = function (culling, force) {
  4035. // Culling
  4036. if (this._depthCullingState.cull !== culling || force) {
  4037. if (culling) {
  4038. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4039. this._depthCullingState.cull = true;
  4040. } else {
  4041. this._depthCullingState.cull = false;
  4042. }
  4043. }
  4044. };
  4045. Engine.prototype.setDepthBuffer = function (enable) {
  4046. this._depthCullingState.depthTest = enable;
  4047. };
  4048. Engine.prototype.getDepthWrite = function () {
  4049. return this._depthCullingState.depthMask;
  4050. };
  4051. Engine.prototype.setDepthWrite = function (enable) {
  4052. this._depthCullingState.depthMask = enable;
  4053. };
  4054. Engine.prototype.setColorWrite = function (enable) {
  4055. this._gl.colorMask(enable, enable, enable, enable);
  4056. };
  4057. Engine.prototype.setAlphaMode = function (mode) {
  4058. switch (mode) {
  4059. case Engine.ALPHA_DISABLE:
  4060. this.setDepthWrite(true);
  4061. this._alphaState.alphaBlend = false;
  4062. break;
  4063. case Engine.ALPHA_COMBINE:
  4064. this.setDepthWrite(false);
  4065. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4066. this._alphaState.alphaBlend = true;
  4067. break;
  4068. case Engine.ALPHA_ADD:
  4069. this.setDepthWrite(false);
  4070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4071. this._alphaState.alphaBlend = true;
  4072. break;
  4073. }
  4074. this._alphaMode = mode;
  4075. };
  4076. Engine.prototype.getAlphaMode = function () {
  4077. return this._alphaMode;
  4078. };
  4079. Engine.prototype.setAlphaTesting = function (enable) {
  4080. this._alphaTest = enable;
  4081. };
  4082. Engine.prototype.getAlphaTesting = function () {
  4083. return this._alphaTest;
  4084. };
  4085. // Textures
  4086. Engine.prototype.wipeCaches = function () {
  4087. this._activeTexturesCache = [];
  4088. this._currentEffect = null;
  4089. this._depthCullingState.reset();
  4090. this._alphaState.reset();
  4091. this._cachedVertexBuffers = null;
  4092. this._cachedIndexBuffer = null;
  4093. this._cachedEffectForVertexBuffers = null;
  4094. };
  4095. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4096. var gl = this._gl;
  4097. gl.bindTexture(gl.TEXTURE_2D, texture);
  4098. var magFilter = gl.NEAREST;
  4099. var minFilter = gl.NEAREST;
  4100. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4101. magFilter = gl.LINEAR;
  4102. minFilter = gl.LINEAR;
  4103. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4104. magFilter = gl.LINEAR;
  4105. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4106. }
  4107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4109. gl.bindTexture(gl.TEXTURE_2D, null);
  4110. texture.samplingMode = samplingMode;
  4111. };
  4112. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4113. var _this = this;
  4114. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4115. if (typeof onLoad === "undefined") { onLoad = null; }
  4116. if (typeof onError === "undefined") { onError = null; }
  4117. if (typeof buffer === "undefined") { buffer = null; }
  4118. var texture = this._gl.createTexture();
  4119. var extension;
  4120. var fromData = false;
  4121. if (url.substr(0, 5) === "data:") {
  4122. fromData = true;
  4123. }
  4124. if (!fromData)
  4125. extension = url.substr(url.length - 4, 4).toLowerCase();
  4126. else {
  4127. var oldUrl = url;
  4128. fromData = oldUrl.split(':');
  4129. url = oldUrl;
  4130. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4131. }
  4132. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4133. var isTGA = (extension === ".tga");
  4134. scene._addPendingData(texture);
  4135. texture.url = url;
  4136. texture.noMipmap = noMipmap;
  4137. texture.references = 1;
  4138. this._loadedTexturesCache.push(texture);
  4139. var onerror = function () {
  4140. scene._removePendingData(texture);
  4141. if (onError) {
  4142. onError();
  4143. }
  4144. };
  4145. if (isTGA) {
  4146. var callback = function (arrayBuffer) {
  4147. var data = new Uint8Array(arrayBuffer);
  4148. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4149. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4150. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4151. if (onLoad) {
  4152. onLoad();
  4153. }
  4154. }, samplingMode);
  4155. };
  4156. if (!(fromData instanceof Array))
  4157. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4158. callback(arrayBuffer);
  4159. }, onerror, scene.database, true);
  4160. else
  4161. callback(buffer);
  4162. } else if (isDDS) {
  4163. callback = function (data) {
  4164. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4165. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4166. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4167. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4168. if (onLoad) {
  4169. onLoad();
  4170. }
  4171. }, samplingMode);
  4172. };
  4173. if (!(fromData instanceof Array))
  4174. BABYLON.Tools.LoadFile(url, function (data) {
  4175. callback(data);
  4176. }, onerror, scene.database, true);
  4177. else
  4178. callback(buffer);
  4179. } else {
  4180. var onload = function (img) {
  4181. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4182. var isPot = (img.width === potWidth && img.height === potHeight);
  4183. if (!isPot) {
  4184. _this._workingCanvas.width = potWidth;
  4185. _this._workingCanvas.height = potHeight;
  4186. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4187. _this._workingContext.imageSmoothingEnabled = false;
  4188. _this._workingContext.mozImageSmoothingEnabled = false;
  4189. _this._workingContext.oImageSmoothingEnabled = false;
  4190. _this._workingContext.webkitImageSmoothingEnabled = false;
  4191. _this._workingContext.msImageSmoothingEnabled = false;
  4192. }
  4193. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4194. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4195. _this._workingContext.imageSmoothingEnabled = true;
  4196. _this._workingContext.mozImageSmoothingEnabled = true;
  4197. _this._workingContext.oImageSmoothingEnabled = true;
  4198. _this._workingContext.webkitImageSmoothingEnabled = true;
  4199. _this._workingContext.msImageSmoothingEnabled = true;
  4200. }
  4201. }
  4202. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4203. if (onLoad) {
  4204. onLoad();
  4205. }
  4206. }, samplingMode);
  4207. };
  4208. if (!(fromData instanceof Array))
  4209. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4210. else
  4211. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4212. }
  4213. return texture;
  4214. };
  4215. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4216. var texture = this._gl.createTexture();
  4217. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4219. // Format
  4220. var internalFormat = this._gl.RGBA;
  4221. switch (format) {
  4222. case Engine.TEXTUREFORMAT_ALPHA:
  4223. internalFormat = this._gl.ALPHA;
  4224. break;
  4225. case Engine.TEXTUREFORMAT_LUMINANCE:
  4226. internalFormat = this._gl.LUMINANCE;
  4227. break;
  4228. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4229. internalFormat = this._gl.LUMINANCE_ALPHA;
  4230. break;
  4231. case Engine.TEXTUREFORMAT_RGB:
  4232. internalFormat = this._gl.RGB;
  4233. break;
  4234. case Engine.TEXTUREFORMAT_RGBA:
  4235. internalFormat = this._gl.RGBA;
  4236. break;
  4237. }
  4238. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4239. if (generateMipMaps) {
  4240. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4241. }
  4242. // Filters
  4243. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4244. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4245. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4246. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4247. this._activeTexturesCache = [];
  4248. texture._baseWidth = width;
  4249. texture._baseHeight = height;
  4250. texture._width = width;
  4251. texture._height = height;
  4252. texture.isReady = true;
  4253. texture.references = 1;
  4254. texture.samplingMode = samplingMode;
  4255. this._loadedTexturesCache.push(texture);
  4256. return texture;
  4257. };
  4258. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4259. var texture = this._gl.createTexture();
  4260. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4261. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4262. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4263. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4264. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4265. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4267. this._activeTexturesCache = [];
  4268. texture._baseWidth = width;
  4269. texture._baseHeight = height;
  4270. texture._width = width;
  4271. texture._height = height;
  4272. texture.isReady = false;
  4273. texture.generateMipMaps = generateMipMaps;
  4274. texture.references = 1;
  4275. texture.samplingMode = samplingMode;
  4276. this._loadedTexturesCache.push(texture);
  4277. return texture;
  4278. };
  4279. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4280. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4281. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4283. if (texture.generateMipMaps) {
  4284. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4285. }
  4286. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4287. this._activeTexturesCache = [];
  4288. texture.isReady = true;
  4289. };
  4290. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4291. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4292. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4293. // Scale the video if it is a NPOT using the current working canvas
  4294. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4295. if (!texture._workingCanvas) {
  4296. texture._workingCanvas = document.createElement("canvas");
  4297. texture._workingContext = texture._workingCanvas.getContext("2d");
  4298. texture._workingCanvas.width = texture._width;
  4299. texture._workingCanvas.height = texture._height;
  4300. }
  4301. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4302. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4303. } else {
  4304. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4305. }
  4306. if (texture.generateMipMaps) {
  4307. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4308. }
  4309. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4310. this._activeTexturesCache = [];
  4311. texture.isReady = true;
  4312. };
  4313. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4314. // old version had a "generateMipMaps" arg instead of options.
  4315. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4316. // in the same way, generateDepthBuffer is defaulted to true
  4317. var generateMipMaps = false;
  4318. var generateDepthBuffer = true;
  4319. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4320. if (options !== undefined) {
  4321. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4322. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4323. if (options.samplingMode !== undefined) {
  4324. samplingMode = options.samplingMode;
  4325. }
  4326. }
  4327. var gl = this._gl;
  4328. var texture = gl.createTexture();
  4329. gl.bindTexture(gl.TEXTURE_2D, texture);
  4330. var width = size.width || size;
  4331. var height = size.height || size;
  4332. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4337. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4338. var depthBuffer;
  4339. // Create the depth buffer
  4340. if (generateDepthBuffer) {
  4341. depthBuffer = gl.createRenderbuffer();
  4342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4343. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4344. }
  4345. // Create the framebuffer
  4346. var framebuffer = gl.createFramebuffer();
  4347. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4348. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4349. if (generateDepthBuffer) {
  4350. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4351. }
  4352. // Unbind
  4353. gl.bindTexture(gl.TEXTURE_2D, null);
  4354. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4355. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4356. texture._framebuffer = framebuffer;
  4357. if (generateDepthBuffer) {
  4358. texture._depthBuffer = depthBuffer;
  4359. }
  4360. texture._width = width;
  4361. texture._height = height;
  4362. texture.isReady = true;
  4363. texture.generateMipMaps = generateMipMaps;
  4364. texture.references = 1;
  4365. texture.samplingMode = samplingMode;
  4366. this._activeTexturesCache = [];
  4367. this._loadedTexturesCache.push(texture);
  4368. return texture;
  4369. };
  4370. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4371. var _this = this;
  4372. var gl = this._gl;
  4373. var texture = gl.createTexture();
  4374. texture.isCube = true;
  4375. texture.url = rootUrl;
  4376. texture.references = 1;
  4377. this._loadedTexturesCache.push(texture);
  4378. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4379. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4380. if (isDDS) {
  4381. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4382. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4383. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4384. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4385. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4386. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4387. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4388. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4389. }
  4390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4394. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4395. _this._activeTexturesCache = [];
  4396. texture._width = info.width;
  4397. texture._height = info.height;
  4398. texture.isReady = true;
  4399. }, null, null, true);
  4400. } else {
  4401. cascadeLoad(rootUrl, scene, function (imgs) {
  4402. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4403. var height = width;
  4404. _this._workingCanvas.width = width;
  4405. _this._workingCanvas.height = height;
  4406. var faces = [
  4407. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4408. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4409. ];
  4410. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4411. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4412. for (var index = 0; index < faces.length; index++) {
  4413. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4414. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4415. }
  4416. if (!noMipmap) {
  4417. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4418. }
  4419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4423. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4424. _this._activeTexturesCache = [];
  4425. texture._width = width;
  4426. texture._height = height;
  4427. texture.isReady = true;
  4428. }, extensions);
  4429. }
  4430. return texture;
  4431. };
  4432. Engine.prototype._releaseTexture = function (texture) {
  4433. var gl = this._gl;
  4434. if (texture._framebuffer) {
  4435. gl.deleteFramebuffer(texture._framebuffer);
  4436. }
  4437. if (texture._depthBuffer) {
  4438. gl.deleteRenderbuffer(texture._depthBuffer);
  4439. }
  4440. gl.deleteTexture(texture);
  4441. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4442. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4443. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4444. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4445. this._activeTexturesCache[channel] = null;
  4446. }
  4447. var index = this._loadedTexturesCache.indexOf(texture);
  4448. if (index !== -1) {
  4449. this._loadedTexturesCache.splice(index, 1);
  4450. }
  4451. };
  4452. Engine.prototype.bindSamplers = function (effect) {
  4453. this._gl.useProgram(effect.getProgram());
  4454. var samplers = effect.getSamplers();
  4455. for (var index = 0; index < samplers.length; index++) {
  4456. var uniform = effect.getUniform(samplers[index]);
  4457. this._gl.uniform1i(uniform, index);
  4458. }
  4459. this._currentEffect = null;
  4460. };
  4461. Engine.prototype._bindTexture = function (channel, texture) {
  4462. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4463. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4464. this._activeTexturesCache[channel] = null;
  4465. };
  4466. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4467. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4468. };
  4469. Engine.prototype.setTexture = function (channel, texture) {
  4470. if (channel < 0) {
  4471. return;
  4472. }
  4473. // Not ready?
  4474. if (!texture || !texture.isReady()) {
  4475. if (this._activeTexturesCache[channel] != null) {
  4476. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4477. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4478. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4479. this._activeTexturesCache[channel] = null;
  4480. }
  4481. return;
  4482. }
  4483. // Video
  4484. if (texture instanceof BABYLON.VideoTexture) {
  4485. if (texture.update()) {
  4486. this._activeTexturesCache[channel] = null;
  4487. }
  4488. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4489. texture.delayLoad();
  4490. return;
  4491. }
  4492. if (this._activeTexturesCache[channel] === texture) {
  4493. return;
  4494. }
  4495. this._activeTexturesCache[channel] = texture;
  4496. var internalTexture = texture.getInternalTexture();
  4497. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4498. if (internalTexture.isCube) {
  4499. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4500. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4501. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4502. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4503. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4504. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4505. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4506. }
  4507. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4508. } else {
  4509. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4510. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4511. internalTexture._cachedWrapU = texture.wrapU;
  4512. switch (texture.wrapU) {
  4513. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4515. break;
  4516. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4517. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4518. break;
  4519. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4520. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4521. break;
  4522. }
  4523. }
  4524. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4525. internalTexture._cachedWrapV = texture.wrapV;
  4526. switch (texture.wrapV) {
  4527. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4529. break;
  4530. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4531. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4532. break;
  4533. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4534. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4535. break;
  4536. }
  4537. }
  4538. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4539. }
  4540. };
  4541. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4542. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4543. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4544. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4545. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4546. }
  4547. };
  4548. Engine.prototype.readPixels = function (x, y, width, height) {
  4549. var data = new Uint8Array(height * width * 4);
  4550. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4551. return data;
  4552. };
  4553. // Dispose
  4554. Engine.prototype.dispose = function () {
  4555. this.hideLoadingUI();
  4556. this.stopRenderLoop();
  4557. while (this.scenes.length) {
  4558. this.scenes[0].dispose();
  4559. }
  4560. for (var name in this._compiledEffects) {
  4561. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4562. }
  4563. for (var i in this._vertexAttribArrays) {
  4564. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4565. continue;
  4566. }
  4567. this._gl.disableVertexAttribArray(i);
  4568. }
  4569. // Events
  4570. window.removeEventListener("blur", this._onBlur);
  4571. window.removeEventListener("focus", this._onFocus);
  4572. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4573. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4574. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4575. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4576. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4577. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4578. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4579. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4580. };
  4581. // Loading screen
  4582. Engine.prototype.displayLoadingUI = function () {
  4583. var _this = this;
  4584. this._loadingDiv = document.createElement("div");
  4585. this._loadingDiv.style.opacity = "0";
  4586. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4587. // Loading text
  4588. this._loadingTextDiv = document.createElement("div");
  4589. this._loadingTextDiv.style.position = "absolute";
  4590. this._loadingTextDiv.style.left = "0";
  4591. this._loadingTextDiv.style.top = "50%";
  4592. this._loadingTextDiv.style.marginTop = "80px";
  4593. this._loadingTextDiv.style.width = "100%";
  4594. this._loadingTextDiv.style.height = "20px";
  4595. this._loadingTextDiv.style.fontFamily = "Arial";
  4596. this._loadingTextDiv.style.fontSize = "14px";
  4597. this._loadingTextDiv.style.color = "white";
  4598. this._loadingTextDiv.style.textAlign = "center";
  4599. this._loadingTextDiv.innerHTML = "Loading";
  4600. this._loadingDiv.appendChild(this._loadingTextDiv);
  4601. // Loading img
  4602. var imgBack = new Image();
  4603. 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==";
  4604. imgBack.style.position = "absolute";
  4605. imgBack.style.left = "50%";
  4606. imgBack.style.top = "50%";
  4607. imgBack.style.marginLeft = "-50px";
  4608. imgBack.style.marginTop = "-50px";
  4609. imgBack.style.transition = "transform 1.0s ease";
  4610. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4611. var deg = 360;
  4612. var onTransitionEnd = function () {
  4613. deg += 360;
  4614. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4615. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4616. };
  4617. imgBack.addEventListener("transitionend", onTransitionEnd);
  4618. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4619. this._loadingDiv.appendChild(imgBack);
  4620. // front image
  4621. var imgFront = new Image();
  4622. 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=";
  4623. imgFront.style.position = "absolute";
  4624. imgFront.style.left = "50%";
  4625. imgFront.style.top = "50%";
  4626. imgFront.style.marginLeft = "-50px";
  4627. imgFront.style.marginTop = "-50px";
  4628. this._loadingDiv.appendChild(imgFront);
  4629. // Resize
  4630. this._resizeLoadingUI = function () {
  4631. var canvasRect = _this.getRenderingCanvasClientRect();
  4632. _this._loadingDiv.style.position = "absolute";
  4633. _this._loadingDiv.style.left = canvasRect.left + "px";
  4634. _this._loadingDiv.style.top = canvasRect.top + "px";
  4635. _this._loadingDiv.style.width = canvasRect.width + "px";
  4636. _this._loadingDiv.style.height = canvasRect.height + "px";
  4637. };
  4638. this._resizeLoadingUI();
  4639. window.addEventListener("resize", this._resizeLoadingUI);
  4640. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4641. document.body.appendChild(this._loadingDiv);
  4642. setTimeout(function () {
  4643. _this._loadingDiv.style.opacity = "1";
  4644. imgBack.style.transform = "rotateZ(360deg)";
  4645. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4646. }, 0);
  4647. };
  4648. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4649. set: function (text) {
  4650. if (!this._loadingDiv) {
  4651. return;
  4652. }
  4653. this._loadingTextDiv.innerHTML = text;
  4654. },
  4655. enumerable: true,
  4656. configurable: true
  4657. });
  4658. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4659. get: function () {
  4660. return this._loadingDivBackgroundColor;
  4661. },
  4662. set: function (color) {
  4663. this._loadingDivBackgroundColor = color;
  4664. if (!this._loadingDiv) {
  4665. return;
  4666. }
  4667. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4668. },
  4669. enumerable: true,
  4670. configurable: true
  4671. });
  4672. Engine.prototype.hideLoadingUI = function () {
  4673. var _this = this;
  4674. if (!this._loadingDiv) {
  4675. return;
  4676. }
  4677. var onTransitionEnd = function () {
  4678. if (!_this._loadingDiv) {
  4679. return;
  4680. }
  4681. document.body.removeChild(_this._loadingDiv);
  4682. window.removeEventListener("resize", _this._resizeLoadingUI);
  4683. _this._loadingDiv = null;
  4684. };
  4685. this._loadingDiv.style.opacity = "0";
  4686. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4687. };
  4688. // FPS
  4689. Engine.prototype.getFps = function () {
  4690. return this.fps;
  4691. };
  4692. Engine.prototype.getDeltaTime = function () {
  4693. return this.deltaTime;
  4694. };
  4695. Engine.prototype._measureFps = function () {
  4696. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4697. var length = this.previousFramesDuration.length;
  4698. if (length >= 2) {
  4699. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4700. }
  4701. if (length >= this.fpsRange) {
  4702. if (length > this.fpsRange) {
  4703. this.previousFramesDuration.splice(0, 1);
  4704. length = this.previousFramesDuration.length;
  4705. }
  4706. var sum = 0;
  4707. for (var id = 0; id < length - 1; id++) {
  4708. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4709. }
  4710. this.fps = 1000.0 / (sum / (length - 1));
  4711. }
  4712. };
  4713. // Statics
  4714. Engine.isSupported = function () {
  4715. try {
  4716. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4717. if (navigator.isCocoonJS) {
  4718. return true;
  4719. }
  4720. var tempcanvas = document.createElement("canvas");
  4721. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4722. return gl != null && !!window.WebGLRenderingContext;
  4723. } catch (e) {
  4724. return false;
  4725. }
  4726. };
  4727. Engine._ALPHA_DISABLE = 0;
  4728. Engine._ALPHA_ADD = 1;
  4729. Engine._ALPHA_COMBINE = 2;
  4730. Engine._DELAYLOADSTATE_NONE = 0;
  4731. Engine._DELAYLOADSTATE_LOADED = 1;
  4732. Engine._DELAYLOADSTATE_LOADING = 2;
  4733. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4734. Engine._TEXTUREFORMAT_ALPHA = 0;
  4735. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4736. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4737. Engine._TEXTUREFORMAT_RGB = 4;
  4738. Engine._TEXTUREFORMAT_RGBA = 4;
  4739. Engine.Epsilon = 0.001;
  4740. Engine.CollisionsEpsilon = 0.001;
  4741. Engine.ShadersRepository = "Babylon/Shaders/";
  4742. return Engine;
  4743. })();
  4744. BABYLON.Engine = Engine;
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.engine.js.map
  4747. var BABYLON;
  4748. (function (BABYLON) {
  4749. var Node = (function () {
  4750. function Node(name, scene) {
  4751. this.state = "";
  4752. this.animations = new Array();
  4753. this._childrenFlag = -1;
  4754. this._isEnabled = true;
  4755. this._isReady = true;
  4756. this._currentRenderId = -1;
  4757. this.name = name;
  4758. this.id = name;
  4759. this._scene = scene;
  4760. this._initCache();
  4761. }
  4762. Node.prototype.getScene = function () {
  4763. return this._scene;
  4764. };
  4765. Node.prototype.getEngine = function () {
  4766. return this._scene.getEngine();
  4767. };
  4768. // override it in derived class
  4769. Node.prototype.getWorldMatrix = function () {
  4770. return BABYLON.Matrix.Identity();
  4771. };
  4772. // override it in derived class if you add new variables to the cache
  4773. // and call the parent class method
  4774. Node.prototype._initCache = function () {
  4775. this._cache = {};
  4776. this._cache.parent = undefined;
  4777. };
  4778. Node.prototype.updateCache = function (force) {
  4779. if (!force && this.isSynchronized())
  4780. return;
  4781. this._cache.parent = this.parent;
  4782. this._updateCache();
  4783. };
  4784. // override it in derived class if you add new variables to the cache
  4785. // and call the parent class method if !ignoreParentClass
  4786. Node.prototype._updateCache = function (ignoreParentClass) {
  4787. };
  4788. // override it in derived class if you add new variables to the cache
  4789. Node.prototype._isSynchronized = function () {
  4790. return true;
  4791. };
  4792. Node.prototype.isSynchronizedWithParent = function () {
  4793. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4794. };
  4795. Node.prototype.isSynchronized = function (updateCache) {
  4796. var check = this.hasNewParent();
  4797. check = check || !this.isSynchronizedWithParent();
  4798. check = check || !this._isSynchronized();
  4799. if (updateCache)
  4800. this.updateCache(true);
  4801. return !check;
  4802. };
  4803. Node.prototype.hasNewParent = function (update) {
  4804. if (this._cache.parent === this.parent)
  4805. return false;
  4806. if (update)
  4807. this._cache.parent = this.parent;
  4808. return true;
  4809. };
  4810. Node.prototype.isReady = function () {
  4811. return this._isReady;
  4812. };
  4813. Node.prototype.isEnabled = function () {
  4814. if (!this._isEnabled) {
  4815. return false;
  4816. }
  4817. if (this.parent) {
  4818. return this.parent.isEnabled();
  4819. }
  4820. return true;
  4821. };
  4822. Node.prototype.setEnabled = function (value) {
  4823. this._isEnabled = value;
  4824. };
  4825. Node.prototype.isDescendantOf = function (ancestor) {
  4826. if (this.parent) {
  4827. if (this.parent === ancestor) {
  4828. return true;
  4829. }
  4830. return this.parent.isDescendantOf(ancestor);
  4831. }
  4832. return false;
  4833. };
  4834. Node.prototype._getDescendants = function (list, results) {
  4835. for (var index = 0; index < list.length; index++) {
  4836. var item = list[index];
  4837. if (item.isDescendantOf(this)) {
  4838. results.push(item);
  4839. }
  4840. }
  4841. };
  4842. Node.prototype.getDescendants = function () {
  4843. var results = [];
  4844. this._getDescendants(this._scene.meshes, results);
  4845. this._getDescendants(this._scene.lights, results);
  4846. this._getDescendants(this._scene.cameras, results);
  4847. return results;
  4848. };
  4849. Node.prototype._setReady = function (state) {
  4850. if (state == this._isReady) {
  4851. return;
  4852. }
  4853. if (!state) {
  4854. this._isReady = false;
  4855. return;
  4856. }
  4857. this._isReady = true;
  4858. if (this.onReady) {
  4859. this.onReady(this);
  4860. }
  4861. };
  4862. return Node;
  4863. })();
  4864. BABYLON.Node = Node;
  4865. })(BABYLON || (BABYLON = {}));
  4866. //# sourceMappingURL=babylon.node.js.map
  4867. var BABYLON;
  4868. (function (BABYLON) {
  4869. var BoundingSphere = (function () {
  4870. function BoundingSphere(minimum, maximum) {
  4871. this.minimum = minimum;
  4872. this.maximum = maximum;
  4873. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4874. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4875. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4876. this.radius = distance * 0.5;
  4877. this.centerWorld = BABYLON.Vector3.Zero();
  4878. this._update(BABYLON.Matrix.Identity());
  4879. }
  4880. // Methods
  4881. BoundingSphere.prototype._update = function (world) {
  4882. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4883. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4884. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4885. };
  4886. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4887. for (var i = 0; i < 6; i++) {
  4888. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4889. return false;
  4890. }
  4891. return true;
  4892. };
  4893. BoundingSphere.prototype.intersectsPoint = function (point) {
  4894. var x = this.centerWorld.x - point.x;
  4895. var y = this.centerWorld.y - point.y;
  4896. var z = this.centerWorld.z - point.z;
  4897. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4898. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4899. return false;
  4900. return true;
  4901. };
  4902. // Statics
  4903. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4904. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4905. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4906. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4907. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4908. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4909. return false;
  4910. return true;
  4911. };
  4912. return BoundingSphere;
  4913. })();
  4914. BABYLON.BoundingSphere = BoundingSphere;
  4915. })(BABYLON || (BABYLON = {}));
  4916. //# sourceMappingURL=babylon.boundingSphere.js.map
  4917. var BABYLON;
  4918. (function (BABYLON) {
  4919. var BoundingBox = (function () {
  4920. function BoundingBox(minimum, maximum) {
  4921. this.minimum = minimum;
  4922. this.maximum = maximum;
  4923. this.vectors = new Array();
  4924. this.vectorsWorld = new Array();
  4925. // Bounding vectors
  4926. this.vectors.push(this.minimum.clone());
  4927. this.vectors.push(this.maximum.clone());
  4928. this.vectors.push(this.minimum.clone());
  4929. this.vectors[2].x = this.maximum.x;
  4930. this.vectors.push(this.minimum.clone());
  4931. this.vectors[3].y = this.maximum.y;
  4932. this.vectors.push(this.minimum.clone());
  4933. this.vectors[4].z = this.maximum.z;
  4934. this.vectors.push(this.maximum.clone());
  4935. this.vectors[5].z = this.minimum.z;
  4936. this.vectors.push(this.maximum.clone());
  4937. this.vectors[6].x = this.minimum.x;
  4938. this.vectors.push(this.maximum.clone());
  4939. this.vectors[7].y = this.minimum.y;
  4940. // OBB
  4941. this.center = this.maximum.add(this.minimum).scale(0.5);
  4942. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4943. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4944. for (var index = 0; index < this.vectors.length; index++) {
  4945. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4946. }
  4947. this.minimumWorld = BABYLON.Vector3.Zero();
  4948. this.maximumWorld = BABYLON.Vector3.Zero();
  4949. this._update(BABYLON.Matrix.Identity());
  4950. }
  4951. // Methods
  4952. BoundingBox.prototype.getWorldMatrix = function () {
  4953. return this._worldMatrix;
  4954. };
  4955. BoundingBox.prototype._update = function (world) {
  4956. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4957. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4958. for (var index = 0; index < this.vectors.length; index++) {
  4959. var v = this.vectorsWorld[index];
  4960. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4961. if (v.x < this.minimumWorld.x)
  4962. this.minimumWorld.x = v.x;
  4963. if (v.y < this.minimumWorld.y)
  4964. this.minimumWorld.y = v.y;
  4965. if (v.z < this.minimumWorld.z)
  4966. this.minimumWorld.z = v.z;
  4967. if (v.x > this.maximumWorld.x)
  4968. this.maximumWorld.x = v.x;
  4969. if (v.y > this.maximumWorld.y)
  4970. this.maximumWorld.y = v.y;
  4971. if (v.z > this.maximumWorld.z)
  4972. this.maximumWorld.z = v.z;
  4973. }
  4974. // OBB
  4975. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4976. this.center.scaleInPlace(0.5);
  4977. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4978. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4979. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4980. this._worldMatrix = world;
  4981. };
  4982. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4983. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4984. };
  4985. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4986. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4987. };
  4988. BoundingBox.prototype.intersectsPoint = function (point) {
  4989. var delta = BABYLON.Engine.Epsilon;
  4990. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4991. return false;
  4992. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4993. return false;
  4994. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4995. return false;
  4996. return true;
  4997. };
  4998. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4999. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5000. };
  5001. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5002. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5003. return false;
  5004. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5005. return false;
  5006. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5007. return false;
  5008. return true;
  5009. };
  5010. // Statics
  5011. BoundingBox.Intersects = function (box0, box1) {
  5012. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5013. return false;
  5014. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5015. return false;
  5016. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5017. return false;
  5018. return true;
  5019. };
  5020. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5021. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5022. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5023. return (num <= (sphereRadius * sphereRadius));
  5024. };
  5025. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5026. for (var p = 0; p < 6; p++) {
  5027. for (var i = 0; i < 8; i++) {
  5028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5029. return false;
  5030. }
  5031. }
  5032. }
  5033. return true;
  5034. };
  5035. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5036. for (var p = 0; p < 6; p++) {
  5037. var inCount = 8;
  5038. for (var i = 0; i < 8; i++) {
  5039. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5040. --inCount;
  5041. } else {
  5042. break;
  5043. }
  5044. }
  5045. if (inCount == 0)
  5046. return false;
  5047. }
  5048. return true;
  5049. };
  5050. return BoundingBox;
  5051. })();
  5052. BABYLON.BoundingBox = BoundingBox;
  5053. })(BABYLON || (BABYLON = {}));
  5054. //# sourceMappingURL=babylon.boundingBox.js.map
  5055. var BABYLON;
  5056. (function (BABYLON) {
  5057. var computeBoxExtents = function (axis, box) {
  5058. var p = BABYLON.Vector3.Dot(box.center, axis);
  5059. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5060. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5061. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5062. var r = r0 + r1 + r2;
  5063. return {
  5064. min: p - r,
  5065. max: p + r
  5066. };
  5067. };
  5068. var extentsOverlap = function (min0, max0, min1, max1) {
  5069. return !(min0 > max1 || min1 > max0);
  5070. };
  5071. var axisOverlap = function (axis, box0, box1) {
  5072. var result0 = computeBoxExtents(axis, box0);
  5073. var result1 = computeBoxExtents(axis, box1);
  5074. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5075. };
  5076. var BoundingInfo = (function () {
  5077. function BoundingInfo(minimum, maximum) {
  5078. this.minimum = minimum;
  5079. this.maximum = maximum;
  5080. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5081. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5082. }
  5083. // Methods
  5084. BoundingInfo.prototype._update = function (world) {
  5085. this.boundingBox._update(world);
  5086. this.boundingSphere._update(world);
  5087. };
  5088. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5089. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5090. return false;
  5091. return this.boundingBox.isInFrustum(frustumPlanes);
  5092. };
  5093. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5094. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5095. };
  5096. BoundingInfo.prototype._checkCollision = function (collider) {
  5097. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5098. };
  5099. BoundingInfo.prototype.intersectsPoint = function (point) {
  5100. if (!this.boundingSphere.centerWorld) {
  5101. return false;
  5102. }
  5103. if (!this.boundingSphere.intersectsPoint(point)) {
  5104. return false;
  5105. }
  5106. if (!this.boundingBox.intersectsPoint(point)) {
  5107. return false;
  5108. }
  5109. return true;
  5110. };
  5111. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5112. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5113. return false;
  5114. }
  5115. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5116. return false;
  5117. }
  5118. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5119. return false;
  5120. }
  5121. if (!precise) {
  5122. return true;
  5123. }
  5124. var box0 = this.boundingBox;
  5125. var box1 = boundingInfo.boundingBox;
  5126. if (!axisOverlap(box0.directions[0], box0, box1))
  5127. return false;
  5128. if (!axisOverlap(box0.directions[1], box0, box1))
  5129. return false;
  5130. if (!axisOverlap(box0.directions[2], box0, box1))
  5131. return false;
  5132. if (!axisOverlap(box1.directions[0], box0, box1))
  5133. return false;
  5134. if (!axisOverlap(box1.directions[1], box0, box1))
  5135. return false;
  5136. if (!axisOverlap(box1.directions[2], box0, box1))
  5137. return false;
  5138. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5139. return false;
  5140. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5141. return false;
  5142. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5143. return false;
  5144. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5145. return false;
  5146. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5147. return false;
  5148. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5149. return false;
  5150. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5151. return false;
  5152. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5153. return false;
  5154. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5155. return false;
  5156. return true;
  5157. };
  5158. return BoundingInfo;
  5159. })();
  5160. BABYLON.BoundingInfo = BoundingInfo;
  5161. })(BABYLON || (BABYLON = {}));
  5162. //# sourceMappingURL=babylon.boundingInfo.js.map
  5163. var BABYLON;
  5164. (function (BABYLON) {
  5165. var Light = (function (_super) {
  5166. __extends(Light, _super);
  5167. function Light(name, scene) {
  5168. _super.call(this, name, scene);
  5169. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5170. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5171. this.intensity = 1.0;
  5172. this.range = Number.MAX_VALUE;
  5173. this.includedOnlyMeshes = new Array();
  5174. this.excludedMeshes = new Array();
  5175. this._excludedMeshesIds = new Array();
  5176. this._includedOnlyMeshesIds = new Array();
  5177. scene.lights.push(this);
  5178. }
  5179. Light.prototype.getShadowGenerator = function () {
  5180. return this._shadowGenerator;
  5181. };
  5182. Light.prototype.getAbsolutePosition = function () {
  5183. return BABYLON.Vector3.Zero();
  5184. };
  5185. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5186. };
  5187. Light.prototype._getWorldMatrix = function () {
  5188. return BABYLON.Matrix.Identity();
  5189. };
  5190. Light.prototype.canAffectMesh = function (mesh) {
  5191. if (!mesh) {
  5192. return true;
  5193. }
  5194. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5195. return false;
  5196. }
  5197. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5198. return false;
  5199. }
  5200. return true;
  5201. };
  5202. Light.prototype.getWorldMatrix = function () {
  5203. this._currentRenderId = this.getScene().getRenderId();
  5204. var worldMatrix = this._getWorldMatrix();
  5205. if (this.parent && this.parent.getWorldMatrix) {
  5206. if (!this._parentedWorldMatrix) {
  5207. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5208. }
  5209. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5210. return this._parentedWorldMatrix;
  5211. }
  5212. return worldMatrix;
  5213. };
  5214. Light.prototype.dispose = function () {
  5215. if (this._shadowGenerator) {
  5216. this._shadowGenerator.dispose();
  5217. this._shadowGenerator = null;
  5218. }
  5219. // Remove from scene
  5220. var index = this.getScene().lights.indexOf(this);
  5221. this.getScene().lights.splice(index, 1);
  5222. };
  5223. return Light;
  5224. })(BABYLON.Node);
  5225. BABYLON.Light = Light;
  5226. })(BABYLON || (BABYLON = {}));
  5227. //# sourceMappingURL=babylon.light.js.map
  5228. var BABYLON;
  5229. (function (BABYLON) {
  5230. var PointLight = (function (_super) {
  5231. __extends(PointLight, _super);
  5232. function PointLight(name, position, scene) {
  5233. _super.call(this, name, scene);
  5234. this.position = position;
  5235. }
  5236. PointLight.prototype.getAbsolutePosition = function () {
  5237. return this._transformedPosition ? this._transformedPosition : this.position;
  5238. };
  5239. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5240. if (this.parent && this.parent.getWorldMatrix) {
  5241. if (!this._transformedPosition) {
  5242. this._transformedPosition = BABYLON.Vector3.Zero();
  5243. }
  5244. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5245. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5246. return;
  5247. }
  5248. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5249. };
  5250. PointLight.prototype.getShadowGenerator = function () {
  5251. return null;
  5252. };
  5253. PointLight.prototype._getWorldMatrix = function () {
  5254. if (!this._worldMatrix) {
  5255. this._worldMatrix = BABYLON.Matrix.Identity();
  5256. }
  5257. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5258. return this._worldMatrix;
  5259. };
  5260. return PointLight;
  5261. })(BABYLON.Light);
  5262. BABYLON.PointLight = PointLight;
  5263. })(BABYLON || (BABYLON = {}));
  5264. //# sourceMappingURL=babylon.pointLight.js.map
  5265. var BABYLON;
  5266. (function (BABYLON) {
  5267. var SpotLight = (function (_super) {
  5268. __extends(SpotLight, _super);
  5269. function SpotLight(name, position, direction, angle, exponent, scene) {
  5270. _super.call(this, name, scene);
  5271. this.position = position;
  5272. this.direction = direction;
  5273. this.angle = angle;
  5274. this.exponent = exponent;
  5275. }
  5276. SpotLight.prototype.getAbsolutePosition = function () {
  5277. return this.transformedPosition ? this.transformedPosition : this.position;
  5278. };
  5279. SpotLight.prototype.setDirectionToTarget = function (target) {
  5280. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5281. return this.direction;
  5282. };
  5283. SpotLight.prototype.computeTransformedPosition = function () {
  5284. if (this.parent && this.parent.getWorldMatrix) {
  5285. if (!this.transformedPosition) {
  5286. this.transformedPosition = BABYLON.Vector3.Zero();
  5287. }
  5288. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5289. return true;
  5290. }
  5291. return false;
  5292. };
  5293. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5294. var normalizeDirection;
  5295. if (this.parent && this.parent.getWorldMatrix) {
  5296. if (!this._transformedDirection) {
  5297. this._transformedDirection = BABYLON.Vector3.Zero();
  5298. }
  5299. this.computeTransformedPosition();
  5300. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5301. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5302. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5303. } else {
  5304. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5305. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5306. }
  5307. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5308. };
  5309. SpotLight.prototype._getWorldMatrix = function () {
  5310. if (!this._worldMatrix) {
  5311. this._worldMatrix = BABYLON.Matrix.Identity();
  5312. }
  5313. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5314. return this._worldMatrix;
  5315. };
  5316. return SpotLight;
  5317. })(BABYLON.Light);
  5318. BABYLON.SpotLight = SpotLight;
  5319. })(BABYLON || (BABYLON = {}));
  5320. //# sourceMappingURL=babylon.spotLight.js.map
  5321. var BABYLON;
  5322. (function (BABYLON) {
  5323. var DirectionalLight = (function (_super) {
  5324. __extends(DirectionalLight, _super);
  5325. function DirectionalLight(name, direction, scene) {
  5326. _super.call(this, name, scene);
  5327. this.direction = direction;
  5328. this.position = direction.scale(-1);
  5329. }
  5330. DirectionalLight.prototype.getAbsolutePosition = function () {
  5331. return this.transformedPosition ? this.transformedPosition : this.position;
  5332. };
  5333. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5334. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5335. return this.direction;
  5336. };
  5337. DirectionalLight.prototype.computeTransformedPosition = function () {
  5338. if (this.parent && this.parent.getWorldMatrix) {
  5339. if (!this.transformedPosition) {
  5340. this.transformedPosition = BABYLON.Vector3.Zero();
  5341. }
  5342. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5343. return true;
  5344. }
  5345. return false;
  5346. };
  5347. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5348. if (this.parent && this.parent.getWorldMatrix) {
  5349. if (!this._transformedDirection) {
  5350. this._transformedDirection = BABYLON.Vector3.Zero();
  5351. }
  5352. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5353. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5354. return;
  5355. }
  5356. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5357. };
  5358. DirectionalLight.prototype._getWorldMatrix = function () {
  5359. if (!this._worldMatrix) {
  5360. this._worldMatrix = BABYLON.Matrix.Identity();
  5361. }
  5362. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5363. return this._worldMatrix;
  5364. };
  5365. return DirectionalLight;
  5366. })(BABYLON.Light);
  5367. BABYLON.DirectionalLight = DirectionalLight;
  5368. })(BABYLON || (BABYLON = {}));
  5369. //# sourceMappingURL=babylon.directionalLight.js.map
  5370. var BABYLON;
  5371. (function (BABYLON) {
  5372. var ShadowGenerator = (function () {
  5373. function ShadowGenerator(mapSize, light) {
  5374. var _this = this;
  5375. // Members
  5376. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5377. this._darkness = 0;
  5378. this._transparencyShadow = false;
  5379. this._viewMatrix = BABYLON.Matrix.Zero();
  5380. this._projectionMatrix = BABYLON.Matrix.Zero();
  5381. this._transformMatrix = BABYLON.Matrix.Zero();
  5382. this._worldViewProjection = BABYLON.Matrix.Zero();
  5383. this._light = light;
  5384. this._scene = light.getScene();
  5385. light._shadowGenerator = this;
  5386. // Render target
  5387. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5388. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5389. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5390. this._shadowMap.renderParticles = false;
  5391. // Custom render function
  5392. var renderSubMesh = function (subMesh) {
  5393. var mesh = subMesh.getRenderingMesh();
  5394. var scene = _this._scene;
  5395. var engine = scene.getEngine();
  5396. // Culling
  5397. engine.setState(subMesh.getMaterial().backFaceCulling);
  5398. // Managing instances
  5399. var batch = mesh._getInstancesRenderList(subMesh._id);
  5400. if (batch.mustReturn) {
  5401. return;
  5402. }
  5403. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5404. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5405. engine.enableEffect(_this._effect);
  5406. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5407. var material = subMesh.getMaterial();
  5408. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5409. // Alpha test
  5410. if (material && material.needAlphaTesting()) {
  5411. var alphaTexture = material.getAlphaTestTexture();
  5412. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5413. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5414. }
  5415. // Bones
  5416. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5417. if (useBones) {
  5418. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5419. }
  5420. if (hardwareInstancedRendering) {
  5421. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5422. } else {
  5423. if (batch.renderSelf[subMesh._id]) {
  5424. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5425. // Draw
  5426. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5427. }
  5428. if (batch.visibleInstances[subMesh._id]) {
  5429. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5430. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5431. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5432. // Draw
  5433. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5434. }
  5435. }
  5436. }
  5437. } else {
  5438. // Need to reset refresh rate of the shadowMap
  5439. _this._shadowMap.resetRefreshCounter();
  5440. }
  5441. };
  5442. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5443. var index;
  5444. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5445. renderSubMesh(opaqueSubMeshes.data[index]);
  5446. }
  5447. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5448. renderSubMesh(alphaTestSubMeshes.data[index]);
  5449. }
  5450. if (_this._transparencyShadow) {
  5451. for (index = 0; index < transparentSubMeshes.length; index++) {
  5452. renderSubMesh(transparentSubMeshes.data[index]);
  5453. }
  5454. }
  5455. };
  5456. }
  5457. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5458. // Static
  5459. get: function () {
  5460. return ShadowGenerator._FILTER_NONE;
  5461. },
  5462. enumerable: true,
  5463. configurable: true
  5464. });
  5465. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5466. get: function () {
  5467. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5473. get: function () {
  5474. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5480. get: function () {
  5481. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5482. },
  5483. set: function (value) {
  5484. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5485. },
  5486. enumerable: true,
  5487. configurable: true
  5488. });
  5489. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5490. get: function () {
  5491. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5492. },
  5493. set: function (value) {
  5494. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5495. },
  5496. enumerable: true,
  5497. configurable: true
  5498. });
  5499. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5500. var defines = [];
  5501. if (this.useVarianceShadowMap) {
  5502. defines.push("#define VSM");
  5503. }
  5504. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5505. var mesh = subMesh.getMesh();
  5506. var scene = mesh.getScene();
  5507. var material = subMesh.getMaterial();
  5508. // Alpha test
  5509. if (material && material.needAlphaTesting()) {
  5510. defines.push("#define ALPHATEST");
  5511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5512. attribs.push(BABYLON.VertexBuffer.UVKind);
  5513. defines.push("#define UV1");
  5514. }
  5515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5516. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5517. defines.push("#define UV2");
  5518. }
  5519. }
  5520. // Bones
  5521. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5522. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5523. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5524. defines.push("#define BONES");
  5525. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5526. }
  5527. // Instances
  5528. if (useInstances) {
  5529. defines.push("#define INSTANCES");
  5530. attribs.push("world0");
  5531. attribs.push("world1");
  5532. attribs.push("world2");
  5533. attribs.push("world3");
  5534. }
  5535. // Get correct effect
  5536. var join = defines.join("\n");
  5537. if (this._cachedDefines !== join) {
  5538. this._cachedDefines = join;
  5539. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5540. }
  5541. return this._effect.isReady();
  5542. };
  5543. ShadowGenerator.prototype.getShadowMap = function () {
  5544. return this._shadowMap;
  5545. };
  5546. ShadowGenerator.prototype.getLight = function () {
  5547. return this._light;
  5548. };
  5549. // Methods
  5550. ShadowGenerator.prototype.getTransformMatrix = function () {
  5551. var lightPosition = this._light.position;
  5552. var lightDirection = this._light.direction;
  5553. if (this._light.computeTransformedPosition()) {
  5554. lightPosition = this._light.transformedPosition;
  5555. }
  5556. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5557. this._cachedPosition = lightPosition.clone();
  5558. this._cachedDirection = lightDirection.clone();
  5559. var activeCamera = this._scene.activeCamera;
  5560. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5561. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5562. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5563. }
  5564. return this._transformMatrix;
  5565. };
  5566. ShadowGenerator.prototype.getDarkness = function () {
  5567. return this._darkness;
  5568. };
  5569. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5570. if (darkness >= 1.0)
  5571. this._darkness = 1.0;
  5572. else if (darkness <= 0.0)
  5573. this._darkness = 0.0;
  5574. else
  5575. this._darkness = darkness;
  5576. };
  5577. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5578. this._transparencyShadow = hasShadow;
  5579. };
  5580. ShadowGenerator.prototype.dispose = function () {
  5581. this._shadowMap.dispose();
  5582. };
  5583. ShadowGenerator._FILTER_NONE = 0;
  5584. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5585. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5586. return ShadowGenerator;
  5587. })();
  5588. BABYLON.ShadowGenerator = ShadowGenerator;
  5589. })(BABYLON || (BABYLON = {}));
  5590. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5591. var BABYLON;
  5592. (function (BABYLON) {
  5593. var HemisphericLight = (function (_super) {
  5594. __extends(HemisphericLight, _super);
  5595. function HemisphericLight(name, direction, scene) {
  5596. _super.call(this, name, scene);
  5597. this.direction = direction;
  5598. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5599. }
  5600. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5601. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5602. return this.direction;
  5603. };
  5604. HemisphericLight.prototype.getShadowGenerator = function () {
  5605. return null;
  5606. };
  5607. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5608. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5609. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5610. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5611. };
  5612. HemisphericLight.prototype._getWorldMatrix = function () {
  5613. if (!this._worldMatrix) {
  5614. this._worldMatrix = BABYLON.Matrix.Identity();
  5615. }
  5616. return this._worldMatrix;
  5617. };
  5618. return HemisphericLight;
  5619. })(BABYLON.Light);
  5620. BABYLON.HemisphericLight = HemisphericLight;
  5621. })(BABYLON || (BABYLON = {}));
  5622. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5623. var BABYLON;
  5624. (function (BABYLON) {
  5625. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5626. if (boxMin.x > sphereCenter.x + sphereRadius)
  5627. return false;
  5628. if (sphereCenter.x - sphereRadius > boxMax.x)
  5629. return false;
  5630. if (boxMin.y > sphereCenter.y + sphereRadius)
  5631. return false;
  5632. if (sphereCenter.y - sphereRadius > boxMax.y)
  5633. return false;
  5634. if (boxMin.z > sphereCenter.z + sphereRadius)
  5635. return false;
  5636. if (sphereCenter.z - sphereRadius > boxMax.z)
  5637. return false;
  5638. return true;
  5639. };
  5640. var getLowestRoot = function (a, b, c, maxR) {
  5641. var determinant = b * b - 4.0 * a * c;
  5642. var result = { root: 0, found: false };
  5643. if (determinant < 0)
  5644. return result;
  5645. var sqrtD = Math.sqrt(determinant);
  5646. var r1 = (-b - sqrtD) / (2.0 * a);
  5647. var r2 = (-b + sqrtD) / (2.0 * a);
  5648. if (r1 > r2) {
  5649. var temp = r2;
  5650. r2 = r1;
  5651. r1 = temp;
  5652. }
  5653. if (r1 > 0 && r1 < maxR) {
  5654. result.root = r1;
  5655. result.found = true;
  5656. return result;
  5657. }
  5658. if (r2 > 0 && r2 < maxR) {
  5659. result.root = r2;
  5660. result.found = true;
  5661. return result;
  5662. }
  5663. return result;
  5664. };
  5665. var Collider = (function () {
  5666. function Collider() {
  5667. this.radius = new BABYLON.Vector3(1, 1, 1);
  5668. this.retry = 0;
  5669. this.basePointWorld = BABYLON.Vector3.Zero();
  5670. this.velocityWorld = BABYLON.Vector3.Zero();
  5671. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5672. this._collisionPoint = BABYLON.Vector3.Zero();
  5673. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5674. this._tempVector = BABYLON.Vector3.Zero();
  5675. this._tempVector2 = BABYLON.Vector3.Zero();
  5676. this._tempVector3 = BABYLON.Vector3.Zero();
  5677. this._tempVector4 = BABYLON.Vector3.Zero();
  5678. this._edge = BABYLON.Vector3.Zero();
  5679. this._baseToVertex = BABYLON.Vector3.Zero();
  5680. this._destinationPoint = BABYLON.Vector3.Zero();
  5681. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5682. this._displacementVector = BABYLON.Vector3.Zero();
  5683. }
  5684. // Methods
  5685. Collider.prototype._initialize = function (source, dir, e) {
  5686. this.velocity = dir;
  5687. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5688. this.basePoint = source;
  5689. source.multiplyToRef(this.radius, this.basePointWorld);
  5690. dir.multiplyToRef(this.radius, this.velocityWorld);
  5691. this.velocityWorldLength = this.velocityWorld.length();
  5692. this.epsilon = e;
  5693. this.collisionFound = false;
  5694. };
  5695. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5696. pa.subtractToRef(point, this._tempVector);
  5697. pb.subtractToRef(point, this._tempVector2);
  5698. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5699. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5700. if (d < 0)
  5701. return false;
  5702. pc.subtractToRef(point, this._tempVector3);
  5703. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5704. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5705. if (d < 0)
  5706. return false;
  5707. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5708. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5709. return d >= 0;
  5710. };
  5711. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5712. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5713. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5714. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5715. return false;
  5716. }
  5717. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5718. return false;
  5719. return true;
  5720. };
  5721. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5722. var t0;
  5723. var embeddedInPlane = false;
  5724. if (!subMesh._trianglePlanes) {
  5725. subMesh._trianglePlanes = [];
  5726. }
  5727. if (!subMesh._trianglePlanes[faceIndex]) {
  5728. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5729. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5730. }
  5731. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5732. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5733. return;
  5734. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5735. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5736. if (normalDotVelocity == 0) {
  5737. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5738. return;
  5739. embeddedInPlane = true;
  5740. t0 = 0;
  5741. } else {
  5742. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5743. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5744. if (t0 > t1) {
  5745. var temp = t1;
  5746. t1 = t0;
  5747. t0 = temp;
  5748. }
  5749. if (t0 > 1.0 || t1 < 0.0)
  5750. return;
  5751. if (t0 < 0)
  5752. t0 = 0;
  5753. if (t0 > 1.0)
  5754. t0 = 1.0;
  5755. }
  5756. this._collisionPoint.copyFromFloats(0, 0, 0);
  5757. var found = false;
  5758. var t = 1.0;
  5759. if (!embeddedInPlane) {
  5760. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5761. this.velocity.scaleToRef(t0, this._tempVector);
  5762. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5763. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5764. found = true;
  5765. t = t0;
  5766. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5767. }
  5768. }
  5769. if (!found) {
  5770. var velocitySquaredLength = this.velocity.lengthSquared();
  5771. var a = velocitySquaredLength;
  5772. this.basePoint.subtractToRef(p1, this._tempVector);
  5773. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5774. var c = this._tempVector.lengthSquared() - 1.0;
  5775. var lowestRoot = getLowestRoot(a, b, c, t);
  5776. if (lowestRoot.found) {
  5777. t = lowestRoot.root;
  5778. found = true;
  5779. this._collisionPoint.copyFrom(p1);
  5780. }
  5781. this.basePoint.subtractToRef(p2, this._tempVector);
  5782. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5783. c = this._tempVector.lengthSquared() - 1.0;
  5784. lowestRoot = getLowestRoot(a, b, c, t);
  5785. if (lowestRoot.found) {
  5786. t = lowestRoot.root;
  5787. found = true;
  5788. this._collisionPoint.copyFrom(p2);
  5789. }
  5790. this.basePoint.subtractToRef(p3, this._tempVector);
  5791. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5792. c = this._tempVector.lengthSquared() - 1.0;
  5793. lowestRoot = getLowestRoot(a, b, c, t);
  5794. if (lowestRoot.found) {
  5795. t = lowestRoot.root;
  5796. found = true;
  5797. this._collisionPoint.copyFrom(p3);
  5798. }
  5799. p2.subtractToRef(p1, this._edge);
  5800. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5801. var edgeSquaredLength = this._edge.lengthSquared();
  5802. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5803. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5804. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5805. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5806. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5807. lowestRoot = getLowestRoot(a, b, c, t);
  5808. if (lowestRoot.found) {
  5809. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5810. if (f >= 0.0 && f <= 1.0) {
  5811. t = lowestRoot.root;
  5812. found = true;
  5813. this._edge.scaleInPlace(f);
  5814. p1.addToRef(this._edge, this._collisionPoint);
  5815. }
  5816. }
  5817. p3.subtractToRef(p2, this._edge);
  5818. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5819. edgeSquaredLength = this._edge.lengthSquared();
  5820. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5821. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5822. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5823. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5824. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5825. lowestRoot = getLowestRoot(a, b, c, t);
  5826. if (lowestRoot.found) {
  5827. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5828. if (f >= 0.0 && f <= 1.0) {
  5829. t = lowestRoot.root;
  5830. found = true;
  5831. this._edge.scaleInPlace(f);
  5832. p2.addToRef(this._edge, this._collisionPoint);
  5833. }
  5834. }
  5835. p1.subtractToRef(p3, this._edge);
  5836. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5837. edgeSquaredLength = this._edge.lengthSquared();
  5838. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5839. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5840. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5841. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5842. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5843. lowestRoot = getLowestRoot(a, b, c, t);
  5844. if (lowestRoot.found) {
  5845. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5846. if (f >= 0.0 && f <= 1.0) {
  5847. t = lowestRoot.root;
  5848. found = true;
  5849. this._edge.scaleInPlace(f);
  5850. p3.addToRef(this._edge, this._collisionPoint);
  5851. }
  5852. }
  5853. }
  5854. if (found) {
  5855. var distToCollision = t * this.velocity.length();
  5856. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5857. if (!this.intersectionPoint) {
  5858. this.intersectionPoint = this._collisionPoint.clone();
  5859. } else {
  5860. this.intersectionPoint.copyFrom(this._collisionPoint);
  5861. }
  5862. this.nearestDistance = distToCollision;
  5863. this.collisionFound = true;
  5864. this.collidedMesh = subMesh.getMesh();
  5865. }
  5866. }
  5867. };
  5868. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5869. for (var i = indexStart; i < indexEnd; i += 3) {
  5870. var p1 = pts[indices[i] - decal];
  5871. var p2 = pts[indices[i + 1] - decal];
  5872. var p3 = pts[indices[i + 2] - decal];
  5873. this._testTriangle(i, subMesh, p3, p2, p1);
  5874. }
  5875. };
  5876. Collider.prototype._getResponse = function (pos, vel) {
  5877. pos.addToRef(vel, this._destinationPoint);
  5878. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5879. this.basePoint.addToRef(vel, pos);
  5880. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5881. this._slidePlaneNormal.normalize();
  5882. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5883. pos.addInPlace(this._displacementVector);
  5884. this.intersectionPoint.addInPlace(this._displacementVector);
  5885. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5886. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5887. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5888. };
  5889. return Collider;
  5890. })();
  5891. BABYLON.Collider = Collider;
  5892. })(BABYLON || (BABYLON = {}));
  5893. //# sourceMappingURL=babylon.collider.js.map
  5894. var BABYLON;
  5895. (function (BABYLON) {
  5896. var Camera = (function (_super) {
  5897. __extends(Camera, _super);
  5898. function Camera(name, position, scene) {
  5899. _super.call(this, name, scene);
  5900. this.position = position;
  5901. // Members
  5902. this.upVector = BABYLON.Vector3.Up();
  5903. this.orthoLeft = null;
  5904. this.orthoRight = null;
  5905. this.orthoBottom = null;
  5906. this.orthoTop = null;
  5907. this.fov = 0.8;
  5908. this.minZ = 1.0;
  5909. this.maxZ = 10000.0;
  5910. this.inertia = 0.9;
  5911. this.mode = Camera.PERSPECTIVE_CAMERA;
  5912. this.isIntermediate = false;
  5913. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5914. this.subCameras = [];
  5915. this.layerMask = 0xFFFFFFFF;
  5916. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5917. this._projectionMatrix = new BABYLON.Matrix();
  5918. this._postProcesses = new Array();
  5919. this._postProcessesTakenIndices = [];
  5920. scene.cameras.push(this);
  5921. if (!scene.activeCamera) {
  5922. scene.activeCamera = this;
  5923. }
  5924. }
  5925. //Cache
  5926. Camera.prototype._initCache = function () {
  5927. _super.prototype._initCache.call(this);
  5928. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5929. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5930. this._cache.mode = undefined;
  5931. this._cache.minZ = undefined;
  5932. this._cache.maxZ = undefined;
  5933. this._cache.fov = undefined;
  5934. this._cache.aspectRatio = undefined;
  5935. this._cache.orthoLeft = undefined;
  5936. this._cache.orthoRight = undefined;
  5937. this._cache.orthoBottom = undefined;
  5938. this._cache.orthoTop = undefined;
  5939. this._cache.renderWidth = undefined;
  5940. this._cache.renderHeight = undefined;
  5941. };
  5942. Camera.prototype._updateCache = function (ignoreParentClass) {
  5943. if (!ignoreParentClass) {
  5944. _super.prototype._updateCache.call(this);
  5945. }
  5946. var engine = this.getEngine();
  5947. this._cache.position.copyFrom(this.position);
  5948. this._cache.upVector.copyFrom(this.upVector);
  5949. this._cache.mode = this.mode;
  5950. this._cache.minZ = this.minZ;
  5951. this._cache.maxZ = this.maxZ;
  5952. this._cache.fov = this.fov;
  5953. this._cache.aspectRatio = engine.getAspectRatio(this);
  5954. this._cache.orthoLeft = this.orthoLeft;
  5955. this._cache.orthoRight = this.orthoRight;
  5956. this._cache.orthoBottom = this.orthoBottom;
  5957. this._cache.orthoTop = this.orthoTop;
  5958. this._cache.renderWidth = engine.getRenderWidth();
  5959. this._cache.renderHeight = engine.getRenderHeight();
  5960. };
  5961. Camera.prototype._updateFromScene = function () {
  5962. this.updateCache();
  5963. this._update();
  5964. };
  5965. // Synchronized
  5966. Camera.prototype._isSynchronized = function () {
  5967. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5968. };
  5969. Camera.prototype._isSynchronizedViewMatrix = function () {
  5970. if (!_super.prototype._isSynchronized.call(this))
  5971. return false;
  5972. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5973. };
  5974. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5975. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5976. if (!check) {
  5977. return false;
  5978. }
  5979. var engine = this.getEngine();
  5980. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5981. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5982. } else {
  5983. 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();
  5984. }
  5985. return check;
  5986. };
  5987. // Controls
  5988. Camera.prototype.attachControl = function (element) {
  5989. };
  5990. Camera.prototype.detachControl = function (element) {
  5991. };
  5992. Camera.prototype._update = function () {
  5993. };
  5994. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5995. if (typeof insertAt === "undefined") { insertAt = null; }
  5996. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5997. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5998. return 0;
  5999. }
  6000. if (insertAt == null || insertAt < 0) {
  6001. this._postProcesses.push(postProcess);
  6002. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6003. return this._postProcesses.length - 1;
  6004. }
  6005. var add = 0;
  6006. if (this._postProcesses[insertAt]) {
  6007. var start = this._postProcesses.length - 1;
  6008. for (var i = start; i >= insertAt + 1; --i) {
  6009. this._postProcesses[i + 1] = this._postProcesses[i];
  6010. }
  6011. add = 1;
  6012. }
  6013. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6014. if (this._postProcessesTakenIndices[i] < insertAt) {
  6015. continue;
  6016. }
  6017. start = this._postProcessesTakenIndices.length - 1;
  6018. for (var j = start; j >= i; --j) {
  6019. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6020. }
  6021. this._postProcessesTakenIndices[i] = insertAt;
  6022. break;
  6023. }
  6024. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6025. this._postProcessesTakenIndices.push(insertAt);
  6026. }
  6027. var result = insertAt + add;
  6028. this._postProcesses[result] = postProcess;
  6029. return result;
  6030. };
  6031. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6032. if (typeof atIndices === "undefined") { atIndices = null; }
  6033. var result = [];
  6034. if (!atIndices) {
  6035. var length = this._postProcesses.length;
  6036. for (var i = 0; i < length; i++) {
  6037. if (this._postProcesses[i] !== postProcess) {
  6038. continue;
  6039. }
  6040. delete this._postProcesses[i];
  6041. var index = this._postProcessesTakenIndices.indexOf(i);
  6042. this._postProcessesTakenIndices.splice(index, 1);
  6043. }
  6044. } else {
  6045. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6046. for (i = 0; i < atIndices.length; i++) {
  6047. var foundPostProcess = this._postProcesses[atIndices[i]];
  6048. if (foundPostProcess !== postProcess) {
  6049. result.push(i);
  6050. continue;
  6051. }
  6052. delete this._postProcesses[atIndices[i]];
  6053. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6054. this._postProcessesTakenIndices.splice(index, 1);
  6055. }
  6056. }
  6057. return result;
  6058. };
  6059. Camera.prototype.getWorldMatrix = function () {
  6060. if (!this._worldMatrix) {
  6061. this._worldMatrix = BABYLON.Matrix.Identity();
  6062. }
  6063. var viewMatrix = this.getViewMatrix();
  6064. viewMatrix.invertToRef(this._worldMatrix);
  6065. return this._worldMatrix;
  6066. };
  6067. Camera.prototype._getViewMatrix = function () {
  6068. return BABYLON.Matrix.Identity();
  6069. };
  6070. Camera.prototype.getViewMatrix = function () {
  6071. this._computedViewMatrix = this._computeViewMatrix();
  6072. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6073. return this._computedViewMatrix;
  6074. }
  6075. if (!this._worldMatrix) {
  6076. this._worldMatrix = BABYLON.Matrix.Identity();
  6077. }
  6078. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6079. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6080. this._computedViewMatrix.invert();
  6081. this._currentRenderId = this.getScene().getRenderId();
  6082. return this._computedViewMatrix;
  6083. };
  6084. Camera.prototype._computeViewMatrix = function (force) {
  6085. if (!force && this._isSynchronizedViewMatrix()) {
  6086. return this._computedViewMatrix;
  6087. }
  6088. this._computedViewMatrix = this._getViewMatrix();
  6089. if (!this.parent || !this.parent.getWorldMatrix) {
  6090. this._currentRenderId = this.getScene().getRenderId();
  6091. }
  6092. return this._computedViewMatrix;
  6093. };
  6094. Camera.prototype.getProjectionMatrix = function (force) {
  6095. if (!force && this._isSynchronizedProjectionMatrix()) {
  6096. return this._projectionMatrix;
  6097. }
  6098. var engine = this.getEngine();
  6099. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6100. if (this.minZ <= 0) {
  6101. this.minZ = 0.1;
  6102. }
  6103. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6104. return this._projectionMatrix;
  6105. }
  6106. var halfWidth = engine.getRenderWidth() / 2.0;
  6107. var halfHeight = engine.getRenderHeight() / 2.0;
  6108. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6109. return this._projectionMatrix;
  6110. };
  6111. Camera.prototype.dispose = function () {
  6112. // Remove from scene
  6113. var index = this.getScene().cameras.indexOf(this);
  6114. this.getScene().cameras.splice(index, 1);
  6115. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6116. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6117. }
  6118. };
  6119. Camera.PERSPECTIVE_CAMERA = 0;
  6120. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6121. return Camera;
  6122. })(BABYLON.Node);
  6123. BABYLON.Camera = Camera;
  6124. })(BABYLON || (BABYLON = {}));
  6125. //# sourceMappingURL=babylon.camera.js.map
  6126. var BABYLON;
  6127. (function (BABYLON) {
  6128. var TargetCamera = (function (_super) {
  6129. __extends(TargetCamera, _super);
  6130. function TargetCamera(name, position, scene) {
  6131. _super.call(this, name, position, scene);
  6132. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6133. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6134. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6135. this.speed = 2.0;
  6136. this.noRotationConstraint = false;
  6137. this.lockedTarget = null;
  6138. this._currentTarget = BABYLON.Vector3.Zero();
  6139. this._viewMatrix = BABYLON.Matrix.Zero();
  6140. this._camMatrix = BABYLON.Matrix.Zero();
  6141. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6142. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6143. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6144. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6145. this._lookAtTemp = BABYLON.Matrix.Zero();
  6146. this._tempMatrix = BABYLON.Matrix.Zero();
  6147. }
  6148. TargetCamera.prototype._getLockedTargetPosition = function () {
  6149. if (!this.lockedTarget) {
  6150. return null;
  6151. }
  6152. return this.lockedTarget.position || this.lockedTarget;
  6153. };
  6154. // Cache
  6155. TargetCamera.prototype._initCache = function () {
  6156. _super.prototype._initCache.call(this);
  6157. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6158. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6159. };
  6160. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6161. if (!ignoreParentClass) {
  6162. _super.prototype._updateCache.call(this);
  6163. }
  6164. var lockedTargetPosition = this._getLockedTargetPosition();
  6165. if (!lockedTargetPosition) {
  6166. this._cache.lockedTarget = null;
  6167. } else {
  6168. if (!this._cache.lockedTarget) {
  6169. this._cache.lockedTarget = lockedTargetPosition.clone();
  6170. } else {
  6171. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6172. }
  6173. }
  6174. this._cache.rotation.copyFrom(this.rotation);
  6175. };
  6176. // Synchronized
  6177. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6178. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6179. return false;
  6180. }
  6181. var lockedTargetPosition = this._getLockedTargetPosition();
  6182. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6183. };
  6184. // Methods
  6185. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6186. var engine = this.getEngine();
  6187. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6188. };
  6189. // Target
  6190. TargetCamera.prototype.setTarget = function (target) {
  6191. this.upVector.normalize();
  6192. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6193. this._camMatrix.invert();
  6194. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6195. var vDir = target.subtract(this.position);
  6196. if (vDir.x >= 0.0) {
  6197. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6198. } else {
  6199. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6200. }
  6201. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6202. if (isNaN(this.rotation.x)) {
  6203. this.rotation.x = 0;
  6204. }
  6205. if (isNaN(this.rotation.y)) {
  6206. this.rotation.y = 0;
  6207. }
  6208. if (isNaN(this.rotation.z)) {
  6209. this.rotation.z = 0;
  6210. }
  6211. };
  6212. TargetCamera.prototype.getTarget = function () {
  6213. return this._currentTarget;
  6214. };
  6215. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6216. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6217. };
  6218. TargetCamera.prototype._updatePosition = function () {
  6219. this.position.addInPlace(this.cameraDirection);
  6220. };
  6221. TargetCamera.prototype._update = function () {
  6222. var needToMove = this._decideIfNeedsToMove();
  6223. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6224. // Move
  6225. if (needToMove) {
  6226. this._updatePosition();
  6227. }
  6228. // Rotate
  6229. if (needToRotate) {
  6230. this.rotation.x += this.cameraRotation.x;
  6231. this.rotation.y += this.cameraRotation.y;
  6232. if (!this.noRotationConstraint) {
  6233. var limit = (Math.PI / 2) * 0.95;
  6234. if (this.rotation.x > limit)
  6235. this.rotation.x = limit;
  6236. if (this.rotation.x < -limit)
  6237. this.rotation.x = -limit;
  6238. }
  6239. }
  6240. // Inertia
  6241. if (needToMove) {
  6242. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6243. this.cameraDirection.x = 0;
  6244. }
  6245. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6246. this.cameraDirection.y = 0;
  6247. }
  6248. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6249. this.cameraDirection.z = 0;
  6250. }
  6251. this.cameraDirection.scaleInPlace(this.inertia);
  6252. }
  6253. if (needToRotate) {
  6254. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6255. this.cameraRotation.x = 0;
  6256. }
  6257. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6258. this.cameraRotation.y = 0;
  6259. }
  6260. this.cameraRotation.scaleInPlace(this.inertia);
  6261. }
  6262. };
  6263. TargetCamera.prototype._getViewMatrix = function () {
  6264. if (!this.lockedTarget) {
  6265. // Compute
  6266. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6267. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6268. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6269. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6270. this._lookAtTemp.invert();
  6271. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6272. } else {
  6273. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6274. }
  6275. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6276. // Computing target and final matrix
  6277. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6278. } else {
  6279. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6280. }
  6281. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6282. return this._viewMatrix;
  6283. };
  6284. return TargetCamera;
  6285. })(BABYLON.Camera);
  6286. BABYLON.TargetCamera = TargetCamera;
  6287. })(BABYLON || (BABYLON = {}));
  6288. //# sourceMappingURL=babylon.targetCamera.js.map
  6289. var BABYLON;
  6290. (function (BABYLON) {
  6291. var FollowCamera = (function (_super) {
  6292. __extends(FollowCamera, _super);
  6293. function FollowCamera(name, position, scene) {
  6294. _super.call(this, name, position, scene);
  6295. this.radius = 12;
  6296. this.rotationOffset = 0;
  6297. this.heightOffset = 4;
  6298. this.cameraAcceleration = 0.05;
  6299. this.maxCameraSpeed = 20;
  6300. }
  6301. FollowCamera.prototype.getRadians = function (degrees) {
  6302. return degrees * Math.PI / 180;
  6303. };
  6304. FollowCamera.prototype.follow = function (cameraTarget) {
  6305. if (!cameraTarget)
  6306. return;
  6307. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6308. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6309. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6310. var dx = targetX - this.position.x;
  6311. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6312. var dz = (targetZ) - this.position.z;
  6313. var vx = dx * this.cameraAcceleration * 2;
  6314. var vy = dy * this.cameraAcceleration;
  6315. var vz = dz * this.cameraAcceleration * 2;
  6316. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6317. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6318. }
  6319. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6320. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6321. }
  6322. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6323. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6324. }
  6325. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6326. this.setTarget(cameraTarget.position);
  6327. };
  6328. FollowCamera.prototype._update = function () {
  6329. _super.prototype._update.call(this);
  6330. this.follow(this.target);
  6331. };
  6332. return FollowCamera;
  6333. })(BABYLON.TargetCamera);
  6334. BABYLON.FollowCamera = FollowCamera;
  6335. })(BABYLON || (BABYLON = {}));
  6336. //# sourceMappingURL=babylon.followCamera.js.map
  6337. var BABYLON;
  6338. (function (BABYLON) {
  6339. var FreeCamera = (function (_super) {
  6340. __extends(FreeCamera, _super);
  6341. function FreeCamera(name, position, scene) {
  6342. _super.call(this, name, position, scene);
  6343. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6344. this.keysUp = [38];
  6345. this.keysDown = [40];
  6346. this.keysLeft = [37];
  6347. this.keysRight = [39];
  6348. this.checkCollisions = false;
  6349. this.applyGravity = false;
  6350. this.angularSensibility = 2000.0;
  6351. this._keys = [];
  6352. this._collider = new BABYLON.Collider();
  6353. this._needMoveForGravity = true;
  6354. this._oldPosition = BABYLON.Vector3.Zero();
  6355. this._diffPosition = BABYLON.Vector3.Zero();
  6356. this._newPosition = BABYLON.Vector3.Zero();
  6357. }
  6358. // Controls
  6359. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6360. var _this = this;
  6361. var previousPosition;
  6362. var engine = this.getEngine();
  6363. if (this._attachedElement) {
  6364. return;
  6365. }
  6366. this._attachedElement = element;
  6367. if (this._onMouseDown === undefined) {
  6368. this._onMouseDown = function (evt) {
  6369. previousPosition = {
  6370. x: evt.clientX,
  6371. y: evt.clientY
  6372. };
  6373. if (!noPreventDefault) {
  6374. evt.preventDefault();
  6375. }
  6376. };
  6377. this._onMouseUp = function (evt) {
  6378. previousPosition = null;
  6379. if (!noPreventDefault) {
  6380. evt.preventDefault();
  6381. }
  6382. };
  6383. this._onMouseOut = function (evt) {
  6384. previousPosition = null;
  6385. _this._keys = [];
  6386. if (!noPreventDefault) {
  6387. evt.preventDefault();
  6388. }
  6389. };
  6390. this._onMouseMove = function (evt) {
  6391. if (!previousPosition && !engine.isPointerLock) {
  6392. return;
  6393. }
  6394. var offsetX;
  6395. var offsetY;
  6396. if (!engine.isPointerLock) {
  6397. offsetX = evt.clientX - previousPosition.x;
  6398. offsetY = evt.clientY - previousPosition.y;
  6399. } else {
  6400. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6401. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6402. }
  6403. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6404. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6405. previousPosition = {
  6406. x: evt.clientX,
  6407. y: evt.clientY
  6408. };
  6409. if (!noPreventDefault) {
  6410. evt.preventDefault();
  6411. }
  6412. };
  6413. this._onKeyDown = function (evt) {
  6414. 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) {
  6415. var index = _this._keys.indexOf(evt.keyCode);
  6416. if (index === -1) {
  6417. _this._keys.push(evt.keyCode);
  6418. }
  6419. if (!noPreventDefault) {
  6420. evt.preventDefault();
  6421. }
  6422. }
  6423. };
  6424. this._onKeyUp = function (evt) {
  6425. 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) {
  6426. var index = _this._keys.indexOf(evt.keyCode);
  6427. if (index >= 0) {
  6428. _this._keys.splice(index, 1);
  6429. }
  6430. if (!noPreventDefault) {
  6431. evt.preventDefault();
  6432. }
  6433. }
  6434. };
  6435. this._onLostFocus = function () {
  6436. _this._keys = [];
  6437. };
  6438. this._reset = function () {
  6439. _this._keys = [];
  6440. previousPosition = null;
  6441. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6442. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6443. };
  6444. }
  6445. element.addEventListener("mousedown", this._onMouseDown, false);
  6446. element.addEventListener("mouseup", this._onMouseUp, false);
  6447. element.addEventListener("mouseout", this._onMouseOut, false);
  6448. element.addEventListener("mousemove", this._onMouseMove, false);
  6449. BABYLON.Tools.RegisterTopRootEvents([
  6450. { name: "keydown", handler: this._onKeyDown },
  6451. { name: "keyup", handler: this._onKeyUp },
  6452. { name: "blur", handler: this._onLostFocus }
  6453. ]);
  6454. };
  6455. FreeCamera.prototype.detachControl = function (element) {
  6456. if (this._attachedElement != element) {
  6457. return;
  6458. }
  6459. element.removeEventListener("mousedown", this._onMouseDown);
  6460. element.removeEventListener("mouseup", this._onMouseUp);
  6461. element.removeEventListener("mouseout", this._onMouseOut);
  6462. element.removeEventListener("mousemove", this._onMouseMove);
  6463. BABYLON.Tools.UnregisterTopRootEvents([
  6464. { name: "keydown", handler: this._onKeyDown },
  6465. { name: "keyup", handler: this._onKeyUp },
  6466. { name: "blur", handler: this._onLostFocus }
  6467. ]);
  6468. this._attachedElement = null;
  6469. if (this._reset) {
  6470. this._reset();
  6471. }
  6472. };
  6473. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6474. var globalPosition;
  6475. if (this.parent) {
  6476. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6477. } else {
  6478. globalPosition = this.position;
  6479. }
  6480. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6481. this._collider.radius = this.ellipsoid;
  6482. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6483. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6484. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6485. this.position.addInPlace(this._diffPosition);
  6486. if (this.onCollide) {
  6487. this.onCollide(this._collider.collidedMesh);
  6488. }
  6489. }
  6490. };
  6491. FreeCamera.prototype._checkInputs = function () {
  6492. if (!this._localDirection) {
  6493. this._localDirection = BABYLON.Vector3.Zero();
  6494. this._transformedDirection = BABYLON.Vector3.Zero();
  6495. }
  6496. for (var index = 0; index < this._keys.length; index++) {
  6497. var keyCode = this._keys[index];
  6498. var speed = this._computeLocalCameraSpeed();
  6499. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6500. this._localDirection.copyFromFloats(-speed, 0, 0);
  6501. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6502. this._localDirection.copyFromFloats(0, 0, speed);
  6503. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6504. this._localDirection.copyFromFloats(speed, 0, 0);
  6505. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6506. this._localDirection.copyFromFloats(0, 0, -speed);
  6507. }
  6508. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6509. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6510. this.cameraDirection.addInPlace(this._transformedDirection);
  6511. }
  6512. };
  6513. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6514. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6515. };
  6516. FreeCamera.prototype._updatePosition = function () {
  6517. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6518. this._collideWithWorld(this.cameraDirection);
  6519. if (this.applyGravity) {
  6520. var oldPosition = this.position;
  6521. this._collideWithWorld(this.getScene().gravity);
  6522. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6523. }
  6524. } else {
  6525. this.position.addInPlace(this.cameraDirection);
  6526. }
  6527. };
  6528. FreeCamera.prototype._update = function () {
  6529. this._checkInputs();
  6530. _super.prototype._update.call(this);
  6531. };
  6532. return FreeCamera;
  6533. })(BABYLON.TargetCamera);
  6534. BABYLON.FreeCamera = FreeCamera;
  6535. })(BABYLON || (BABYLON = {}));
  6536. //# sourceMappingURL=babylon.freeCamera.js.map
  6537. var BABYLON;
  6538. (function (BABYLON) {
  6539. // We're mainly based on the logic defined into the FreeCamera code
  6540. var TouchCamera = (function (_super) {
  6541. __extends(TouchCamera, _super);
  6542. function TouchCamera(name, position, scene) {
  6543. _super.call(this, name, position, scene);
  6544. this._offsetX = null;
  6545. this._offsetY = null;
  6546. this._pointerCount = 0;
  6547. this._pointerPressed = [];
  6548. this.angularSensibility = 200000.0;
  6549. this.moveSensibility = 500.0;
  6550. }
  6551. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6552. var _this = this;
  6553. var previousPosition;
  6554. if (this._attachedCanvas) {
  6555. return;
  6556. }
  6557. this._attachedCanvas = canvas;
  6558. if (this._onPointerDown === undefined) {
  6559. this._onPointerDown = function (evt) {
  6560. if (!noPreventDefault) {
  6561. evt.preventDefault();
  6562. }
  6563. _this._pointerPressed.push(evt.pointerId);
  6564. if (_this._pointerPressed.length !== 1) {
  6565. return;
  6566. }
  6567. previousPosition = {
  6568. x: evt.clientX,
  6569. y: evt.clientY
  6570. };
  6571. };
  6572. this._onPointerUp = function (evt) {
  6573. if (!noPreventDefault) {
  6574. evt.preventDefault();
  6575. }
  6576. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6577. if (index === -1) {
  6578. return;
  6579. }
  6580. _this._pointerPressed.splice(index, 1);
  6581. if (index != 0) {
  6582. return;
  6583. }
  6584. previousPosition = null;
  6585. _this._offsetX = null;
  6586. _this._offsetY = null;
  6587. };
  6588. this._onPointerMove = function (evt) {
  6589. if (!noPreventDefault) {
  6590. evt.preventDefault();
  6591. }
  6592. if (!previousPosition) {
  6593. return;
  6594. }
  6595. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6596. if (index != 0) {
  6597. return;
  6598. }
  6599. _this._offsetX = evt.clientX - previousPosition.x;
  6600. _this._offsetY = -(evt.clientY - previousPosition.y);
  6601. };
  6602. this._onLostFocus = function () {
  6603. _this._offsetX = null;
  6604. _this._offsetY = null;
  6605. };
  6606. }
  6607. canvas.addEventListener("pointerdown", this._onPointerDown);
  6608. canvas.addEventListener("pointerup", this._onPointerUp);
  6609. canvas.addEventListener("pointerout", this._onPointerUp);
  6610. canvas.addEventListener("pointermove", this._onPointerMove);
  6611. BABYLON.Tools.RegisterTopRootEvents([
  6612. { name: "blur", handler: this._onLostFocus }
  6613. ]);
  6614. };
  6615. TouchCamera.prototype.detachControl = function (canvas) {
  6616. if (this._attachedCanvas != canvas) {
  6617. return;
  6618. }
  6619. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6620. canvas.removeEventListener("pointerup", this._onPointerUp);
  6621. canvas.removeEventListener("pointerout", this._onPointerUp);
  6622. canvas.removeEventListener("pointermove", this._onPointerMove);
  6623. BABYLON.Tools.UnregisterTopRootEvents([
  6624. { name: "blur", handler: this._onLostFocus }
  6625. ]);
  6626. this._attachedCanvas = null;
  6627. };
  6628. TouchCamera.prototype._checkInputs = function () {
  6629. if (!this._offsetX) {
  6630. return;
  6631. }
  6632. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6633. if (this._pointerPressed.length > 1) {
  6634. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6635. } else {
  6636. var speed = this._computeLocalCameraSpeed();
  6637. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6638. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6639. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6640. }
  6641. };
  6642. return TouchCamera;
  6643. })(BABYLON.FreeCamera);
  6644. BABYLON.TouchCamera = TouchCamera;
  6645. })(BABYLON || (BABYLON = {}));
  6646. //# sourceMappingURL=babylon.touchCamera.js.map
  6647. var BABYLON;
  6648. (function (BABYLON) {
  6649. // We're mainly based on the logic defined into the FreeCamera code
  6650. var DeviceOrientationCamera = (function (_super) {
  6651. __extends(DeviceOrientationCamera, _super);
  6652. function DeviceOrientationCamera(name, position, scene) {
  6653. var _this = this;
  6654. _super.call(this, name, position, scene);
  6655. this._offsetX = null;
  6656. this._offsetY = null;
  6657. this._orientationGamma = 0;
  6658. this._orientationBeta = 0;
  6659. this._initialOrientationGamma = 0;
  6660. this._initialOrientationBeta = 0;
  6661. this.angularSensibility = 10000.0;
  6662. this.moveSensibility = 50.0;
  6663. window.addEventListener("resize", function () {
  6664. _this._initialOrientationGamma = null;
  6665. }, false);
  6666. }
  6667. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6668. var _this = this;
  6669. if (this._attachedCanvas) {
  6670. return;
  6671. }
  6672. this._attachedCanvas = canvas;
  6673. if (!this._orientationChanged) {
  6674. this._orientationChanged = function (evt) {
  6675. if (!_this._initialOrientationGamma) {
  6676. _this._initialOrientationGamma = evt.gamma;
  6677. _this._initialOrientationBeta = evt.beta;
  6678. }
  6679. _this._orientationGamma = evt.gamma;
  6680. _this._orientationBeta = evt.beta;
  6681. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6682. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6683. };
  6684. }
  6685. window.addEventListener("deviceorientation", this._orientationChanged);
  6686. };
  6687. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6688. if (this._attachedCanvas != canvas) {
  6689. return;
  6690. }
  6691. window.removeEventListener("deviceorientation", this._orientationChanged);
  6692. this._attachedCanvas = null;
  6693. this._orientationGamma = 0;
  6694. this._orientationBeta = 0;
  6695. this._initialOrientationGamma = 0;
  6696. this._initialOrientationBeta = 0;
  6697. };
  6698. DeviceOrientationCamera.prototype._checkInputs = function () {
  6699. if (!this._offsetX) {
  6700. return;
  6701. }
  6702. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6703. var speed = this._computeLocalCameraSpeed();
  6704. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6705. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6706. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6707. };
  6708. return DeviceOrientationCamera;
  6709. })(BABYLON.FreeCamera);
  6710. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6711. })(BABYLON || (BABYLON = {}));
  6712. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6713. var BABYLON;
  6714. (function (BABYLON) {
  6715. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6716. var ArcRotateCamera = (function (_super) {
  6717. __extends(ArcRotateCamera, _super);
  6718. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6719. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6720. this.alpha = alpha;
  6721. this.beta = beta;
  6722. this.radius = radius;
  6723. this.target = target;
  6724. this.inertialAlphaOffset = 0;
  6725. this.inertialBetaOffset = 0;
  6726. this.inertialRadiusOffset = 0;
  6727. this.lowerAlphaLimit = null;
  6728. this.upperAlphaLimit = null;
  6729. this.lowerBetaLimit = 0.01;
  6730. this.upperBetaLimit = Math.PI;
  6731. this.lowerRadiusLimit = null;
  6732. this.upperRadiusLimit = null;
  6733. this.angularSensibility = 1000.0;
  6734. this.wheelPrecision = 3.0;
  6735. this.keysUp = [38];
  6736. this.keysDown = [40];
  6737. this.keysLeft = [37];
  6738. this.keysRight = [39];
  6739. this.zoomOnFactor = 1;
  6740. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6741. this._keys = [];
  6742. this._viewMatrix = new BABYLON.Matrix();
  6743. this.checkCollisions = false;
  6744. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6745. this._collider = new BABYLON.Collider();
  6746. this._previousPosition = BABYLON.Vector3.Zero();
  6747. this._collisionVelocity = BABYLON.Vector3.Zero();
  6748. this._newPosition = BABYLON.Vector3.Zero();
  6749. // Pinch
  6750. // value for pinch step scaling
  6751. // set to 20 by default
  6752. this.pinchPrecision = 20;
  6753. this.getViewMatrix();
  6754. }
  6755. ArcRotateCamera.prototype._getTargetPosition = function () {
  6756. return this.target.position || this.target;
  6757. };
  6758. // Cache
  6759. ArcRotateCamera.prototype._initCache = function () {
  6760. _super.prototype._initCache.call(this);
  6761. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6762. this._cache.alpha = undefined;
  6763. this._cache.beta = undefined;
  6764. this._cache.radius = undefined;
  6765. this._cache.targetScreenOffset = undefined;
  6766. };
  6767. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6768. if (!ignoreParentClass) {
  6769. _super.prototype._updateCache.call(this);
  6770. }
  6771. this._cache.target.copyFrom(this._getTargetPosition());
  6772. this._cache.alpha = this.alpha;
  6773. this._cache.beta = this.beta;
  6774. this._cache.radius = this.radius;
  6775. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6776. };
  6777. // Synchronized
  6778. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6779. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6780. return false;
  6781. 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);
  6782. };
  6783. // Methods
  6784. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6785. var _this = this;
  6786. var previousPosition;
  6787. var pointerId;
  6788. // to know if pinch started
  6789. var pinchStarted = false;
  6790. // two pinch point on X
  6791. // that will use for find if user action is pinch open or pinch close
  6792. var pinchPointX1, pinchPointX2;
  6793. if (this._attachedElement) {
  6794. return;
  6795. }
  6796. this._attachedElement = element;
  6797. var engine = this.getEngine();
  6798. if (this._onPointerDown === undefined) {
  6799. this._onPointerDown = function (evt) {
  6800. if (pointerId) {
  6801. return;
  6802. }
  6803. pointerId = evt.pointerId;
  6804. previousPosition = {
  6805. x: evt.clientX,
  6806. y: evt.clientY
  6807. };
  6808. if (!noPreventDefault) {
  6809. evt.preventDefault();
  6810. }
  6811. };
  6812. this._onPointerUp = function (evt) {
  6813. previousPosition = null;
  6814. pointerId = null;
  6815. if (!noPreventDefault) {
  6816. evt.preventDefault();
  6817. }
  6818. };
  6819. this._onPointerMove = function (evt) {
  6820. if (!previousPosition) {
  6821. return;
  6822. }
  6823. if (pointerId !== evt.pointerId) {
  6824. return;
  6825. }
  6826. // return pinch is started
  6827. if (pinchStarted) {
  6828. return;
  6829. }
  6830. var offsetX = evt.clientX - previousPosition.x;
  6831. var offsetY = evt.clientY - previousPosition.y;
  6832. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6833. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6834. previousPosition = {
  6835. x: evt.clientX,
  6836. y: evt.clientY
  6837. };
  6838. if (!noPreventDefault) {
  6839. evt.preventDefault();
  6840. }
  6841. };
  6842. this._onMouseMove = function (evt) {
  6843. if (!engine.isPointerLock) {
  6844. return;
  6845. }
  6846. // return pinch is started
  6847. if (pinchStarted) {
  6848. return;
  6849. }
  6850. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6851. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6852. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6853. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6854. if (!noPreventDefault) {
  6855. evt.preventDefault();
  6856. }
  6857. };
  6858. this._wheel = function (event) {
  6859. var delta = 0;
  6860. if (event.wheelDelta) {
  6861. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6862. } else if (event.detail) {
  6863. delta = -event.detail / _this.wheelPrecision;
  6864. }
  6865. if (delta)
  6866. _this.inertialRadiusOffset += delta;
  6867. if (event.preventDefault) {
  6868. if (!noPreventDefault) {
  6869. event.preventDefault();
  6870. }
  6871. }
  6872. };
  6873. this._onKeyDown = function (evt) {
  6874. 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) {
  6875. var index = _this._keys.indexOf(evt.keyCode);
  6876. if (index === -1) {
  6877. _this._keys.push(evt.keyCode);
  6878. }
  6879. if (evt.preventDefault) {
  6880. if (!noPreventDefault) {
  6881. evt.preventDefault();
  6882. }
  6883. }
  6884. }
  6885. };
  6886. this._onKeyUp = function (evt) {
  6887. 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) {
  6888. var index = _this._keys.indexOf(evt.keyCode);
  6889. if (index >= 0) {
  6890. _this._keys.splice(index, 1);
  6891. }
  6892. if (evt.preventDefault) {
  6893. if (!noPreventDefault) {
  6894. evt.preventDefault();
  6895. }
  6896. }
  6897. }
  6898. };
  6899. this._onLostFocus = function () {
  6900. _this._keys = [];
  6901. pointerId = null;
  6902. };
  6903. this._onGestureStart = function (e) {
  6904. if (window.MSGesture === undefined) {
  6905. return;
  6906. }
  6907. if (!_this._MSGestureHandler) {
  6908. _this._MSGestureHandler = new MSGesture();
  6909. _this._MSGestureHandler.target = element;
  6910. }
  6911. _this._MSGestureHandler.addPointer(e.pointerId);
  6912. };
  6913. this._onGesture = function (e) {
  6914. _this.radius *= e.scale;
  6915. if (e.preventDefault) {
  6916. if (!noPreventDefault) {
  6917. e.stopPropagation();
  6918. e.preventDefault();
  6919. }
  6920. }
  6921. };
  6922. this._reset = function () {
  6923. _this._keys = [];
  6924. _this.inertialAlphaOffset = 0;
  6925. _this.inertialBetaOffset = 0;
  6926. _this.inertialRadiusOffset = 0;
  6927. previousPosition = null;
  6928. pointerId = null;
  6929. };
  6930. this._touchStart = function (event) {
  6931. if (event.touches.length === 2) {
  6932. //-- start pinch if two fingers on the screen
  6933. pinchStarted = true;
  6934. _this._pinchStart(event);
  6935. }
  6936. };
  6937. this._touchMove = function (event) {
  6938. if (pinchStarted) {
  6939. //-- make scaling
  6940. _this._pinchMove(event);
  6941. }
  6942. };
  6943. this._touchEnd = function (event) {
  6944. if (pinchStarted) {
  6945. //-- end of pinch
  6946. _this._pinchEnd(event);
  6947. }
  6948. };
  6949. this._pinchStart = function (event) {
  6950. // save origin touch point
  6951. pinchPointX1 = event.touches[0].clientX;
  6952. pinchPointX2 = event.touches[1].clientX;
  6953. // block the camera
  6954. // if not it rotate around target during pinch
  6955. pinchStarted = true;
  6956. };
  6957. this._pinchMove = function (event) {
  6958. // variable for new camera's radius
  6959. var delta = 0;
  6960. // variables to know if pinch open or pinch close
  6961. var direction = 1;
  6962. var distanceXOrigine, distanceXNow;
  6963. if (event.touches.length !== 2)
  6964. return;
  6965. // calculate absolute distances of the two fingers
  6966. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6967. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6968. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6969. if (distanceXNow < distanceXOrigine) {
  6970. direction = -1;
  6971. }
  6972. // calculate new radius
  6973. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6974. // set new radius
  6975. _this.inertialRadiusOffset -= delta;
  6976. // save origin touch point
  6977. pinchPointX1 = event.touches[0].clientX;
  6978. pinchPointX2 = event.touches[1].clientX;
  6979. };
  6980. this._pinchEnd = function (event) {
  6981. // cancel pinch and deblock camera rotation
  6982. pinchStarted = false;
  6983. };
  6984. }
  6985. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6986. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6987. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6988. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6989. element.addEventListener("mousemove", this._onMouseMove, false);
  6990. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6991. element.addEventListener("MSGestureChange", this._onGesture, false);
  6992. element.addEventListener('mousewheel', this._wheel, false);
  6993. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6994. // pinch
  6995. element.addEventListener('touchstart', this._touchStart, false);
  6996. element.addEventListener('touchmove', this._touchMove, false);
  6997. element.addEventListener('touchend', this._touchEnd, false);
  6998. BABYLON.Tools.RegisterTopRootEvents([
  6999. { name: "keydown", handler: this._onKeyDown },
  7000. { name: "keyup", handler: this._onKeyUp },
  7001. { name: "blur", handler: this._onLostFocus }
  7002. ]);
  7003. };
  7004. ArcRotateCamera.prototype.detachControl = function (element) {
  7005. if (this._attachedElement != element) {
  7006. return;
  7007. }
  7008. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7009. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7010. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7011. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7012. element.removeEventListener("mousemove", this._onMouseMove);
  7013. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7014. element.removeEventListener("MSGestureChange", this._onGesture);
  7015. element.removeEventListener('mousewheel', this._wheel);
  7016. element.removeEventListener('DOMMouseScroll', this._wheel);
  7017. // pinch
  7018. element.removeEventListener('touchstart', this._touchStart);
  7019. element.removeEventListener('touchmove', this._touchMove);
  7020. element.removeEventListener('touchend', this._touchEnd);
  7021. BABYLON.Tools.UnregisterTopRootEvents([
  7022. { name: "keydown", handler: this._onKeyDown },
  7023. { name: "keyup", handler: this._onKeyUp },
  7024. { name: "blur", handler: this._onLostFocus }
  7025. ]);
  7026. this._MSGestureHandler = null;
  7027. this._attachedElement = null;
  7028. if (this._reset) {
  7029. this._reset();
  7030. }
  7031. };
  7032. ArcRotateCamera.prototype._update = function () {
  7033. for (var index = 0; index < this._keys.length; index++) {
  7034. var keyCode = this._keys[index];
  7035. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7036. this.inertialAlphaOffset -= 0.01;
  7037. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7038. this.inertialBetaOffset -= 0.01;
  7039. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7040. this.inertialAlphaOffset += 0.01;
  7041. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7042. this.inertialBetaOffset += 0.01;
  7043. }
  7044. }
  7045. // Inertia
  7046. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7047. this.alpha += this.inertialAlphaOffset;
  7048. this.beta += this.inertialBetaOffset;
  7049. this.radius -= this.inertialRadiusOffset;
  7050. this.inertialAlphaOffset *= this.inertia;
  7051. this.inertialBetaOffset *= this.inertia;
  7052. this.inertialRadiusOffset *= this.inertia;
  7053. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7054. this.inertialAlphaOffset = 0;
  7055. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7056. this.inertialBetaOffset = 0;
  7057. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7058. this.inertialRadiusOffset = 0;
  7059. }
  7060. // Limits
  7061. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7062. this.alpha = this.lowerAlphaLimit;
  7063. }
  7064. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7065. this.alpha = this.upperAlphaLimit;
  7066. }
  7067. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7068. this.beta = this.lowerBetaLimit;
  7069. }
  7070. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7071. this.beta = this.upperBetaLimit;
  7072. }
  7073. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7074. this.radius = this.lowerRadiusLimit;
  7075. }
  7076. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7077. this.radius = this.upperRadiusLimit;
  7078. }
  7079. };
  7080. ArcRotateCamera.prototype.setPosition = function (position) {
  7081. var radiusv3 = position.subtract(this._getTargetPosition());
  7082. this.radius = radiusv3.length();
  7083. // Alpha
  7084. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7085. if (radiusv3.z < 0) {
  7086. this.alpha = 2 * Math.PI - this.alpha;
  7087. }
  7088. // Beta
  7089. this.beta = Math.acos(radiusv3.y / this.radius);
  7090. };
  7091. ArcRotateCamera.prototype._getViewMatrix = function () {
  7092. // Compute
  7093. var cosa = Math.cos(this.alpha);
  7094. var sina = Math.sin(this.alpha);
  7095. var cosb = Math.cos(this.beta);
  7096. var sinb = Math.sin(this.beta);
  7097. var target = this._getTargetPosition();
  7098. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7099. if (this.checkCollisions) {
  7100. this._collider.radius = this.collisionRadius;
  7101. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7102. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7103. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7104. this.position.copyFrom(this._previousPosition);
  7105. this.alpha = this._previousAlpha;
  7106. this.beta = this._previousBeta;
  7107. this.radius = this._previousRadius;
  7108. if (this.onCollide) {
  7109. this.onCollide(this._collider.collidedMesh);
  7110. }
  7111. }
  7112. }
  7113. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7114. this._previousAlpha = this.alpha;
  7115. this._previousBeta = this.beta;
  7116. this._previousRadius = this.radius;
  7117. this._previousPosition.copyFrom(this.position);
  7118. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7119. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7120. return this._viewMatrix;
  7121. };
  7122. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7123. meshes = meshes || this.getScene().meshes;
  7124. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7125. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7126. this.radius = distance * this.zoomOnFactor;
  7127. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7128. };
  7129. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7130. var meshesOrMinMaxVector;
  7131. var distance;
  7132. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7133. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7134. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7135. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7136. } else {
  7137. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7138. distance = meshesOrMinMaxVectorAndDistance.distance;
  7139. }
  7140. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7141. this.maxZ = distance * 2;
  7142. };
  7143. return ArcRotateCamera;
  7144. })(BABYLON.Camera);
  7145. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7146. })(BABYLON || (BABYLON = {}));
  7147. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7148. var BABYLON;
  7149. (function (BABYLON) {
  7150. var Scene = (function () {
  7151. // Constructor
  7152. function Scene(engine) {
  7153. // Members
  7154. this.autoClear = true;
  7155. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7156. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7157. this.forceWireframe = false;
  7158. this.forcePointsCloud = false;
  7159. this.forceShowBoundingBoxes = false;
  7160. this.animationsEnabled = true;
  7161. this.cameraToUseForPointers = null;
  7162. // Fog
  7163. this.fogEnabled = true;
  7164. this.fogMode = Scene.FOGMODE_NONE;
  7165. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7166. this.fogDensity = 0.1;
  7167. this.fogStart = 0;
  7168. this.fogEnd = 1000.0;
  7169. // Lights
  7170. this.shadowsEnabled = true;
  7171. this.lightsEnabled = true;
  7172. this.lights = new Array();
  7173. // Cameras
  7174. this.cameras = new Array();
  7175. this.activeCameras = new Array();
  7176. // Meshes
  7177. this.meshes = new Array();
  7178. // Geometries
  7179. this._geometries = new Array();
  7180. this.materials = new Array();
  7181. this.multiMaterials = new Array();
  7182. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7183. // Textures
  7184. this.texturesEnabled = true;
  7185. this.textures = new Array();
  7186. // Particles
  7187. this.particlesEnabled = true;
  7188. this.particleSystems = new Array();
  7189. // Sprites
  7190. this.spriteManagers = new Array();
  7191. // Layers
  7192. this.layers = new Array();
  7193. // Skeletons
  7194. this.skeletonsEnabled = true;
  7195. this.skeletons = new Array();
  7196. // Lens flares
  7197. this.lensFlaresEnabled = true;
  7198. this.lensFlareSystems = new Array();
  7199. // Collisions
  7200. this.collisionsEnabled = true;
  7201. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7202. // Postprocesses
  7203. this.postProcessesEnabled = true;
  7204. // Customs render targets
  7205. this.renderTargetsEnabled = true;
  7206. this.customRenderTargets = new Array();
  7207. // Imported meshes
  7208. this.importedMeshesFiles = new Array();
  7209. this._actionManagers = new Array();
  7210. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7211. // Procedural textures
  7212. this.proceduralTexturesEnabled = true;
  7213. this._proceduralTextures = new Array();
  7214. this.soundTracks = new Array();
  7215. this._totalVertices = 0;
  7216. this._activeVertices = 0;
  7217. this._activeParticles = 0;
  7218. this._lastFrameDuration = 0;
  7219. this._evaluateActiveMeshesDuration = 0;
  7220. this._renderTargetsDuration = 0;
  7221. this._particlesDuration = 0;
  7222. this._renderDuration = 0;
  7223. this._spritesDuration = 0;
  7224. this._animationRatio = 0;
  7225. this._renderId = 0;
  7226. this._executeWhenReadyTimeoutId = -1;
  7227. this._toBeDisposed = new BABYLON.SmartArray(256);
  7228. this._onReadyCallbacks = new Array();
  7229. this._pendingData = [];
  7230. this._onBeforeRenderCallbacks = new Array();
  7231. this._onAfterRenderCallbacks = new Array();
  7232. this._activeMeshes = new BABYLON.SmartArray(256);
  7233. this._processedMaterials = new BABYLON.SmartArray(256);
  7234. this._renderTargets = new BABYLON.SmartArray(256);
  7235. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7236. this._activeSkeletons = new BABYLON.SmartArray(32);
  7237. this._activeBones = 0;
  7238. this._activeAnimatables = new Array();
  7239. this._transformMatrix = BABYLON.Matrix.Zero();
  7240. this._scaledPosition = BABYLON.Vector3.Zero();
  7241. this._scaledVelocity = BABYLON.Vector3.Zero();
  7242. this._engine = engine;
  7243. engine.scenes.push(this);
  7244. this._renderingManager = new BABYLON.RenderingManager(this);
  7245. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7246. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7247. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7248. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7249. this.attachControl();
  7250. this._debugLayer = new BABYLON.DebugLayer(this);
  7251. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7252. }
  7253. Object.defineProperty(Scene.prototype, "debugLayer", {
  7254. // Properties
  7255. get: function () {
  7256. return this._debugLayer;
  7257. },
  7258. enumerable: true,
  7259. configurable: true
  7260. });
  7261. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7262. get: function () {
  7263. return this._meshUnderPointer;
  7264. },
  7265. enumerable: true,
  7266. configurable: true
  7267. });
  7268. Object.defineProperty(Scene.prototype, "pointerX", {
  7269. get: function () {
  7270. return this._pointerX;
  7271. },
  7272. enumerable: true,
  7273. configurable: true
  7274. });
  7275. Object.defineProperty(Scene.prototype, "pointerY", {
  7276. get: function () {
  7277. return this._pointerY;
  7278. },
  7279. enumerable: true,
  7280. configurable: true
  7281. });
  7282. Scene.prototype.getCachedMaterial = function () {
  7283. return this._cachedMaterial;
  7284. };
  7285. Scene.prototype.getBoundingBoxRenderer = function () {
  7286. return this._boundingBoxRenderer;
  7287. };
  7288. Scene.prototype.getOutlineRenderer = function () {
  7289. return this._outlineRenderer;
  7290. };
  7291. Scene.prototype.getEngine = function () {
  7292. return this._engine;
  7293. };
  7294. Scene.prototype.getTotalVertices = function () {
  7295. return this._totalVertices;
  7296. };
  7297. Scene.prototype.getActiveVertices = function () {
  7298. return this._activeVertices;
  7299. };
  7300. Scene.prototype.getActiveParticles = function () {
  7301. return this._activeParticles;
  7302. };
  7303. Scene.prototype.getActiveBones = function () {
  7304. return this._activeBones;
  7305. };
  7306. // Stats
  7307. Scene.prototype.getLastFrameDuration = function () {
  7308. return this._lastFrameDuration;
  7309. };
  7310. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7311. return this._evaluateActiveMeshesDuration;
  7312. };
  7313. Scene.prototype.getActiveMeshes = function () {
  7314. return this._activeMeshes;
  7315. };
  7316. Scene.prototype.getRenderTargetsDuration = function () {
  7317. return this._renderTargetsDuration;
  7318. };
  7319. Scene.prototype.getRenderDuration = function () {
  7320. return this._renderDuration;
  7321. };
  7322. Scene.prototype.getParticlesDuration = function () {
  7323. return this._particlesDuration;
  7324. };
  7325. Scene.prototype.getSpritesDuration = function () {
  7326. return this._spritesDuration;
  7327. };
  7328. Scene.prototype.getAnimationRatio = function () {
  7329. return this._animationRatio;
  7330. };
  7331. Scene.prototype.getRenderId = function () {
  7332. return this._renderId;
  7333. };
  7334. Scene.prototype._updatePointerPosition = function (evt) {
  7335. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7336. this._pointerX = evt.clientX - canvasRect.left;
  7337. this._pointerY = evt.clientY - canvasRect.top;
  7338. if (this.cameraToUseForPointers) {
  7339. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7340. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7341. }
  7342. };
  7343. // Pointers handling
  7344. Scene.prototype.attachControl = function () {
  7345. var _this = this;
  7346. this._onPointerMove = function (evt) {
  7347. var canvas = _this._engine.getRenderingCanvas();
  7348. _this._updatePointerPosition(evt);
  7349. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7350. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7351. }, false, _this.cameraToUseForPointers);
  7352. if (pickResult.hit) {
  7353. _this._meshUnderPointer = pickResult.pickedMesh;
  7354. _this.setPointerOverMesh(pickResult.pickedMesh);
  7355. canvas.style.cursor = "pointer";
  7356. } else {
  7357. _this.setPointerOverMesh(null);
  7358. canvas.style.cursor = "";
  7359. _this._meshUnderPointer = null;
  7360. }
  7361. };
  7362. this._onPointerDown = function (evt) {
  7363. var predicate = null;
  7364. if (!_this.onPointerDown) {
  7365. predicate = function (mesh) {
  7366. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7367. };
  7368. }
  7369. _this._updatePointerPosition(evt);
  7370. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7371. if (pickResult.hit) {
  7372. if (pickResult.pickedMesh.actionManager) {
  7373. switch (evt.button) {
  7374. case 0:
  7375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7376. break;
  7377. case 1:
  7378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7379. break;
  7380. case 2:
  7381. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7382. break;
  7383. }
  7384. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7385. }
  7386. }
  7387. if (_this.onPointerDown) {
  7388. _this.onPointerDown(evt, pickResult);
  7389. }
  7390. };
  7391. this._onKeyDown = function (evt) {
  7392. if (_this.actionManager) {
  7393. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7394. }
  7395. };
  7396. this._onKeyUp = function (evt) {
  7397. if (_this.actionManager) {
  7398. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7399. }
  7400. };
  7401. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7402. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7403. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7404. window.addEventListener("keydown", this._onKeyDown, false);
  7405. window.addEventListener("keyup", this._onKeyUp, false);
  7406. };
  7407. Scene.prototype.detachControl = function () {
  7408. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7409. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7410. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7411. window.removeEventListener("keydown", this._onKeyDown);
  7412. window.removeEventListener("keyup", this._onKeyUp);
  7413. };
  7414. // Ready
  7415. Scene.prototype.isReady = function () {
  7416. if (this._pendingData.length > 0) {
  7417. return false;
  7418. }
  7419. for (var index = 0; index < this._geometries.length; index++) {
  7420. var geometry = this._geometries[index];
  7421. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7422. return false;
  7423. }
  7424. }
  7425. for (index = 0; index < this.meshes.length; index++) {
  7426. var mesh = this.meshes[index];
  7427. if (!mesh.isReady()) {
  7428. return false;
  7429. }
  7430. var mat = mesh.material;
  7431. if (mat) {
  7432. if (!mat.isReady(mesh)) {
  7433. return false;
  7434. }
  7435. }
  7436. }
  7437. return true;
  7438. };
  7439. Scene.prototype.resetCachedMaterial = function () {
  7440. this._cachedMaterial = null;
  7441. };
  7442. Scene.prototype.registerBeforeRender = function (func) {
  7443. this._onBeforeRenderCallbacks.push(func);
  7444. };
  7445. Scene.prototype.unregisterBeforeRender = function (func) {
  7446. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7447. if (index > -1) {
  7448. this._onBeforeRenderCallbacks.splice(index, 1);
  7449. }
  7450. };
  7451. Scene.prototype.registerAfterRender = function (func) {
  7452. this._onAfterRenderCallbacks.push(func);
  7453. };
  7454. Scene.prototype.unregisterAfterRender = function (func) {
  7455. var index = this._onAfterRenderCallbacks.indexOf(func);
  7456. if (index > -1) {
  7457. this._onAfterRenderCallbacks.splice(index, 1);
  7458. }
  7459. };
  7460. Scene.prototype._addPendingData = function (data) {
  7461. this._pendingData.push(data);
  7462. };
  7463. Scene.prototype._removePendingData = function (data) {
  7464. var index = this._pendingData.indexOf(data);
  7465. if (index !== -1) {
  7466. this._pendingData.splice(index, 1);
  7467. }
  7468. };
  7469. Scene.prototype.getWaitingItemsCount = function () {
  7470. return this._pendingData.length;
  7471. };
  7472. Scene.prototype.executeWhenReady = function (func) {
  7473. var _this = this;
  7474. this._onReadyCallbacks.push(func);
  7475. if (this._executeWhenReadyTimeoutId !== -1) {
  7476. return;
  7477. }
  7478. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7479. _this._checkIsReady();
  7480. }, 150);
  7481. };
  7482. Scene.prototype._checkIsReady = function () {
  7483. var _this = this;
  7484. if (this.isReady()) {
  7485. this._onReadyCallbacks.forEach(function (func) {
  7486. func();
  7487. });
  7488. this._onReadyCallbacks = [];
  7489. this._executeWhenReadyTimeoutId = -1;
  7490. return;
  7491. }
  7492. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7493. _this._checkIsReady();
  7494. }, 150);
  7495. };
  7496. // Animations
  7497. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7498. if (speedRatio === undefined) {
  7499. speedRatio = 1.0;
  7500. }
  7501. this.stopAnimation(target);
  7502. if (!animatable) {
  7503. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7504. }
  7505. // Local animations
  7506. if (target.animations) {
  7507. animatable.appendAnimations(target, target.animations);
  7508. }
  7509. // Children animations
  7510. if (target.getAnimatables) {
  7511. var animatables = target.getAnimatables();
  7512. for (var index = 0; index < animatables.length; index++) {
  7513. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7514. }
  7515. }
  7516. return animatable;
  7517. };
  7518. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7519. if (speedRatio === undefined) {
  7520. speedRatio = 1.0;
  7521. }
  7522. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7523. return animatable;
  7524. };
  7525. Scene.prototype.getAnimatableByTarget = function (target) {
  7526. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7527. if (this._activeAnimatables[index].target === target) {
  7528. return this._activeAnimatables[index];
  7529. }
  7530. }
  7531. return null;
  7532. };
  7533. Scene.prototype.stopAnimation = function (target) {
  7534. var animatable = this.getAnimatableByTarget(target);
  7535. if (animatable) {
  7536. animatable.stop();
  7537. }
  7538. };
  7539. Scene.prototype._animate = function () {
  7540. if (!this.animationsEnabled) {
  7541. return;
  7542. }
  7543. if (!this._animationStartDate) {
  7544. this._animationStartDate = BABYLON.Tools.Now;
  7545. }
  7546. // Getting time
  7547. var now = BABYLON.Tools.Now;
  7548. var delay = now - this._animationStartDate;
  7549. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7550. if (!this._activeAnimatables[index]._animate(delay)) {
  7551. this._activeAnimatables.splice(index, 1);
  7552. index--;
  7553. }
  7554. }
  7555. };
  7556. // Matrix
  7557. Scene.prototype.getViewMatrix = function () {
  7558. return this._viewMatrix;
  7559. };
  7560. Scene.prototype.getProjectionMatrix = function () {
  7561. return this._projectionMatrix;
  7562. };
  7563. Scene.prototype.getTransformMatrix = function () {
  7564. return this._transformMatrix;
  7565. };
  7566. Scene.prototype.setTransformMatrix = function (view, projection) {
  7567. this._viewMatrix = view;
  7568. this._projectionMatrix = projection;
  7569. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7570. };
  7571. // Methods
  7572. Scene.prototype.setActiveCameraByID = function (id) {
  7573. var camera = this.getCameraByID(id);
  7574. if (camera) {
  7575. this.activeCamera = camera;
  7576. return camera;
  7577. }
  7578. return null;
  7579. };
  7580. Scene.prototype.setActiveCameraByName = function (name) {
  7581. var camera = this.getCameraByName(name);
  7582. if (camera) {
  7583. this.activeCamera = camera;
  7584. return camera;
  7585. }
  7586. return null;
  7587. };
  7588. Scene.prototype.getMaterialByID = function (id) {
  7589. for (var index = 0; index < this.materials.length; index++) {
  7590. if (this.materials[index].id === id) {
  7591. return this.materials[index];
  7592. }
  7593. }
  7594. return null;
  7595. };
  7596. Scene.prototype.getMaterialByName = function (name) {
  7597. for (var index = 0; index < this.materials.length; index++) {
  7598. if (this.materials[index].name === name) {
  7599. return this.materials[index];
  7600. }
  7601. }
  7602. return null;
  7603. };
  7604. Scene.prototype.getCameraByID = function (id) {
  7605. for (var index = 0; index < this.cameras.length; index++) {
  7606. if (this.cameras[index].id === id) {
  7607. return this.cameras[index];
  7608. }
  7609. }
  7610. return null;
  7611. };
  7612. Scene.prototype.getCameraByName = function (name) {
  7613. for (var index = 0; index < this.cameras.length; index++) {
  7614. if (this.cameras[index].name === name) {
  7615. return this.cameras[index];
  7616. }
  7617. }
  7618. return null;
  7619. };
  7620. Scene.prototype.getLightByName = function (name) {
  7621. for (var index = 0; index < this.lights.length; index++) {
  7622. if (this.lights[index].name === name) {
  7623. return this.lights[index];
  7624. }
  7625. }
  7626. return null;
  7627. };
  7628. Scene.prototype.getLightByID = function (id) {
  7629. for (var index = 0; index < this.lights.length; index++) {
  7630. if (this.lights[index].id === id) {
  7631. return this.lights[index];
  7632. }
  7633. }
  7634. return null;
  7635. };
  7636. Scene.prototype.getGeometryByID = function (id) {
  7637. for (var index = 0; index < this._geometries.length; index++) {
  7638. if (this._geometries[index].id === id) {
  7639. return this._geometries[index];
  7640. }
  7641. }
  7642. return null;
  7643. };
  7644. Scene.prototype.pushGeometry = function (geometry, force) {
  7645. if (!force && this.getGeometryByID(geometry.id)) {
  7646. return false;
  7647. }
  7648. this._geometries.push(geometry);
  7649. return true;
  7650. };
  7651. Scene.prototype.getGeometries = function () {
  7652. return this._geometries;
  7653. };
  7654. Scene.prototype.getMeshByID = function (id) {
  7655. for (var index = 0; index < this.meshes.length; index++) {
  7656. if (this.meshes[index].id === id) {
  7657. return this.meshes[index];
  7658. }
  7659. }
  7660. return null;
  7661. };
  7662. Scene.prototype.getLastMeshByID = function (id) {
  7663. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7664. if (this.meshes[index].id === id) {
  7665. return this.meshes[index];
  7666. }
  7667. }
  7668. return null;
  7669. };
  7670. Scene.prototype.getLastEntryByID = function (id) {
  7671. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7672. if (this.meshes[index].id === id) {
  7673. return this.meshes[index];
  7674. }
  7675. }
  7676. for (index = this.cameras.length - 1; index >= 0; index--) {
  7677. if (this.cameras[index].id === id) {
  7678. return this.cameras[index];
  7679. }
  7680. }
  7681. for (index = this.lights.length - 1; index >= 0; index--) {
  7682. if (this.lights[index].id === id) {
  7683. return this.lights[index];
  7684. }
  7685. }
  7686. return null;
  7687. };
  7688. Scene.prototype.getNodeByName = function (name) {
  7689. var mesh = this.getMeshByName(name);
  7690. if (mesh) {
  7691. return mesh;
  7692. }
  7693. var light = this.getLightByName(name);
  7694. if (light) {
  7695. return light;
  7696. }
  7697. return this.getCameraByName(name);
  7698. };
  7699. Scene.prototype.getMeshByName = function (name) {
  7700. for (var index = 0; index < this.meshes.length; index++) {
  7701. if (this.meshes[index].name === name) {
  7702. return this.meshes[index];
  7703. }
  7704. }
  7705. return null;
  7706. };
  7707. Scene.prototype.getLastSkeletonByID = function (id) {
  7708. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7709. if (this.skeletons[index].id === id) {
  7710. return this.skeletons[index];
  7711. }
  7712. }
  7713. return null;
  7714. };
  7715. Scene.prototype.getSkeletonById = function (id) {
  7716. for (var index = 0; index < this.skeletons.length; index++) {
  7717. if (this.skeletons[index].id === id) {
  7718. return this.skeletons[index];
  7719. }
  7720. }
  7721. return null;
  7722. };
  7723. Scene.prototype.getSkeletonByName = function (name) {
  7724. for (var index = 0; index < this.skeletons.length; index++) {
  7725. if (this.skeletons[index].name === name) {
  7726. return this.skeletons[index];
  7727. }
  7728. }
  7729. return null;
  7730. };
  7731. Scene.prototype.isActiveMesh = function (mesh) {
  7732. return (this._activeMeshes.indexOf(mesh) !== -1);
  7733. };
  7734. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7735. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7736. var material = subMesh.getMaterial();
  7737. if (mesh.showSubMeshesBoundingBox) {
  7738. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7739. }
  7740. if (material) {
  7741. // Render targets
  7742. if (material.getRenderTargetTextures) {
  7743. if (this._processedMaterials.indexOf(material) === -1) {
  7744. this._processedMaterials.push(material);
  7745. this._renderTargets.concat(material.getRenderTargetTextures());
  7746. }
  7747. }
  7748. // Dispatch
  7749. this._activeVertices += subMesh.indexCount;
  7750. this._renderingManager.dispatch(subMesh);
  7751. }
  7752. }
  7753. };
  7754. Scene.prototype._evaluateActiveMeshes = function () {
  7755. this._activeMeshes.reset();
  7756. this._renderingManager.reset();
  7757. this._processedMaterials.reset();
  7758. this._activeParticleSystems.reset();
  7759. this._activeSkeletons.reset();
  7760. this._boundingBoxRenderer.reset();
  7761. if (!this._frustumPlanes) {
  7762. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7763. } else {
  7764. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7765. }
  7766. // Meshes
  7767. var meshes;
  7768. var len;
  7769. if (this._selectionOctree) {
  7770. var selection = this._selectionOctree.select(this._frustumPlanes);
  7771. meshes = selection.data;
  7772. len = selection.length;
  7773. } else {
  7774. len = this.meshes.length;
  7775. meshes = this.meshes;
  7776. }
  7777. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7778. var mesh = meshes[meshIndex];
  7779. if (mesh.isBlocked) {
  7780. continue;
  7781. }
  7782. this._totalVertices += mesh.getTotalVertices();
  7783. if (!mesh.isReady()) {
  7784. continue;
  7785. }
  7786. mesh.computeWorldMatrix();
  7787. // Intersections
  7788. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7789. this._meshesForIntersections.pushNoDuplicate(mesh);
  7790. }
  7791. // Switch to current LOD
  7792. var meshLOD = mesh.getLOD(this.activeCamera);
  7793. if (!meshLOD) {
  7794. continue;
  7795. }
  7796. mesh._preActivate();
  7797. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7798. this._activeMeshes.push(mesh);
  7799. mesh._activate(this._renderId);
  7800. this._activeMesh(meshLOD);
  7801. }
  7802. }
  7803. // Particle systems
  7804. var beforeParticlesDate = BABYLON.Tools.Now;
  7805. if (this.particlesEnabled) {
  7806. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7807. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7808. var particleSystem = this.particleSystems[particleIndex];
  7809. if (!particleSystem.isStarted()) {
  7810. continue;
  7811. }
  7812. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7813. this._activeParticleSystems.push(particleSystem);
  7814. particleSystem.animate();
  7815. }
  7816. }
  7817. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7818. }
  7819. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7820. };
  7821. Scene.prototype._activeMesh = function (mesh) {
  7822. if (mesh.skeleton && this.skeletonsEnabled) {
  7823. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7824. }
  7825. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7826. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7827. }
  7828. if (mesh && mesh.subMeshes) {
  7829. // Submeshes Octrees
  7830. var len;
  7831. var subMeshes;
  7832. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7833. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7834. len = intersections.length;
  7835. subMeshes = intersections.data;
  7836. } else {
  7837. subMeshes = mesh.subMeshes;
  7838. len = subMeshes.length;
  7839. }
  7840. for (var subIndex = 0; subIndex < len; subIndex++) {
  7841. var subMesh = subMeshes[subIndex];
  7842. this._evaluateSubMesh(subMesh, mesh);
  7843. }
  7844. }
  7845. };
  7846. Scene.prototype.updateTransformMatrix = function (force) {
  7847. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7848. };
  7849. Scene.prototype._renderForCamera = function (camera) {
  7850. var engine = this._engine;
  7851. this.activeCamera = camera;
  7852. if (!this.activeCamera)
  7853. throw new Error("Active camera not set");
  7854. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7855. // Viewport
  7856. engine.setViewport(this.activeCamera.viewport);
  7857. // Camera
  7858. this._renderId++;
  7859. this.updateTransformMatrix();
  7860. if (this.beforeCameraRender) {
  7861. this.beforeCameraRender(this.activeCamera);
  7862. }
  7863. // Meshes
  7864. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7865. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7866. this._evaluateActiveMeshes();
  7867. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7868. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7869. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7870. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7871. skeleton.prepare();
  7872. this._activeBones += skeleton.bones.length;
  7873. }
  7874. // Render targets
  7875. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7876. if (this.renderTargetsEnabled) {
  7877. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7878. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7879. var renderTarget = this._renderTargets.data[renderIndex];
  7880. if (renderTarget._shouldRender()) {
  7881. this._renderId++;
  7882. renderTarget.render();
  7883. }
  7884. }
  7885. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7886. this._renderId++;
  7887. }
  7888. if (this._renderTargets.length > 0) {
  7889. engine.restoreDefaultFramebuffer();
  7890. }
  7891. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7892. // Prepare Frame
  7893. this.postProcessManager._prepareFrame();
  7894. var beforeRenderDate = BABYLON.Tools.Now;
  7895. // Backgrounds
  7896. if (this.layers.length) {
  7897. engine.setDepthBuffer(false);
  7898. var layerIndex;
  7899. var layer;
  7900. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7901. layer = this.layers[layerIndex];
  7902. if (layer.isBackground) {
  7903. layer.render();
  7904. }
  7905. }
  7906. engine.setDepthBuffer(true);
  7907. }
  7908. // Render
  7909. BABYLON.Tools.StartPerformanceCounter("Main render");
  7910. this._renderingManager.render(null, null, true, true);
  7911. BABYLON.Tools.EndPerformanceCounter("Main render");
  7912. // Bounding boxes
  7913. this._boundingBoxRenderer.render();
  7914. // Lens flares
  7915. if (this.lensFlaresEnabled) {
  7916. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7917. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7918. this.lensFlareSystems[lensFlareSystemIndex].render();
  7919. }
  7920. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7921. }
  7922. // Foregrounds
  7923. if (this.layers.length) {
  7924. engine.setDepthBuffer(false);
  7925. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7926. layer = this.layers[layerIndex];
  7927. if (!layer.isBackground) {
  7928. layer.render();
  7929. }
  7930. }
  7931. engine.setDepthBuffer(true);
  7932. }
  7933. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7934. // Finalize frame
  7935. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7936. // Update camera
  7937. this.activeCamera._updateFromScene();
  7938. // Reset some special arrays
  7939. this._renderTargets.reset();
  7940. if (this.afterCameraRender) {
  7941. this.afterCameraRender(this.activeCamera);
  7942. }
  7943. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7944. };
  7945. Scene.prototype._processSubCameras = function (camera) {
  7946. if (camera.subCameras.length === 0) {
  7947. this._renderForCamera(camera);
  7948. return;
  7949. }
  7950. for (var index = 0; index < camera.subCameras.length; index++) {
  7951. this._renderForCamera(camera.subCameras[index]);
  7952. }
  7953. this.activeCamera = camera;
  7954. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7955. // Update camera
  7956. this.activeCamera._updateFromScene();
  7957. };
  7958. Scene.prototype._checkIntersections = function () {
  7959. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7960. var sourceMesh = this._meshesForIntersections.data[index];
  7961. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7962. var action = sourceMesh.actionManager.actions[actionIndex];
  7963. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7964. var otherMesh = action.getTriggerParameter();
  7965. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7966. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7967. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7968. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7969. sourceMesh._intersectionsInProgress.push(otherMesh);
  7970. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7971. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7972. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7973. if (indexOfOther > -1) {
  7974. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7975. }
  7976. }
  7977. }
  7978. }
  7979. }
  7980. };
  7981. Scene.prototype.render = function () {
  7982. var startDate = BABYLON.Tools.Now;
  7983. this._particlesDuration = 0;
  7984. this._spritesDuration = 0;
  7985. this._activeParticles = 0;
  7986. this._renderDuration = 0;
  7987. this._renderTargetsDuration = 0;
  7988. this._evaluateActiveMeshesDuration = 0;
  7989. this._totalVertices = 0;
  7990. this._activeVertices = 0;
  7991. this._activeBones = 0;
  7992. this.getEngine().resetDrawCalls();
  7993. this._meshesForIntersections.reset();
  7994. this.resetCachedMaterial();
  7995. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7996. // Actions
  7997. if (this.actionManager) {
  7998. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7999. }
  8000. // Before render
  8001. if (this.beforeRender) {
  8002. this.beforeRender();
  8003. }
  8004. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8005. this._onBeforeRenderCallbacks[callbackIndex]();
  8006. }
  8007. // Animations
  8008. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8009. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8010. this._animate();
  8011. // Physics
  8012. if (this._physicsEngine) {
  8013. BABYLON.Tools.StartPerformanceCounter("Physics");
  8014. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8015. BABYLON.Tools.EndPerformanceCounter("Physics");
  8016. }
  8017. // Customs render targets
  8018. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8019. var engine = this.getEngine();
  8020. if (this.renderTargetsEnabled) {
  8021. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8022. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8023. var renderTarget = this.customRenderTargets[customIndex];
  8024. if (renderTarget._shouldRender()) {
  8025. this._renderId++;
  8026. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8027. if (!this.activeCamera)
  8028. throw new Error("Active camera not set");
  8029. // Viewport
  8030. engine.setViewport(this.activeCamera.viewport);
  8031. // Camera
  8032. this.updateTransformMatrix();
  8033. renderTarget.render();
  8034. }
  8035. }
  8036. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8037. this._renderId++;
  8038. }
  8039. if (this.customRenderTargets.length > 0) {
  8040. engine.restoreDefaultFramebuffer();
  8041. }
  8042. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8043. // Procedural textures
  8044. if (this.proceduralTexturesEnabled) {
  8045. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8046. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8047. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8048. if (proceduralTexture._shouldRender()) {
  8049. proceduralTexture.render();
  8050. }
  8051. }
  8052. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8053. }
  8054. // Clear
  8055. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8056. // Shadows
  8057. if (this.shadowsEnabled) {
  8058. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8059. var light = this.lights[lightIndex];
  8060. var shadowGenerator = light.getShadowGenerator();
  8061. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8062. this._renderTargets.push(shadowGenerator.getShadowMap());
  8063. }
  8064. }
  8065. }
  8066. // RenderPipeline
  8067. this.postProcessRenderPipelineManager.update();
  8068. // Multi-cameras?
  8069. if (this.activeCameras.length > 0) {
  8070. var currentRenderId = this._renderId;
  8071. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8072. this._renderId = currentRenderId;
  8073. this._processSubCameras(this.activeCameras[cameraIndex]);
  8074. }
  8075. } else {
  8076. if (!this.activeCamera) {
  8077. throw new Error("No camera defined");
  8078. }
  8079. this._processSubCameras(this.activeCamera);
  8080. }
  8081. // Intersection checks
  8082. this._checkIntersections();
  8083. // Update the audio listener attached to the camera
  8084. this._updateAudioParameters();
  8085. // After render
  8086. if (this.afterRender) {
  8087. this.afterRender();
  8088. }
  8089. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8090. this._onAfterRenderCallbacks[callbackIndex]();
  8091. }
  8092. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8093. this._toBeDisposed.data[index].dispose();
  8094. this._toBeDisposed[index] = null;
  8095. }
  8096. this._toBeDisposed.reset();
  8097. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8098. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8099. };
  8100. Scene.prototype._updateAudioParameters = function () {
  8101. var listeningCamera;
  8102. var audioEngine = this._engine.getAudioEngine();
  8103. if (this.activeCameras.length > 0) {
  8104. listeningCamera = this.activeCameras[0];
  8105. } else {
  8106. listeningCamera = this.activeCamera;
  8107. }
  8108. if (listeningCamera && audioEngine.canUseWebAudio) {
  8109. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8110. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8111. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8112. cameraDirection.normalize();
  8113. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8114. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8115. var sound = this.mainSoundTrack.soundCollection[i];
  8116. if (sound.useCustomAttenuation) {
  8117. sound.updateDistanceFromListener();
  8118. }
  8119. }
  8120. for (var i = 0; i < this.soundTracks.length; i++) {
  8121. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8122. var sound = this.soundTracks[i].soundCollection[j];
  8123. if (sound.useCustomAttenuation) {
  8124. sound.updateDistanceFromListener();
  8125. }
  8126. }
  8127. }
  8128. }
  8129. };
  8130. Scene.prototype.dispose = function () {
  8131. this.beforeRender = null;
  8132. this.afterRender = null;
  8133. this.skeletons = [];
  8134. this._boundingBoxRenderer.dispose();
  8135. // Debug layer
  8136. this.debugLayer.hide();
  8137. // Events
  8138. if (this.onDispose) {
  8139. this.onDispose();
  8140. }
  8141. this._onBeforeRenderCallbacks = [];
  8142. this._onAfterRenderCallbacks = [];
  8143. this.detachControl();
  8144. // Detach cameras
  8145. var canvas = this._engine.getRenderingCanvas();
  8146. var index;
  8147. for (index = 0; index < this.cameras.length; index++) {
  8148. this.cameras[index].detachControl(canvas);
  8149. }
  8150. while (this.lights.length) {
  8151. this.lights[0].dispose();
  8152. }
  8153. while (this.meshes.length) {
  8154. this.meshes[0].dispose(true);
  8155. }
  8156. while (this.cameras.length) {
  8157. this.cameras[0].dispose();
  8158. }
  8159. while (this.materials.length) {
  8160. this.materials[0].dispose();
  8161. }
  8162. while (this.particleSystems.length) {
  8163. this.particleSystems[0].dispose();
  8164. }
  8165. while (this.spriteManagers.length) {
  8166. this.spriteManagers[0].dispose();
  8167. }
  8168. while (this.layers.length) {
  8169. this.layers[0].dispose();
  8170. }
  8171. while (this.textures.length) {
  8172. this.textures[0].dispose();
  8173. }
  8174. // Post-processes
  8175. this.postProcessManager.dispose();
  8176. // Physics
  8177. if (this._physicsEngine) {
  8178. this.disablePhysicsEngine();
  8179. }
  8180. // Remove from engine
  8181. index = this._engine.scenes.indexOf(this);
  8182. if (index > -1) {
  8183. this._engine.scenes.splice(index, 1);
  8184. }
  8185. this._engine.wipeCaches();
  8186. };
  8187. // Collisions
  8188. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8189. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8190. position.divideToRef(collider.radius, this._scaledPosition);
  8191. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8192. collider.retry = 0;
  8193. collider.initialVelocity = this._scaledVelocity;
  8194. collider.initialPosition = this._scaledPosition;
  8195. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8196. finalPosition.multiplyInPlace(collider.radius);
  8197. };
  8198. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8199. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8200. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8201. if (collider.retry >= maximumRetry) {
  8202. finalPosition.copyFrom(position);
  8203. return;
  8204. }
  8205. collider._initialize(position, velocity, closeDistance);
  8206. for (var index = 0; index < this.meshes.length; index++) {
  8207. var mesh = this.meshes[index];
  8208. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8209. mesh._checkCollision(collider);
  8210. }
  8211. }
  8212. if (!collider.collisionFound) {
  8213. position.addToRef(velocity, finalPosition);
  8214. return;
  8215. }
  8216. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8217. collider._getResponse(position, velocity);
  8218. }
  8219. if (velocity.length() <= closeDistance) {
  8220. finalPosition.copyFrom(position);
  8221. return;
  8222. }
  8223. collider.retry++;
  8224. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8225. };
  8226. // Octrees
  8227. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8228. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8229. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8230. if (!this._selectionOctree) {
  8231. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8232. }
  8233. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8234. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8235. for (var index = 0; index < this.meshes.length; index++) {
  8236. var mesh = this.meshes[index];
  8237. mesh.computeWorldMatrix(true);
  8238. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8239. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8240. BABYLON.Tools.CheckExtends(minBox, min, max);
  8241. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8242. }
  8243. // Update octree
  8244. this._selectionOctree.update(min, max, this.meshes);
  8245. return this._selectionOctree;
  8246. };
  8247. // Picking
  8248. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8249. var engine = this._engine;
  8250. if (!camera) {
  8251. if (!this.activeCamera)
  8252. throw new Error("Active camera not set");
  8253. camera = this.activeCamera;
  8254. }
  8255. var cameraViewport = camera.viewport;
  8256. var viewport = cameraViewport.toGlobal(engine);
  8257. // Moving coordinates to local viewport world
  8258. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8259. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8260. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8261. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8262. };
  8263. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8264. var pickingInfo = null;
  8265. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8266. var mesh = this.meshes[meshIndex];
  8267. if (predicate) {
  8268. if (!predicate(mesh)) {
  8269. continue;
  8270. }
  8271. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8272. continue;
  8273. }
  8274. var world = mesh.getWorldMatrix();
  8275. var ray = rayFunction(world);
  8276. var result = mesh.intersects(ray, fastCheck);
  8277. if (!result || !result.hit)
  8278. continue;
  8279. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8280. continue;
  8281. pickingInfo = result;
  8282. if (fastCheck) {
  8283. break;
  8284. }
  8285. }
  8286. return pickingInfo || new BABYLON.PickingInfo();
  8287. };
  8288. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8289. var _this = this;
  8290. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8291. /// <param name="x">X position on screen</param>
  8292. /// <param name="y">Y position on screen</param>
  8293. /// <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>
  8294. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8295. /// <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>
  8296. return this._internalPick(function (world) {
  8297. return _this.createPickingRay(x, y, world, camera);
  8298. }, predicate, fastCheck);
  8299. };
  8300. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8301. var _this = this;
  8302. return this._internalPick(function (world) {
  8303. if (!_this._pickWithRayInverseMatrix) {
  8304. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8305. }
  8306. world.invertToRef(_this._pickWithRayInverseMatrix);
  8307. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8308. }, predicate, fastCheck);
  8309. };
  8310. Scene.prototype.setPointerOverMesh = function (mesh) {
  8311. if (this._pointerOverMesh === mesh) {
  8312. return;
  8313. }
  8314. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8315. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8316. }
  8317. this._pointerOverMesh = mesh;
  8318. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8319. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8320. }
  8321. };
  8322. Scene.prototype.getPointerOverMesh = function () {
  8323. return this._pointerOverMesh;
  8324. };
  8325. // Physics
  8326. Scene.prototype.getPhysicsEngine = function () {
  8327. return this._physicsEngine;
  8328. };
  8329. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8330. if (this._physicsEngine) {
  8331. return true;
  8332. }
  8333. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8334. if (!this._physicsEngine.isSupported()) {
  8335. this._physicsEngine = null;
  8336. return false;
  8337. }
  8338. this._physicsEngine._initialize(gravity);
  8339. return true;
  8340. };
  8341. Scene.prototype.disablePhysicsEngine = function () {
  8342. if (!this._physicsEngine) {
  8343. return;
  8344. }
  8345. this._physicsEngine.dispose();
  8346. this._physicsEngine = undefined;
  8347. };
  8348. Scene.prototype.isPhysicsEnabled = function () {
  8349. return this._physicsEngine !== undefined;
  8350. };
  8351. Scene.prototype.setGravity = function (gravity) {
  8352. if (!this._physicsEngine) {
  8353. return;
  8354. }
  8355. this._physicsEngine._setGravity(gravity);
  8356. };
  8357. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8358. if (parts.parts) {
  8359. options = parts;
  8360. parts = parts.parts;
  8361. }
  8362. if (!this._physicsEngine) {
  8363. return null;
  8364. }
  8365. for (var index = 0; index < parts.length; index++) {
  8366. var mesh = parts[index].mesh;
  8367. mesh._physicImpostor = parts[index].impostor;
  8368. mesh._physicsMass = options.mass / parts.length;
  8369. mesh._physicsFriction = options.friction;
  8370. mesh._physicRestitution = options.restitution;
  8371. }
  8372. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8373. };
  8374. //ANY
  8375. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8376. for (var index = 0; index < compound.parts.length; index++) {
  8377. var mesh = compound.parts[index].mesh;
  8378. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8379. this._physicsEngine._unregisterMesh(mesh);
  8380. }
  8381. };
  8382. // Tags
  8383. Scene.prototype._getByTags = function (list, tagsQuery) {
  8384. if (tagsQuery === undefined) {
  8385. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8386. return list;
  8387. }
  8388. var listByTags = [];
  8389. for (var i in list) {
  8390. var item = list[i];
  8391. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8392. listByTags.push(item);
  8393. }
  8394. }
  8395. return listByTags;
  8396. };
  8397. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8398. return this._getByTags(this.meshes, tagsQuery);
  8399. };
  8400. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8401. return this._getByTags(this.cameras, tagsQuery);
  8402. };
  8403. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8404. return this._getByTags(this.lights, tagsQuery);
  8405. };
  8406. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8407. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8408. };
  8409. Scene.FOGMODE_NONE = 0;
  8410. Scene.FOGMODE_EXP = 1;
  8411. Scene.FOGMODE_EXP2 = 2;
  8412. Scene.FOGMODE_LINEAR = 3;
  8413. Scene.MinDeltaTime = 1.0;
  8414. Scene.MaxDeltaTime = 1000.0;
  8415. return Scene;
  8416. })();
  8417. BABYLON.Scene = Scene;
  8418. })(BABYLON || (BABYLON = {}));
  8419. //# sourceMappingURL=babylon.scene.js.map
  8420. var BABYLON;
  8421. (function (BABYLON) {
  8422. var VertexBuffer = (function () {
  8423. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8424. if (engine instanceof BABYLON.Mesh) {
  8425. this._engine = engine.getScene().getEngine();
  8426. } else {
  8427. this._engine = engine;
  8428. }
  8429. this._updatable = updatable;
  8430. this._data = data;
  8431. if (!postponeInternalCreation) {
  8432. this.create();
  8433. }
  8434. this._kind = kind;
  8435. if (stride) {
  8436. this._strideSize = stride;
  8437. return;
  8438. }
  8439. switch (kind) {
  8440. case VertexBuffer.PositionKind:
  8441. this._strideSize = 3;
  8442. break;
  8443. case VertexBuffer.NormalKind:
  8444. this._strideSize = 3;
  8445. break;
  8446. case VertexBuffer.UVKind:
  8447. this._strideSize = 2;
  8448. break;
  8449. case VertexBuffer.UV2Kind:
  8450. this._strideSize = 2;
  8451. break;
  8452. case VertexBuffer.ColorKind:
  8453. this._strideSize = 4;
  8454. break;
  8455. case VertexBuffer.MatricesIndicesKind:
  8456. this._strideSize = 4;
  8457. break;
  8458. case VertexBuffer.MatricesWeightsKind:
  8459. this._strideSize = 4;
  8460. break;
  8461. }
  8462. }
  8463. // Properties
  8464. VertexBuffer.prototype.isUpdatable = function () {
  8465. return this._updatable;
  8466. };
  8467. VertexBuffer.prototype.getData = function () {
  8468. return this._data;
  8469. };
  8470. VertexBuffer.prototype.getBuffer = function () {
  8471. return this._buffer;
  8472. };
  8473. VertexBuffer.prototype.getStrideSize = function () {
  8474. return this._strideSize;
  8475. };
  8476. // Methods
  8477. VertexBuffer.prototype.create = function (data) {
  8478. if (!data && this._buffer) {
  8479. return;
  8480. }
  8481. data = data || this._data;
  8482. if (!this._buffer) {
  8483. if (this._updatable) {
  8484. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8485. } else {
  8486. this._buffer = this._engine.createVertexBuffer(data);
  8487. }
  8488. }
  8489. if (this._updatable) {
  8490. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8491. this._data = data;
  8492. }
  8493. };
  8494. VertexBuffer.prototype.update = function (data) {
  8495. this.create(data);
  8496. };
  8497. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8498. if (!this._buffer) {
  8499. return;
  8500. }
  8501. if (this._updatable) {
  8502. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8503. this._data = null;
  8504. }
  8505. };
  8506. VertexBuffer.prototype.dispose = function () {
  8507. if (!this._buffer) {
  8508. return;
  8509. }
  8510. if (this._engine._releaseBuffer(this._buffer)) {
  8511. this._buffer = null;
  8512. }
  8513. };
  8514. Object.defineProperty(VertexBuffer, "PositionKind", {
  8515. get: function () {
  8516. return VertexBuffer._PositionKind;
  8517. },
  8518. enumerable: true,
  8519. configurable: true
  8520. });
  8521. Object.defineProperty(VertexBuffer, "NormalKind", {
  8522. get: function () {
  8523. return VertexBuffer._NormalKind;
  8524. },
  8525. enumerable: true,
  8526. configurable: true
  8527. });
  8528. Object.defineProperty(VertexBuffer, "UVKind", {
  8529. get: function () {
  8530. return VertexBuffer._UVKind;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8536. get: function () {
  8537. return VertexBuffer._UV2Kind;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(VertexBuffer, "ColorKind", {
  8543. get: function () {
  8544. return VertexBuffer._ColorKind;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8550. get: function () {
  8551. return VertexBuffer._MatricesIndicesKind;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8557. get: function () {
  8558. return VertexBuffer._MatricesWeightsKind;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. VertexBuffer._PositionKind = "position";
  8564. VertexBuffer._NormalKind = "normal";
  8565. VertexBuffer._UVKind = "uv";
  8566. VertexBuffer._UV2Kind = "uv2";
  8567. VertexBuffer._ColorKind = "color";
  8568. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8569. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8570. return VertexBuffer;
  8571. })();
  8572. BABYLON.VertexBuffer = VertexBuffer;
  8573. })(BABYLON || (BABYLON = {}));
  8574. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8575. var BABYLON;
  8576. (function (BABYLON) {
  8577. var AbstractMesh = (function (_super) {
  8578. __extends(AbstractMesh, _super);
  8579. function AbstractMesh(name, scene) {
  8580. _super.call(this, name, scene);
  8581. // Properties
  8582. this.position = new BABYLON.Vector3(0, 0, 0);
  8583. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8584. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8585. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8586. this.visibility = 1.0;
  8587. this.alphaIndex = Number.MAX_VALUE;
  8588. this.infiniteDistance = false;
  8589. this.isVisible = true;
  8590. this.isPickable = true;
  8591. this.showBoundingBox = false;
  8592. this.showSubMeshesBoundingBox = false;
  8593. this.onDispose = null;
  8594. this.checkCollisions = false;
  8595. this.isBlocker = false;
  8596. this.renderingGroupId = 0;
  8597. this.receiveShadows = false;
  8598. this.renderOutline = false;
  8599. this.outlineColor = BABYLON.Color3.Red();
  8600. this.outlineWidth = 0.02;
  8601. this.renderOverlay = false;
  8602. this.overlayColor = BABYLON.Color3.Red();
  8603. this.overlayAlpha = 0.5;
  8604. this.hasVertexAlpha = false;
  8605. this.useVertexColors = true;
  8606. this.applyFog = true;
  8607. this.useOctreeForRenderingSelection = true;
  8608. this.useOctreeForPicking = true;
  8609. this.useOctreeForCollisions = true;
  8610. this.layerMask = 0xFFFFFFFF;
  8611. // Physics
  8612. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8613. // Collisions
  8614. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8615. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8616. this._collider = new BABYLON.Collider();
  8617. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8618. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8619. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8620. // Cache
  8621. this._localScaling = BABYLON.Matrix.Zero();
  8622. this._localRotation = BABYLON.Matrix.Zero();
  8623. this._localTranslation = BABYLON.Matrix.Zero();
  8624. this._localBillboard = BABYLON.Matrix.Zero();
  8625. this._localPivotScaling = BABYLON.Matrix.Zero();
  8626. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8627. this._localWorld = BABYLON.Matrix.Zero();
  8628. this._worldMatrix = BABYLON.Matrix.Zero();
  8629. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8630. this._absolutePosition = BABYLON.Vector3.Zero();
  8631. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8632. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8633. this._isDirty = false;
  8634. this._pivotMatrix = BABYLON.Matrix.Identity();
  8635. this._isDisposed = false;
  8636. this._renderId = 0;
  8637. this._intersectionsInProgress = new Array();
  8638. this._onAfterWorldMatrixUpdate = new Array();
  8639. scene.meshes.push(this);
  8640. }
  8641. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8642. get: function () {
  8643. return AbstractMesh._BILLBOARDMODE_NONE;
  8644. },
  8645. enumerable: true,
  8646. configurable: true
  8647. });
  8648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8649. get: function () {
  8650. return AbstractMesh._BILLBOARDMODE_X;
  8651. },
  8652. enumerable: true,
  8653. configurable: true
  8654. });
  8655. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8656. get: function () {
  8657. return AbstractMesh._BILLBOARDMODE_Y;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8663. get: function () {
  8664. return AbstractMesh._BILLBOARDMODE_Z;
  8665. },
  8666. enumerable: true,
  8667. configurable: true
  8668. });
  8669. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8670. get: function () {
  8671. return AbstractMesh._BILLBOARDMODE_ALL;
  8672. },
  8673. enumerable: true,
  8674. configurable: true
  8675. });
  8676. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8677. // Methods
  8678. get: function () {
  8679. return false;
  8680. },
  8681. enumerable: true,
  8682. configurable: true
  8683. });
  8684. AbstractMesh.prototype.getLOD = function (camera) {
  8685. return this;
  8686. };
  8687. AbstractMesh.prototype.getTotalVertices = function () {
  8688. return 0;
  8689. };
  8690. AbstractMesh.prototype.getIndices = function () {
  8691. return null;
  8692. };
  8693. AbstractMesh.prototype.getVerticesData = function (kind) {
  8694. return null;
  8695. };
  8696. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8697. return false;
  8698. };
  8699. AbstractMesh.prototype.getBoundingInfo = function () {
  8700. if (this._masterMesh) {
  8701. return this._masterMesh.getBoundingInfo();
  8702. }
  8703. if (!this._boundingInfo) {
  8704. this._updateBoundingInfo();
  8705. }
  8706. return this._boundingInfo;
  8707. };
  8708. AbstractMesh.prototype._preActivate = function () {
  8709. };
  8710. AbstractMesh.prototype._activate = function (renderId) {
  8711. this._renderId = renderId;
  8712. };
  8713. AbstractMesh.prototype.getWorldMatrix = function () {
  8714. if (this._masterMesh) {
  8715. return this._masterMesh.getWorldMatrix();
  8716. }
  8717. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8718. this.computeWorldMatrix();
  8719. }
  8720. return this._worldMatrix;
  8721. };
  8722. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8723. get: function () {
  8724. return this._worldMatrix;
  8725. },
  8726. enumerable: true,
  8727. configurable: true
  8728. });
  8729. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8730. get: function () {
  8731. return this._absolutePosition;
  8732. },
  8733. enumerable: true,
  8734. configurable: true
  8735. });
  8736. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8737. if (!this.rotationQuaternion) {
  8738. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8739. this.rotation = BABYLON.Vector3.Zero();
  8740. }
  8741. if (!space || space == 0 /* LOCAL */) {
  8742. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8743. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8744. } else {
  8745. if (this.parent) {
  8746. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8747. invertParentWorldMatrix.invert();
  8748. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8749. }
  8750. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8751. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8752. }
  8753. };
  8754. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8755. var displacementVector = axis.scale(distance);
  8756. if (!space || space == 0 /* LOCAL */) {
  8757. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8758. this.setPositionWithLocalVector(tempV3);
  8759. } else {
  8760. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8761. }
  8762. };
  8763. AbstractMesh.prototype.getAbsolutePosition = function () {
  8764. this.computeWorldMatrix();
  8765. return this._absolutePosition;
  8766. };
  8767. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8768. if (!absolutePosition) {
  8769. return;
  8770. }
  8771. var absolutePositionX;
  8772. var absolutePositionY;
  8773. var absolutePositionZ;
  8774. if (absolutePosition.x === undefined) {
  8775. if (arguments.length < 3) {
  8776. return;
  8777. }
  8778. absolutePositionX = arguments[0];
  8779. absolutePositionY = arguments[1];
  8780. absolutePositionZ = arguments[2];
  8781. } else {
  8782. absolutePositionX = absolutePosition.x;
  8783. absolutePositionY = absolutePosition.y;
  8784. absolutePositionZ = absolutePosition.z;
  8785. }
  8786. if (this.parent) {
  8787. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8788. invertParentWorldMatrix.invert();
  8789. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8790. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8791. } else {
  8792. this.position.x = absolutePositionX;
  8793. this.position.y = absolutePositionY;
  8794. this.position.z = absolutePositionZ;
  8795. }
  8796. };
  8797. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8798. this._pivotMatrix = matrix;
  8799. this._cache.pivotMatrixUpdated = true;
  8800. };
  8801. AbstractMesh.prototype.getPivotMatrix = function () {
  8802. return this._pivotMatrix;
  8803. };
  8804. AbstractMesh.prototype._isSynchronized = function () {
  8805. if (this._isDirty) {
  8806. return false;
  8807. }
  8808. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8809. return false;
  8810. if (this._cache.pivotMatrixUpdated) {
  8811. return false;
  8812. }
  8813. if (this.infiniteDistance) {
  8814. return false;
  8815. }
  8816. if (!this._cache.position.equals(this.position))
  8817. return false;
  8818. if (this.rotationQuaternion) {
  8819. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8820. return false;
  8821. } else {
  8822. if (!this._cache.rotation.equals(this.rotation))
  8823. return false;
  8824. }
  8825. if (!this._cache.scaling.equals(this.scaling))
  8826. return false;
  8827. return true;
  8828. };
  8829. AbstractMesh.prototype._initCache = function () {
  8830. _super.prototype._initCache.call(this);
  8831. this._cache.localMatrixUpdated = false;
  8832. this._cache.position = BABYLON.Vector3.Zero();
  8833. this._cache.scaling = BABYLON.Vector3.Zero();
  8834. this._cache.rotation = BABYLON.Vector3.Zero();
  8835. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8836. };
  8837. AbstractMesh.prototype.markAsDirty = function (property) {
  8838. if (property === "rotation") {
  8839. this.rotationQuaternion = null;
  8840. }
  8841. this._currentRenderId = Number.MAX_VALUE;
  8842. this._isDirty = true;
  8843. };
  8844. AbstractMesh.prototype._updateBoundingInfo = function () {
  8845. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8846. this._boundingInfo._update(this.worldMatrixFromCache);
  8847. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8848. };
  8849. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8850. if (!this.subMeshes) {
  8851. return;
  8852. }
  8853. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8854. var subMesh = this.subMeshes[subIndex];
  8855. subMesh.updateBoundingInfo(matrix);
  8856. }
  8857. };
  8858. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8859. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8860. return this._worldMatrix;
  8861. }
  8862. this._cache.position.copyFrom(this.position);
  8863. this._cache.scaling.copyFrom(this.scaling);
  8864. this._cache.pivotMatrixUpdated = false;
  8865. this._currentRenderId = this.getScene().getRenderId();
  8866. this._isDirty = false;
  8867. // Scaling
  8868. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8869. // Rotation
  8870. if (this.rotationQuaternion) {
  8871. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8872. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8873. } else {
  8874. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8875. this._cache.rotation.copyFrom(this.rotation);
  8876. }
  8877. // Translation
  8878. if (this.infiniteDistance && !this.parent) {
  8879. var camera = this.getScene().activeCamera;
  8880. var cameraWorldMatrix = camera.getWorldMatrix();
  8881. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8882. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8883. } else {
  8884. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8885. }
  8886. // Composing transformations
  8887. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8888. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8889. // Billboarding
  8890. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8891. var localPosition = this.position.clone();
  8892. var zero = this.getScene().activeCamera.position.clone();
  8893. if (this.parent && this.parent.position) {
  8894. localPosition.addInPlace(this.parent.position);
  8895. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8896. }
  8897. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8898. zero = this.getScene().activeCamera.position;
  8899. } else {
  8900. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8901. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8902. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8903. zero.y = localPosition.y + 0.001;
  8904. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8905. zero.z = localPosition.z + 0.001;
  8906. }
  8907. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8908. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8909. this._localBillboard.invert();
  8910. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8911. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8912. }
  8913. // Local world
  8914. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8915. // Parent
  8916. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8917. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8918. } else {
  8919. this._worldMatrix.copyFrom(this._localWorld);
  8920. }
  8921. // Bounding info
  8922. this._updateBoundingInfo();
  8923. // Absolute position
  8924. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8925. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8926. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8927. }
  8928. return this._worldMatrix;
  8929. };
  8930. /**
  8931. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8932. * @param func: callback function to add
  8933. */
  8934. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8935. this._onAfterWorldMatrixUpdate.push(func);
  8936. };
  8937. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8938. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8939. if (index > -1) {
  8940. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8941. }
  8942. };
  8943. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8944. this.computeWorldMatrix();
  8945. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8946. };
  8947. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8948. this.computeWorldMatrix();
  8949. var invLocalWorldMatrix = this._localWorld.clone();
  8950. invLocalWorldMatrix.invert();
  8951. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8952. };
  8953. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8954. this.computeWorldMatrix();
  8955. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8956. };
  8957. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8958. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8959. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8960. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8961. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8962. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8963. /// <returns>Mesh oriented towards targetMesh</returns>
  8964. yawCor = yawCor || 0; // default to zero if undefined
  8965. pitchCor = pitchCor || 0;
  8966. rollCor = rollCor || 0;
  8967. var dv = targetPoint.subtract(this.position);
  8968. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8969. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8970. var pitch = Math.atan2(dv.y, len);
  8971. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8972. };
  8973. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8974. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8975. return false;
  8976. }
  8977. return true;
  8978. };
  8979. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8980. if (!camera) {
  8981. camera = this.getScene().activeCamera;
  8982. }
  8983. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8984. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8985. return false;
  8986. }
  8987. return true;
  8988. };
  8989. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8990. if (!this._boundingInfo || !mesh._boundingInfo) {
  8991. return false;
  8992. }
  8993. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8994. };
  8995. AbstractMesh.prototype.intersectsPoint = function (point) {
  8996. if (!this._boundingInfo) {
  8997. return false;
  8998. }
  8999. return this._boundingInfo.intersectsPoint(point);
  9000. };
  9001. // Physics
  9002. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9003. var physicsEngine = this.getScene().getPhysicsEngine();
  9004. if (!physicsEngine) {
  9005. return;
  9006. }
  9007. if (impostor.impostor) {
  9008. // Old API
  9009. options = impostor;
  9010. impostor = impostor.impostor;
  9011. }
  9012. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9013. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9014. physicsEngine._unregisterMesh(this);
  9015. return;
  9016. }
  9017. options.mass = options.mass || 0;
  9018. options.friction = options.friction || 0.2;
  9019. options.restitution = options.restitution || 0.2;
  9020. this._physicImpostor = impostor;
  9021. this._physicsMass = options.mass;
  9022. this._physicsFriction = options.friction;
  9023. this._physicRestitution = options.restitution;
  9024. return physicsEngine._registerMesh(this, impostor, options);
  9025. };
  9026. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9027. if (!this._physicImpostor) {
  9028. return BABYLON.PhysicsEngine.NoImpostor;
  9029. }
  9030. return this._physicImpostor;
  9031. };
  9032. AbstractMesh.prototype.getPhysicsMass = function () {
  9033. if (!this._physicsMass) {
  9034. return 0;
  9035. }
  9036. return this._physicsMass;
  9037. };
  9038. AbstractMesh.prototype.getPhysicsFriction = function () {
  9039. if (!this._physicsFriction) {
  9040. return 0;
  9041. }
  9042. return this._physicsFriction;
  9043. };
  9044. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9045. if (!this._physicRestitution) {
  9046. return 0;
  9047. }
  9048. return this._physicRestitution;
  9049. };
  9050. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9051. if (!camera) {
  9052. camera = this.getScene().activeCamera;
  9053. }
  9054. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9055. };
  9056. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9057. if (!camera) {
  9058. camera = this.getScene().activeCamera;
  9059. }
  9060. return this.absolutePosition.subtract(camera.position).length();
  9061. };
  9062. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9063. if (!this._physicImpostor) {
  9064. return;
  9065. }
  9066. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9067. };
  9068. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9069. if (!this._physicImpostor) {
  9070. return;
  9071. }
  9072. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9073. };
  9074. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9075. if (!this._physicImpostor) {
  9076. return;
  9077. }
  9078. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9079. };
  9080. // Collisions
  9081. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9082. var globalPosition = this.getAbsolutePosition();
  9083. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9084. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9085. this._collider.radius = this.ellipsoid;
  9086. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9087. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9088. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9089. this.position.addInPlace(this._diffPositionForCollisions);
  9090. }
  9091. };
  9092. // Submeshes octree
  9093. /**
  9094. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9095. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9096. */
  9097. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9098. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  9099. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  9100. if (!this._submeshesOctree) {
  9101. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9102. }
  9103. this.computeWorldMatrix(true);
  9104. // Update octree
  9105. var bbox = this.getBoundingInfo().boundingBox;
  9106. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9107. return this._submeshesOctree;
  9108. };
  9109. // Collisions
  9110. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9111. this._generatePointsArray();
  9112. // Transformation
  9113. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9114. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9115. subMesh._lastColliderWorldVertices = [];
  9116. subMesh._trianglePlanes = [];
  9117. var start = subMesh.verticesStart;
  9118. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9119. for (var i = start; i < end; i++) {
  9120. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9121. }
  9122. }
  9123. // Collide
  9124. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9125. };
  9126. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9127. var subMeshes;
  9128. var len;
  9129. // Octrees
  9130. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9131. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9132. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9133. len = intersections.length;
  9134. subMeshes = intersections.data;
  9135. } else {
  9136. subMeshes = this.subMeshes;
  9137. len = subMeshes.length;
  9138. }
  9139. for (var index = 0; index < len; index++) {
  9140. var subMesh = subMeshes[index];
  9141. // Bounding test
  9142. if (len > 1 && !subMesh._checkCollision(collider))
  9143. continue;
  9144. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9145. }
  9146. };
  9147. AbstractMesh.prototype._checkCollision = function (collider) {
  9148. // Bounding box test
  9149. if (!this._boundingInfo._checkCollision(collider))
  9150. return;
  9151. // Transformation matrix
  9152. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9153. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9154. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9155. };
  9156. // Picking
  9157. AbstractMesh.prototype._generatePointsArray = function () {
  9158. return false;
  9159. };
  9160. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9161. var pickingInfo = new BABYLON.PickingInfo();
  9162. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9163. return pickingInfo;
  9164. }
  9165. if (!this._generatePointsArray()) {
  9166. return pickingInfo;
  9167. }
  9168. var intersectInfo = null;
  9169. // Octrees
  9170. var subMeshes;
  9171. var len;
  9172. if (this._submeshesOctree && this.useOctreeForPicking) {
  9173. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9174. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9175. len = intersections.length;
  9176. subMeshes = intersections.data;
  9177. } else {
  9178. subMeshes = this.subMeshes;
  9179. len = subMeshes.length;
  9180. }
  9181. for (var index = 0; index < len; index++) {
  9182. var subMesh = subMeshes[index];
  9183. // Bounding test
  9184. if (len > 1 && !subMesh.canIntersects(ray))
  9185. continue;
  9186. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9187. if (currentIntersectInfo) {
  9188. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9189. intersectInfo = currentIntersectInfo;
  9190. if (fastCheck) {
  9191. break;
  9192. }
  9193. }
  9194. }
  9195. }
  9196. if (intersectInfo) {
  9197. // Get picked point
  9198. var world = this.getWorldMatrix();
  9199. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9200. var direction = ray.direction.clone();
  9201. direction.normalize();
  9202. direction = direction.scale(intersectInfo.distance);
  9203. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9204. var pickedPoint = worldOrigin.add(worldDirection);
  9205. // Return result
  9206. pickingInfo.hit = true;
  9207. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9208. pickingInfo.pickedPoint = pickedPoint;
  9209. pickingInfo.pickedMesh = this;
  9210. pickingInfo.bu = intersectInfo.bu;
  9211. pickingInfo.bv = intersectInfo.bv;
  9212. pickingInfo.faceId = intersectInfo.faceId;
  9213. return pickingInfo;
  9214. }
  9215. return pickingInfo;
  9216. };
  9217. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9218. return null;
  9219. };
  9220. AbstractMesh.prototype.releaseSubMeshes = function () {
  9221. if (this.subMeshes) {
  9222. while (this.subMeshes.length) {
  9223. this.subMeshes[0].dispose();
  9224. }
  9225. } else {
  9226. this.subMeshes = new Array();
  9227. }
  9228. };
  9229. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9230. // Physics
  9231. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9232. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9233. }
  9234. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9235. var other = this._intersectionsInProgress[index];
  9236. var pos = other._intersectionsInProgress.indexOf(this);
  9237. other._intersectionsInProgress.splice(pos, 1);
  9238. }
  9239. this._intersectionsInProgress = [];
  9240. // SubMeshes
  9241. this.releaseSubMeshes();
  9242. // Remove from scene
  9243. var index = this.getScene().meshes.indexOf(this);
  9244. if (index != -1) {
  9245. // Remove from the scene if mesh found
  9246. this.getScene().meshes.splice(index, 1);
  9247. }
  9248. if (!doNotRecurse) {
  9249. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9250. if (this.getScene().particleSystems[index].emitter == this) {
  9251. this.getScene().particleSystems[index].dispose();
  9252. index--;
  9253. }
  9254. }
  9255. // Children
  9256. var objects = this.getScene().meshes.slice(0);
  9257. for (index = 0; index < objects.length; index++) {
  9258. if (objects[index].parent == this) {
  9259. objects[index].dispose();
  9260. }
  9261. }
  9262. } else {
  9263. for (index = 0; index < this.getScene().meshes.length; index++) {
  9264. var obj = this.getScene().meshes[index];
  9265. if (obj.parent === this) {
  9266. obj.parent = null;
  9267. obj.computeWorldMatrix(true);
  9268. }
  9269. }
  9270. }
  9271. this._onAfterWorldMatrixUpdate = [];
  9272. this._isDisposed = true;
  9273. // Callback
  9274. if (this.onDispose) {
  9275. this.onDispose();
  9276. }
  9277. };
  9278. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9279. AbstractMesh._BILLBOARDMODE_X = 1;
  9280. AbstractMesh._BILLBOARDMODE_Y = 2;
  9281. AbstractMesh._BILLBOARDMODE_Z = 4;
  9282. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9283. return AbstractMesh;
  9284. })(BABYLON.Node);
  9285. BABYLON.AbstractMesh = AbstractMesh;
  9286. })(BABYLON || (BABYLON = {}));
  9287. //# sourceMappingURL=babylon.abstractMesh.js.map
  9288. var BABYLON;
  9289. (function (BABYLON) {
  9290. var _InstancesBatch = (function () {
  9291. function _InstancesBatch() {
  9292. this.mustReturn = false;
  9293. this.visibleInstances = new Array();
  9294. this.renderSelf = new Array();
  9295. }
  9296. return _InstancesBatch;
  9297. })();
  9298. BABYLON._InstancesBatch = _InstancesBatch;
  9299. var Mesh = (function (_super) {
  9300. __extends(Mesh, _super);
  9301. /**
  9302. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9303. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9304. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9305. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9306. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9307. * When false, achieved by calling a clone(), also passing False.
  9308. * This will make creation of children, recursive.
  9309. */
  9310. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9311. if (typeof parent === "undefined") { parent = null; }
  9312. _super.call(this, name, scene);
  9313. // Members
  9314. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9315. this.instances = new Array();
  9316. this._LODLevels = new Array();
  9317. this._onBeforeRenderCallbacks = new Array();
  9318. this._onAfterRenderCallbacks = new Array();
  9319. this._visibleInstances = {};
  9320. this._renderIdForInstances = new Array();
  9321. this._batchCache = new _InstancesBatch();
  9322. this._instancesBufferSize = 32 * 16 * 4;
  9323. if (source) {
  9324. // Geometry
  9325. if (source._geometry) {
  9326. source._geometry.applyToMesh(this);
  9327. }
  9328. // Deep copy
  9329. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9330. // Material
  9331. this.material = source.material;
  9332. if (!doNotCloneChildren) {
  9333. for (var index = 0; index < scene.meshes.length; index++) {
  9334. var mesh = scene.meshes[index];
  9335. if (mesh.parent === source) {
  9336. // doNotCloneChildren is always going to be False
  9337. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9338. }
  9339. }
  9340. }
  9341. for (index = 0; index < scene.particleSystems.length; index++) {
  9342. var system = scene.particleSystems[index];
  9343. if (system.emitter === source) {
  9344. system.clone(system.name, this);
  9345. }
  9346. }
  9347. this.computeWorldMatrix(true);
  9348. }
  9349. // Parent
  9350. if (parent !== null) {
  9351. this.parent = parent;
  9352. }
  9353. }
  9354. Mesh.prototype._clone = function () {
  9355. };
  9356. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9357. // Methods
  9358. get: function () {
  9359. return this._LODLevels.length > 0;
  9360. },
  9361. enumerable: true,
  9362. configurable: true
  9363. });
  9364. Mesh.prototype._sortLODLevels = function () {
  9365. this._LODLevels.sort(function (a, b) {
  9366. if (a.distance < b.distance) {
  9367. return 1;
  9368. }
  9369. if (a.distance > b.distance) {
  9370. return -1;
  9371. }
  9372. return 0;
  9373. });
  9374. };
  9375. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9376. if (mesh && mesh._masterMesh) {
  9377. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9378. return this;
  9379. }
  9380. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9381. this._LODLevels.push(level);
  9382. if (mesh) {
  9383. mesh._masterMesh = this;
  9384. }
  9385. this._sortLODLevels();
  9386. return this;
  9387. };
  9388. Mesh.prototype.removeLODLevel = function (mesh) {
  9389. for (var index = 0; index < this._LODLevels.length; index++) {
  9390. if (this._LODLevels[index].mesh === mesh) {
  9391. this._LODLevels.splice(index, 1);
  9392. if (mesh) {
  9393. mesh._masterMesh = null;
  9394. }
  9395. }
  9396. }
  9397. this._sortLODLevels();
  9398. return this;
  9399. };
  9400. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9401. if (!this._LODLevels || this._LODLevels.length === 0) {
  9402. return this;
  9403. }
  9404. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9405. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9406. return this;
  9407. }
  9408. for (var index = 0; index < this._LODLevels.length; index++) {
  9409. var level = this._LODLevels[index];
  9410. if (level.distance < distanceToCamera) {
  9411. if (level.mesh) {
  9412. level.mesh._preActivate();
  9413. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9414. }
  9415. return level.mesh;
  9416. }
  9417. }
  9418. return this;
  9419. };
  9420. Object.defineProperty(Mesh.prototype, "geometry", {
  9421. get: function () {
  9422. return this._geometry;
  9423. },
  9424. enumerable: true,
  9425. configurable: true
  9426. });
  9427. Mesh.prototype.getTotalVertices = function () {
  9428. if (!this._geometry) {
  9429. return 0;
  9430. }
  9431. return this._geometry.getTotalVertices();
  9432. };
  9433. Mesh.prototype.getVerticesData = function (kind) {
  9434. if (!this._geometry) {
  9435. return null;
  9436. }
  9437. return this._geometry.getVerticesData(kind);
  9438. };
  9439. Mesh.prototype.getVertexBuffer = function (kind) {
  9440. if (!this._geometry) {
  9441. return undefined;
  9442. }
  9443. return this._geometry.getVertexBuffer(kind);
  9444. };
  9445. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9446. if (!this._geometry) {
  9447. if (this._delayInfo) {
  9448. return this._delayInfo.indexOf(kind) !== -1;
  9449. }
  9450. return false;
  9451. }
  9452. return this._geometry.isVerticesDataPresent(kind);
  9453. };
  9454. Mesh.prototype.getVerticesDataKinds = function () {
  9455. if (!this._geometry) {
  9456. var result = [];
  9457. if (this._delayInfo) {
  9458. for (var kind in this._delayInfo) {
  9459. result.push(kind);
  9460. }
  9461. }
  9462. return result;
  9463. }
  9464. return this._geometry.getVerticesDataKinds();
  9465. };
  9466. Mesh.prototype.getTotalIndices = function () {
  9467. if (!this._geometry) {
  9468. return 0;
  9469. }
  9470. return this._geometry.getTotalIndices();
  9471. };
  9472. Mesh.prototype.getIndices = function () {
  9473. if (!this._geometry) {
  9474. return [];
  9475. }
  9476. return this._geometry.getIndices();
  9477. };
  9478. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9479. get: function () {
  9480. return this._masterMesh !== null && this._masterMesh !== undefined;
  9481. },
  9482. enumerable: true,
  9483. configurable: true
  9484. });
  9485. Mesh.prototype.isReady = function () {
  9486. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9487. return false;
  9488. }
  9489. return _super.prototype.isReady.call(this);
  9490. };
  9491. Mesh.prototype.isDisposed = function () {
  9492. return this._isDisposed;
  9493. };
  9494. // Methods
  9495. Mesh.prototype._preActivate = function () {
  9496. var sceneRenderId = this.getScene().getRenderId();
  9497. if (this._preActivateId == sceneRenderId) {
  9498. return;
  9499. }
  9500. this._preActivateId = sceneRenderId;
  9501. this._visibleInstances = null;
  9502. };
  9503. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9504. if (!this._visibleInstances) {
  9505. this._visibleInstances = {};
  9506. this._visibleInstances.defaultRenderId = renderId;
  9507. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9508. }
  9509. if (!this._visibleInstances[renderId]) {
  9510. this._visibleInstances[renderId] = new Array();
  9511. }
  9512. this._visibleInstances[renderId].push(instance);
  9513. };
  9514. Mesh.prototype.refreshBoundingInfo = function () {
  9515. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9516. if (data) {
  9517. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9518. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9519. }
  9520. if (this.subMeshes) {
  9521. for (var index = 0; index < this.subMeshes.length; index++) {
  9522. this.subMeshes[index].refreshBoundingInfo();
  9523. }
  9524. }
  9525. this._updateBoundingInfo();
  9526. };
  9527. Mesh.prototype._createGlobalSubMesh = function () {
  9528. var totalVertices = this.getTotalVertices();
  9529. if (!totalVertices || !this.getIndices()) {
  9530. return null;
  9531. }
  9532. this.releaseSubMeshes();
  9533. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9534. };
  9535. Mesh.prototype.subdivide = function (count) {
  9536. if (count < 1) {
  9537. return;
  9538. }
  9539. var totalIndices = this.getTotalIndices();
  9540. var subdivisionSize = (totalIndices / count) | 0;
  9541. var offset = 0;
  9542. while (subdivisionSize % 3 != 0) {
  9543. subdivisionSize++;
  9544. }
  9545. this.releaseSubMeshes();
  9546. for (var index = 0; index < count; index++) {
  9547. if (offset >= totalIndices) {
  9548. break;
  9549. }
  9550. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9551. offset += subdivisionSize;
  9552. }
  9553. this.synchronizeInstances();
  9554. };
  9555. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9556. if (kind instanceof Array) {
  9557. var temp = data;
  9558. data = kind;
  9559. kind = temp;
  9560. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9561. }
  9562. if (!this._geometry) {
  9563. var vertexData = new BABYLON.VertexData();
  9564. vertexData.set(data, kind);
  9565. var scene = this.getScene();
  9566. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9567. } else {
  9568. this._geometry.setVerticesData(kind, data, updatable, stride);
  9569. }
  9570. };
  9571. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9572. if (!this._geometry) {
  9573. return;
  9574. }
  9575. if (!makeItUnique) {
  9576. this._geometry.updateVerticesData(kind, data, updateExtends);
  9577. } else {
  9578. this.makeGeometryUnique();
  9579. this.updateVerticesData(kind, data, updateExtends, false);
  9580. }
  9581. };
  9582. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9583. if (!this._geometry) {
  9584. return;
  9585. }
  9586. if (!makeItUnique) {
  9587. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9588. } else {
  9589. this.makeGeometryUnique();
  9590. this.updateVerticesDataDirectly(kind, data, offset, false);
  9591. }
  9592. };
  9593. Mesh.prototype.makeGeometryUnique = function () {
  9594. if (!this._geometry) {
  9595. return;
  9596. }
  9597. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9598. geometry.applyToMesh(this);
  9599. };
  9600. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9601. if (!this._geometry) {
  9602. var vertexData = new BABYLON.VertexData();
  9603. vertexData.indices = indices;
  9604. var scene = this.getScene();
  9605. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9606. } else {
  9607. this._geometry.setIndices(indices, totalVertices);
  9608. }
  9609. };
  9610. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9611. var engine = this.getScene().getEngine();
  9612. // Wireframe
  9613. var indexToBind;
  9614. switch (fillMode) {
  9615. case BABYLON.Material.PointFillMode:
  9616. indexToBind = null;
  9617. break;
  9618. case BABYLON.Material.WireFrameFillMode:
  9619. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9620. break;
  9621. default:
  9622. case BABYLON.Material.TriangleFillMode:
  9623. indexToBind = this._geometry.getIndexBuffer();
  9624. break;
  9625. }
  9626. // VBOs
  9627. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9628. };
  9629. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9630. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9631. return;
  9632. }
  9633. var engine = this.getScene().getEngine();
  9634. switch (fillMode) {
  9635. case BABYLON.Material.PointFillMode:
  9636. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9637. break;
  9638. case BABYLON.Material.WireFrameFillMode:
  9639. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9640. break;
  9641. default:
  9642. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9643. }
  9644. };
  9645. Mesh.prototype.registerBeforeRender = function (func) {
  9646. this._onBeforeRenderCallbacks.push(func);
  9647. };
  9648. Mesh.prototype.unregisterBeforeRender = function (func) {
  9649. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9650. if (index > -1) {
  9651. this._onBeforeRenderCallbacks.splice(index, 1);
  9652. }
  9653. };
  9654. Mesh.prototype.registerAfterRender = function (func) {
  9655. this._onAfterRenderCallbacks.push(func);
  9656. };
  9657. Mesh.prototype.unregisterAfterRender = function (func) {
  9658. var index = this._onAfterRenderCallbacks.indexOf(func);
  9659. if (index > -1) {
  9660. this._onAfterRenderCallbacks.splice(index, 1);
  9661. }
  9662. };
  9663. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9664. var scene = this.getScene();
  9665. this._batchCache.mustReturn = false;
  9666. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9667. this._batchCache.visibleInstances[subMeshId] = null;
  9668. if (this._visibleInstances) {
  9669. var currentRenderId = scene.getRenderId();
  9670. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9671. var selfRenderId = this._renderId;
  9672. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9673. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9674. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9675. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9676. }
  9677. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9678. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9679. this._batchCache.mustReturn = true;
  9680. return this._batchCache;
  9681. }
  9682. if (currentRenderId !== selfRenderId) {
  9683. this._batchCache.renderSelf[subMeshId] = false;
  9684. }
  9685. }
  9686. this._renderIdForInstances[subMeshId] = currentRenderId;
  9687. }
  9688. return this._batchCache;
  9689. };
  9690. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9691. var visibleInstances = batch.visibleInstances[subMesh._id];
  9692. var matricesCount = visibleInstances.length + 1;
  9693. var bufferSize = matricesCount * 16 * 4;
  9694. while (this._instancesBufferSize < bufferSize) {
  9695. this._instancesBufferSize *= 2;
  9696. }
  9697. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9698. if (this._worldMatricesInstancesBuffer) {
  9699. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9700. }
  9701. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9702. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9703. }
  9704. var offset = 0;
  9705. var instancesCount = 0;
  9706. var world = this.getWorldMatrix();
  9707. if (batch.renderSelf[subMesh._id]) {
  9708. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9709. offset += 16;
  9710. instancesCount++;
  9711. }
  9712. if (visibleInstances) {
  9713. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9714. var instance = visibleInstances[instanceIndex];
  9715. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9716. offset += 16;
  9717. instancesCount++;
  9718. }
  9719. }
  9720. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9721. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9722. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9723. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9724. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9725. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9726. this._draw(subMesh, fillMode, instancesCount);
  9727. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9728. };
  9729. Mesh.prototype.render = function (subMesh) {
  9730. var scene = this.getScene();
  9731. // Managing instances
  9732. var batch = this._getInstancesRenderList(subMesh._id);
  9733. if (batch.mustReturn) {
  9734. return;
  9735. }
  9736. // Checking geometry state
  9737. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9738. return;
  9739. }
  9740. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9741. this._onBeforeRenderCallbacks[callbackIndex]();
  9742. }
  9743. var engine = scene.getEngine();
  9744. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9745. // Material
  9746. var effectiveMaterial = subMesh.getMaterial();
  9747. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9748. return;
  9749. }
  9750. // Outline - step 1
  9751. var savedDepthWrite = engine.getDepthWrite();
  9752. if (this.renderOutline) {
  9753. engine.setDepthWrite(false);
  9754. scene.getOutlineRenderer().render(subMesh, batch);
  9755. engine.setDepthWrite(savedDepthWrite);
  9756. }
  9757. effectiveMaterial._preBind();
  9758. var effect = effectiveMaterial.getEffect();
  9759. // Bind
  9760. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9761. this._bind(subMesh, effect, fillMode);
  9762. var world = this.getWorldMatrix();
  9763. effectiveMaterial.bind(world, this);
  9764. // Instances rendering
  9765. if (hardwareInstancedRendering) {
  9766. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9767. } else {
  9768. if (batch.renderSelf[subMesh._id]) {
  9769. // Draw
  9770. this._draw(subMesh, fillMode);
  9771. }
  9772. if (batch.visibleInstances[subMesh._id]) {
  9773. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9774. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9775. // World
  9776. world = instance.getWorldMatrix();
  9777. effectiveMaterial.bindOnlyWorldMatrix(world);
  9778. // Draw
  9779. this._draw(subMesh, fillMode);
  9780. }
  9781. }
  9782. }
  9783. // Unbind
  9784. effectiveMaterial.unbind();
  9785. // Outline - step 2
  9786. if (this.renderOutline && savedDepthWrite) {
  9787. engine.setDepthWrite(true);
  9788. engine.setColorWrite(false);
  9789. scene.getOutlineRenderer().render(subMesh, batch);
  9790. engine.setColorWrite(true);
  9791. }
  9792. // Overlay
  9793. if (this.renderOverlay) {
  9794. var currentMode = engine.getAlphaMode();
  9795. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9796. scene.getOutlineRenderer().render(subMesh, batch, true);
  9797. engine.setAlphaMode(currentMode);
  9798. }
  9799. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9800. this._onAfterRenderCallbacks[callbackIndex]();
  9801. }
  9802. };
  9803. Mesh.prototype.getEmittedParticleSystems = function () {
  9804. var results = new Array();
  9805. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9806. var particleSystem = this.getScene().particleSystems[index];
  9807. if (particleSystem.emitter === this) {
  9808. results.push(particleSystem);
  9809. }
  9810. }
  9811. return results;
  9812. };
  9813. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9814. var results = new Array();
  9815. var descendants = this.getDescendants();
  9816. descendants.push(this);
  9817. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9818. var particleSystem = this.getScene().particleSystems[index];
  9819. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9820. results.push(particleSystem);
  9821. }
  9822. }
  9823. return results;
  9824. };
  9825. Mesh.prototype.getChildren = function () {
  9826. var results = [];
  9827. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9828. var mesh = this.getScene().meshes[index];
  9829. if (mesh.parent == this) {
  9830. results.push(mesh);
  9831. }
  9832. }
  9833. return results;
  9834. };
  9835. Mesh.prototype._checkDelayState = function () {
  9836. var _this = this;
  9837. var that = this;
  9838. var scene = this.getScene();
  9839. if (this._geometry) {
  9840. this._geometry.load(scene);
  9841. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9842. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9843. scene._addPendingData(that);
  9844. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9845. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9846. if (data instanceof ArrayBuffer) {
  9847. _this._delayLoadingFunction(data, _this);
  9848. } else {
  9849. _this._delayLoadingFunction(JSON.parse(data), _this);
  9850. }
  9851. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9852. scene._removePendingData(_this);
  9853. }, function () {
  9854. }, scene.database, getBinaryData);
  9855. }
  9856. };
  9857. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9858. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9859. return false;
  9860. }
  9861. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9862. return false;
  9863. }
  9864. this._checkDelayState();
  9865. return true;
  9866. };
  9867. Mesh.prototype.setMaterialByID = function (id) {
  9868. var materials = this.getScene().materials;
  9869. for (var index = 0; index < materials.length; index++) {
  9870. if (materials[index].id == id) {
  9871. this.material = materials[index];
  9872. return;
  9873. }
  9874. }
  9875. // Multi
  9876. var multiMaterials = this.getScene().multiMaterials;
  9877. for (index = 0; index < multiMaterials.length; index++) {
  9878. if (multiMaterials[index].id == id) {
  9879. this.material = multiMaterials[index];
  9880. return;
  9881. }
  9882. }
  9883. };
  9884. Mesh.prototype.getAnimatables = function () {
  9885. var results = [];
  9886. if (this.material) {
  9887. results.push(this.material);
  9888. }
  9889. if (this.skeleton) {
  9890. results.push(this.skeleton);
  9891. }
  9892. return results;
  9893. };
  9894. // Geometry
  9895. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9896. // Position
  9897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9898. return;
  9899. }
  9900. this._resetPointsArrayCache();
  9901. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9902. var temp = [];
  9903. for (var index = 0; index < data.length; index += 3) {
  9904. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9905. }
  9906. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9907. // Normals
  9908. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9909. return;
  9910. }
  9911. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9912. for (index = 0; index < data.length; index += 3) {
  9913. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9914. }
  9915. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9916. };
  9917. // Cache
  9918. Mesh.prototype._resetPointsArrayCache = function () {
  9919. this._positions = null;
  9920. };
  9921. Mesh.prototype._generatePointsArray = function () {
  9922. if (this._positions)
  9923. return true;
  9924. this._positions = [];
  9925. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9926. if (!data) {
  9927. return false;
  9928. }
  9929. for (var index = 0; index < data.length; index += 3) {
  9930. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9931. }
  9932. return true;
  9933. };
  9934. // Clone
  9935. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9936. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9937. };
  9938. // Dispose
  9939. Mesh.prototype.dispose = function (doNotRecurse) {
  9940. if (this._geometry) {
  9941. this._geometry.releaseForMesh(this, true);
  9942. }
  9943. // Instances
  9944. if (this._worldMatricesInstancesBuffer) {
  9945. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9946. this._worldMatricesInstancesBuffer = null;
  9947. }
  9948. while (this.instances.length) {
  9949. this.instances[0].dispose();
  9950. }
  9951. _super.prototype.dispose.call(this, doNotRecurse);
  9952. };
  9953. // Geometric tools
  9954. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9955. var _this = this;
  9956. var scene = this.getScene();
  9957. var onload = function (img) {
  9958. // Getting height map data
  9959. var canvas = document.createElement("canvas");
  9960. var context = canvas.getContext("2d");
  9961. var heightMapWidth = img.width;
  9962. var heightMapHeight = img.height;
  9963. canvas.width = heightMapWidth;
  9964. canvas.height = heightMapHeight;
  9965. context.drawImage(img, 0, 0);
  9966. // Create VertexData from map data
  9967. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9968. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9969. };
  9970. BABYLON.Tools.LoadImage(url, onload, function () {
  9971. }, scene.database);
  9972. };
  9973. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9974. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9975. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9976. return;
  9977. }
  9978. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9979. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9980. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9981. var position = BABYLON.Vector3.Zero();
  9982. var normal = BABYLON.Vector3.Zero();
  9983. var uv = BABYLON.Vector2.Zero();
  9984. for (var index = 0; index < positions.length; index += 3) {
  9985. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9986. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9987. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9988. // Compute height
  9989. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9990. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9991. var pos = (u + v * heightMapWidth) * 4;
  9992. var r = buffer[pos] / 255.0;
  9993. var g = buffer[pos + 1] / 255.0;
  9994. var b = buffer[pos + 2] / 255.0;
  9995. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9996. normal.normalize();
  9997. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9998. position = position.add(normal);
  9999. position.toArray(positions, index);
  10000. }
  10001. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10002. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10003. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10004. };
  10005. Mesh.prototype.convertToFlatShadedMesh = function () {
  10006. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10007. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10008. var kinds = this.getVerticesDataKinds();
  10009. var vbs = [];
  10010. var data = [];
  10011. var newdata = [];
  10012. var updatableNormals = false;
  10013. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10014. var kind = kinds[kindIndex];
  10015. var vertexBuffer = this.getVertexBuffer(kind);
  10016. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10017. updatableNormals = vertexBuffer.isUpdatable();
  10018. kinds.splice(kindIndex, 1);
  10019. kindIndex--;
  10020. continue;
  10021. }
  10022. vbs[kind] = vertexBuffer;
  10023. data[kind] = vbs[kind].getData();
  10024. newdata[kind] = [];
  10025. }
  10026. // Save previous submeshes
  10027. var previousSubmeshes = this.subMeshes.slice(0);
  10028. var indices = this.getIndices();
  10029. var totalIndices = this.getTotalIndices();
  10030. for (index = 0; index < totalIndices; index++) {
  10031. var vertexIndex = indices[index];
  10032. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10033. kind = kinds[kindIndex];
  10034. var stride = vbs[kind].getStrideSize();
  10035. for (var offset = 0; offset < stride; offset++) {
  10036. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10037. }
  10038. }
  10039. }
  10040. // Updating faces & normal
  10041. var normals = [];
  10042. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10043. for (var index = 0; index < totalIndices; index += 3) {
  10044. indices[index] = index;
  10045. indices[index + 1] = index + 1;
  10046. indices[index + 2] = index + 2;
  10047. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10048. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10049. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10050. var p1p2 = p1.subtract(p2);
  10051. var p3p2 = p3.subtract(p2);
  10052. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10053. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10054. normals.push(normal.x);
  10055. normals.push(normal.y);
  10056. normals.push(normal.z);
  10057. }
  10058. }
  10059. this.setIndices(indices);
  10060. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10061. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10062. kind = kinds[kindIndex];
  10063. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10064. }
  10065. // Updating submeshes
  10066. this.releaseSubMeshes();
  10067. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10068. var previousOne = previousSubmeshes[submeshIndex];
  10069. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10070. }
  10071. this.synchronizeInstances();
  10072. };
  10073. // Instances
  10074. Mesh.prototype.createInstance = function (name) {
  10075. return new BABYLON.InstancedMesh(name, this);
  10076. };
  10077. Mesh.prototype.synchronizeInstances = function () {
  10078. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10079. var instance = this.instances[instanceIndex];
  10080. instance._syncSubMeshes();
  10081. }
  10082. };
  10083. /**
  10084. * Simplify the mesh according to the given array of settings.
  10085. * Function will return immediately and will simplify async.
  10086. * @param settings a collection of simplification settings.
  10087. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10088. * @param type the type of simplification to run.
  10089. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10090. */
  10091. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10092. var _this = this;
  10093. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  10094. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  10095. var getSimplifier = function () {
  10096. switch (type) {
  10097. case 0 /* QUADRATIC */:
  10098. default:
  10099. return new BABYLON.QuadraticErrorSimplification(_this);
  10100. }
  10101. };
  10102. if (parallelProcessing) {
  10103. //parallel simplifier
  10104. settings.forEach(function (setting) {
  10105. var simplifier = getSimplifier();
  10106. simplifier.simplify(setting, function (newMesh) {
  10107. _this.addLODLevel(setting.distance, newMesh);
  10108. //check if it is the last
  10109. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10110. //all done, run the success callback.
  10111. successCallback();
  10112. }
  10113. });
  10114. });
  10115. } else {
  10116. //single simplifier.
  10117. var simplifier = getSimplifier();
  10118. var runDecimation = function (setting, callback) {
  10119. simplifier.simplify(setting, function (newMesh) {
  10120. _this.addLODLevel(setting.distance, newMesh);
  10121. //run the next quality level
  10122. callback();
  10123. });
  10124. };
  10125. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10126. runDecimation(settings[loop.index], function () {
  10127. loop.executeNext();
  10128. });
  10129. }, function () {
  10130. //execution ended, run the success callback.
  10131. successCallback();
  10132. });
  10133. }
  10134. };
  10135. // Statics
  10136. Mesh.CreateBox = function (name, size, scene, updatable) {
  10137. var box = new BABYLON.Mesh(name, scene);
  10138. var vertexData = BABYLON.VertexData.CreateBox(size);
  10139. vertexData.applyToMesh(box, updatable);
  10140. return box;
  10141. };
  10142. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10143. var sphere = new BABYLON.Mesh(name, scene);
  10144. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10145. vertexData.applyToMesh(sphere, updatable);
  10146. return sphere;
  10147. };
  10148. // Cylinder and cone (Code inspired by SharpDX.org)
  10149. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10150. // subdivisions is a new parameter, we need to support old signature
  10151. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10152. if (scene !== undefined) {
  10153. updatable = scene;
  10154. }
  10155. scene = subdivisions;
  10156. subdivisions = 1;
  10157. }
  10158. var cylinder = new BABYLON.Mesh(name, scene);
  10159. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10160. vertexData.applyToMesh(cylinder, updatable);
  10161. return cylinder;
  10162. };
  10163. // Torus (Code from SharpDX.org)
  10164. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10165. var torus = new BABYLON.Mesh(name, scene);
  10166. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10167. vertexData.applyToMesh(torus, updatable);
  10168. return torus;
  10169. };
  10170. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10171. var torusKnot = new BABYLON.Mesh(name, scene);
  10172. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10173. vertexData.applyToMesh(torusKnot, updatable);
  10174. return torusKnot;
  10175. };
  10176. // Lines
  10177. Mesh.CreateLines = function (name, points, scene, updatable) {
  10178. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10179. var vertexData = BABYLON.VertexData.CreateLines(points);
  10180. vertexData.applyToMesh(lines, updatable);
  10181. return lines;
  10182. };
  10183. // Plane & ground
  10184. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10185. var plane = new BABYLON.Mesh(name, scene);
  10186. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10187. vertexData.applyToMesh(plane, updatable);
  10188. return plane;
  10189. };
  10190. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10191. var ground = new BABYLON.GroundMesh(name, scene);
  10192. ground._setReady(false);
  10193. ground._subdivisions = subdivisions;
  10194. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10195. vertexData.applyToMesh(ground, updatable);
  10196. ground._setReady(true);
  10197. return ground;
  10198. };
  10199. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10200. var tiledGround = new BABYLON.Mesh(name, scene);
  10201. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10202. vertexData.applyToMesh(tiledGround, updatable);
  10203. return tiledGround;
  10204. };
  10205. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10206. var ground = new BABYLON.GroundMesh(name, scene);
  10207. ground._subdivisions = subdivisions;
  10208. ground._setReady(false);
  10209. var onload = function (img) {
  10210. // Getting height map data
  10211. var canvas = document.createElement("canvas");
  10212. var context = canvas.getContext("2d");
  10213. var heightMapWidth = img.width;
  10214. var heightMapHeight = img.height;
  10215. canvas.width = heightMapWidth;
  10216. canvas.height = heightMapHeight;
  10217. context.drawImage(img, 0, 0);
  10218. // Create VertexData from map data
  10219. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10220. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10221. vertexData.applyToMesh(ground, updatable);
  10222. ground._setReady(true);
  10223. };
  10224. BABYLON.Tools.LoadImage(url, onload, function () {
  10225. }, scene.database);
  10226. return ground;
  10227. };
  10228. // Tools
  10229. Mesh.MinMax = function (meshes) {
  10230. var minVector = null;
  10231. var maxVector = null;
  10232. for (var i in meshes) {
  10233. var mesh = meshes[i];
  10234. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10235. if (!minVector) {
  10236. minVector = boundingBox.minimumWorld;
  10237. maxVector = boundingBox.maximumWorld;
  10238. continue;
  10239. }
  10240. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10241. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10242. }
  10243. return {
  10244. min: minVector,
  10245. max: maxVector
  10246. };
  10247. };
  10248. Mesh.Center = function (meshesOrMinMaxVector) {
  10249. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10250. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10251. };
  10252. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10253. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10254. var source = meshes[0];
  10255. var material = source.material;
  10256. var scene = source.getScene();
  10257. if (!allow32BitsIndices) {
  10258. var totalVertices = 0;
  10259. for (var index = 0; index < meshes.length; index++) {
  10260. totalVertices += meshes[index].getTotalVertices();
  10261. if (totalVertices > 65536) {
  10262. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10263. return null;
  10264. }
  10265. }
  10266. }
  10267. // Merge
  10268. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10269. vertexData.transform(source.getWorldMatrix());
  10270. for (index = 1; index < meshes.length; index++) {
  10271. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10272. otherVertexData.transform(meshes[index].getWorldMatrix());
  10273. vertexData.merge(otherVertexData);
  10274. }
  10275. var newMesh = new Mesh(source.name + "_merged", scene);
  10276. vertexData.applyToMesh(newMesh);
  10277. // Setting properties
  10278. newMesh.material = material;
  10279. newMesh.checkCollisions = source.checkCollisions;
  10280. // Cleaning
  10281. if (disposeSource) {
  10282. for (index = 0; index < meshes.length; index++) {
  10283. meshes[index].dispose();
  10284. }
  10285. }
  10286. return newMesh;
  10287. };
  10288. return Mesh;
  10289. })(BABYLON.AbstractMesh);
  10290. BABYLON.Mesh = Mesh;
  10291. })(BABYLON || (BABYLON = {}));
  10292. //# sourceMappingURL=babylon.mesh.js.map
  10293. var BABYLON;
  10294. (function (BABYLON) {
  10295. var GroundMesh = (function (_super) {
  10296. __extends(GroundMesh, _super);
  10297. function GroundMesh(name, scene) {
  10298. _super.call(this, name, scene);
  10299. this.generateOctree = false;
  10300. this._worldInverse = new BABYLON.Matrix();
  10301. }
  10302. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10303. get: function () {
  10304. return this._subdivisions;
  10305. },
  10306. enumerable: true,
  10307. configurable: true
  10308. });
  10309. GroundMesh.prototype.optimize = function (chunksCount) {
  10310. this.subdivide(this._subdivisions);
  10311. this.createOrUpdateSubmeshesOctree(32);
  10312. };
  10313. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10314. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10315. this.getWorldMatrix().invertToRef(this._worldInverse);
  10316. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10317. var pickInfo = this.intersects(ray);
  10318. if (pickInfo.hit) {
  10319. return pickInfo.pickedPoint.y;
  10320. }
  10321. return 0;
  10322. };
  10323. return GroundMesh;
  10324. })(BABYLON.Mesh);
  10325. BABYLON.GroundMesh = GroundMesh;
  10326. })(BABYLON || (BABYLON = {}));
  10327. //# sourceMappingURL=babylon.groundMesh.js.map
  10328. var BABYLON;
  10329. (function (BABYLON) {
  10330. var InstancedMesh = (function (_super) {
  10331. __extends(InstancedMesh, _super);
  10332. function InstancedMesh(name, source) {
  10333. _super.call(this, name, source.getScene());
  10334. source.instances.push(this);
  10335. this._sourceMesh = source;
  10336. this.position.copyFrom(source.position);
  10337. this.rotation.copyFrom(source.rotation);
  10338. this.scaling.copyFrom(source.scaling);
  10339. if (source.rotationQuaternion) {
  10340. this.rotationQuaternion = source.rotationQuaternion.clone();
  10341. }
  10342. this.infiniteDistance = source.infiniteDistance;
  10343. this.setPivotMatrix(source.getPivotMatrix());
  10344. this.refreshBoundingInfo();
  10345. this._syncSubMeshes();
  10346. }
  10347. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10348. // Methods
  10349. get: function () {
  10350. return this._sourceMesh.receiveShadows;
  10351. },
  10352. enumerable: true,
  10353. configurable: true
  10354. });
  10355. Object.defineProperty(InstancedMesh.prototype, "material", {
  10356. get: function () {
  10357. return this._sourceMesh.material;
  10358. },
  10359. enumerable: true,
  10360. configurable: true
  10361. });
  10362. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10363. get: function () {
  10364. return this._sourceMesh.visibility;
  10365. },
  10366. enumerable: true,
  10367. configurable: true
  10368. });
  10369. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10370. get: function () {
  10371. return this._sourceMesh.skeleton;
  10372. },
  10373. enumerable: true,
  10374. configurable: true
  10375. });
  10376. InstancedMesh.prototype.getTotalVertices = function () {
  10377. return this._sourceMesh.getTotalVertices();
  10378. };
  10379. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10380. get: function () {
  10381. return this._sourceMesh;
  10382. },
  10383. enumerable: true,
  10384. configurable: true
  10385. });
  10386. InstancedMesh.prototype.getVerticesData = function (kind) {
  10387. return this._sourceMesh.getVerticesData(kind);
  10388. };
  10389. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10390. return this._sourceMesh.isVerticesDataPresent(kind);
  10391. };
  10392. InstancedMesh.prototype.getIndices = function () {
  10393. return this._sourceMesh.getIndices();
  10394. };
  10395. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10396. get: function () {
  10397. return this._sourceMesh._positions;
  10398. },
  10399. enumerable: true,
  10400. configurable: true
  10401. });
  10402. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10403. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10404. if (data) {
  10405. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10406. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10407. }
  10408. this._updateBoundingInfo();
  10409. };
  10410. InstancedMesh.prototype._preActivate = function () {
  10411. if (this._currentLOD) {
  10412. this._currentLOD._preActivate();
  10413. }
  10414. };
  10415. InstancedMesh.prototype._activate = function (renderId) {
  10416. if (this._currentLOD) {
  10417. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10418. }
  10419. };
  10420. InstancedMesh.prototype.getLOD = function (camera) {
  10421. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10422. if (this._currentLOD === this.sourceMesh) {
  10423. return this;
  10424. }
  10425. return this._currentLOD;
  10426. };
  10427. InstancedMesh.prototype._syncSubMeshes = function () {
  10428. this.releaseSubMeshes();
  10429. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10430. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10431. }
  10432. };
  10433. InstancedMesh.prototype._generatePointsArray = function () {
  10434. return this._sourceMesh._generatePointsArray();
  10435. };
  10436. // Clone
  10437. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10438. var result = this._sourceMesh.createInstance(name);
  10439. // Deep copy
  10440. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10441. // Bounding info
  10442. this.refreshBoundingInfo();
  10443. // Parent
  10444. if (newParent) {
  10445. result.parent = newParent;
  10446. }
  10447. if (!doNotCloneChildren) {
  10448. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10449. var mesh = this.getScene().meshes[index];
  10450. if (mesh.parent == this) {
  10451. mesh.clone(mesh.name, result);
  10452. }
  10453. }
  10454. }
  10455. result.computeWorldMatrix(true);
  10456. return result;
  10457. };
  10458. // Dispoe
  10459. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10460. // Remove from mesh
  10461. var index = this._sourceMesh.instances.indexOf(this);
  10462. this._sourceMesh.instances.splice(index, 1);
  10463. _super.prototype.dispose.call(this, doNotRecurse);
  10464. };
  10465. return InstancedMesh;
  10466. })(BABYLON.AbstractMesh);
  10467. BABYLON.InstancedMesh = InstancedMesh;
  10468. })(BABYLON || (BABYLON = {}));
  10469. //# sourceMappingURL=babylon.instancedMesh.js.map
  10470. var BABYLON;
  10471. (function (BABYLON) {
  10472. var SubMesh = (function () {
  10473. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10474. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10475. this.materialIndex = materialIndex;
  10476. this.verticesStart = verticesStart;
  10477. this.verticesCount = verticesCount;
  10478. this.indexStart = indexStart;
  10479. this.indexCount = indexCount;
  10480. this._renderId = 0;
  10481. this._mesh = mesh;
  10482. this._renderingMesh = renderingMesh || mesh;
  10483. mesh.subMeshes.push(this);
  10484. this._id = mesh.subMeshes.length - 1;
  10485. if (createBoundingBox) {
  10486. this.refreshBoundingInfo();
  10487. }
  10488. }
  10489. SubMesh.prototype.getBoundingInfo = function () {
  10490. return this._boundingInfo;
  10491. };
  10492. SubMesh.prototype.getMesh = function () {
  10493. return this._mesh;
  10494. };
  10495. SubMesh.prototype.getRenderingMesh = function () {
  10496. return this._renderingMesh;
  10497. };
  10498. SubMesh.prototype.getMaterial = function () {
  10499. var rootMaterial = this._renderingMesh.material;
  10500. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10501. var multiMaterial = rootMaterial;
  10502. return multiMaterial.getSubMaterial(this.materialIndex);
  10503. }
  10504. if (!rootMaterial) {
  10505. return this._mesh.getScene().defaultMaterial;
  10506. }
  10507. return rootMaterial;
  10508. };
  10509. // Methods
  10510. SubMesh.prototype.refreshBoundingInfo = function () {
  10511. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10512. if (!data) {
  10513. this._boundingInfo = this._mesh._boundingInfo;
  10514. return;
  10515. }
  10516. var indices = this._renderingMesh.getIndices();
  10517. var extend;
  10518. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10519. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10520. } else {
  10521. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10522. }
  10523. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10524. };
  10525. SubMesh.prototype._checkCollision = function (collider) {
  10526. return this._boundingInfo._checkCollision(collider);
  10527. };
  10528. SubMesh.prototype.updateBoundingInfo = function (world) {
  10529. if (!this._boundingInfo) {
  10530. this.refreshBoundingInfo();
  10531. }
  10532. this._boundingInfo._update(world);
  10533. };
  10534. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10535. return this._boundingInfo.isInFrustum(frustumPlanes);
  10536. };
  10537. SubMesh.prototype.render = function () {
  10538. this._renderingMesh.render(this);
  10539. };
  10540. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10541. if (!this._linesIndexBuffer) {
  10542. var linesIndices = [];
  10543. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10544. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10545. }
  10546. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10547. this.linesIndexCount = linesIndices.length;
  10548. }
  10549. return this._linesIndexBuffer;
  10550. };
  10551. SubMesh.prototype.canIntersects = function (ray) {
  10552. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10553. };
  10554. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10555. var intersectInfo = null;
  10556. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10557. var p0 = positions[indices[index]];
  10558. var p1 = positions[indices[index + 1]];
  10559. var p2 = positions[indices[index + 2]];
  10560. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10561. if (currentIntersectInfo) {
  10562. if (currentIntersectInfo.distance < 0) {
  10563. continue;
  10564. }
  10565. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10566. intersectInfo = currentIntersectInfo;
  10567. intersectInfo.faceId = index / 3;
  10568. if (fastCheck) {
  10569. break;
  10570. }
  10571. }
  10572. }
  10573. }
  10574. return intersectInfo;
  10575. };
  10576. // Clone
  10577. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10578. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10579. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10580. return result;
  10581. };
  10582. // Dispose
  10583. SubMesh.prototype.dispose = function () {
  10584. if (this._linesIndexBuffer) {
  10585. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10586. this._linesIndexBuffer = null;
  10587. }
  10588. // Remove from mesh
  10589. var index = this._mesh.subMeshes.indexOf(this);
  10590. this._mesh.subMeshes.splice(index, 1);
  10591. };
  10592. // Statics
  10593. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10594. var minVertexIndex = Number.MAX_VALUE;
  10595. var maxVertexIndex = -Number.MAX_VALUE;
  10596. renderingMesh = renderingMesh || mesh;
  10597. var indices = renderingMesh.getIndices();
  10598. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10599. var vertexIndex = indices[index];
  10600. if (vertexIndex < minVertexIndex)
  10601. minVertexIndex = vertexIndex;
  10602. if (vertexIndex > maxVertexIndex)
  10603. maxVertexIndex = vertexIndex;
  10604. }
  10605. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10606. };
  10607. return SubMesh;
  10608. })();
  10609. BABYLON.SubMesh = SubMesh;
  10610. })(BABYLON || (BABYLON = {}));
  10611. //# sourceMappingURL=babylon.subMesh.js.map
  10612. var BABYLON;
  10613. (function (BABYLON) {
  10614. var BaseTexture = (function () {
  10615. function BaseTexture(scene) {
  10616. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10617. this.hasAlpha = false;
  10618. this.getAlphaFromRGB = false;
  10619. this.level = 1;
  10620. this.isCube = false;
  10621. this.isRenderTarget = false;
  10622. this.animations = new Array();
  10623. this.coordinatesIndex = 0;
  10624. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10625. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10626. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10627. this.anisotropicFilteringLevel = 4;
  10628. this._scene = scene;
  10629. this._scene.textures.push(this);
  10630. }
  10631. BaseTexture.prototype.getScene = function () {
  10632. return this._scene;
  10633. };
  10634. BaseTexture.prototype.getTextureMatrix = function () {
  10635. return null;
  10636. };
  10637. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10638. return null;
  10639. };
  10640. BaseTexture.prototype.getInternalTexture = function () {
  10641. return this._texture;
  10642. };
  10643. BaseTexture.prototype.isReady = function () {
  10644. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10645. return true;
  10646. }
  10647. if (this._texture) {
  10648. return this._texture.isReady;
  10649. }
  10650. return false;
  10651. };
  10652. BaseTexture.prototype.getSize = function () {
  10653. if (this._texture._width) {
  10654. return { width: this._texture._width, height: this._texture._height };
  10655. }
  10656. if (this._texture._size) {
  10657. return { width: this._texture._size, height: this._texture._size };
  10658. }
  10659. return { width: 0, height: 0 };
  10660. };
  10661. BaseTexture.prototype.getBaseSize = function () {
  10662. if (!this.isReady())
  10663. return { width: 0, height: 0 };
  10664. if (this._texture._size) {
  10665. return { width: this._texture._size, height: this._texture._size };
  10666. }
  10667. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10668. };
  10669. BaseTexture.prototype.scale = function (ratio) {
  10670. };
  10671. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10672. get: function () {
  10673. return false;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10679. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10680. for (var index = 0; index < texturesCache.length; index++) {
  10681. var texturesCacheEntry = texturesCache[index];
  10682. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10683. texturesCache.splice(index, 1);
  10684. return;
  10685. }
  10686. }
  10687. };
  10688. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10689. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10690. for (var index = 0; index < texturesCache.length; index++) {
  10691. var texturesCacheEntry = texturesCache[index];
  10692. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10693. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10694. texturesCacheEntry.references++;
  10695. return texturesCacheEntry;
  10696. }
  10697. }
  10698. }
  10699. return null;
  10700. };
  10701. BaseTexture.prototype.delayLoad = function () {
  10702. };
  10703. BaseTexture.prototype.releaseInternalTexture = function () {
  10704. if (!this._texture) {
  10705. return;
  10706. }
  10707. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10708. this._texture.references--;
  10709. // Final reference ?
  10710. if (this._texture.references === 0) {
  10711. var index = texturesCache.indexOf(this._texture);
  10712. texturesCache.splice(index, 1);
  10713. this._scene.getEngine()._releaseTexture(this._texture);
  10714. delete this._texture;
  10715. }
  10716. };
  10717. BaseTexture.prototype.clone = function () {
  10718. return null;
  10719. };
  10720. BaseTexture.prototype.dispose = function () {
  10721. // Remove from scene
  10722. var index = this._scene.textures.indexOf(this);
  10723. if (index >= 0) {
  10724. this._scene.textures.splice(index, 1);
  10725. }
  10726. if (this._texture === undefined) {
  10727. return;
  10728. }
  10729. this.releaseInternalTexture();
  10730. // Callback
  10731. if (this.onDispose) {
  10732. this.onDispose();
  10733. }
  10734. };
  10735. return BaseTexture;
  10736. })();
  10737. BABYLON.BaseTexture = BaseTexture;
  10738. })(BABYLON || (BABYLON = {}));
  10739. //# sourceMappingURL=babylon.baseTexture.js.map
  10740. var BABYLON;
  10741. (function (BABYLON) {
  10742. var RenderingGroup = (function () {
  10743. function RenderingGroup(index, scene) {
  10744. this.index = index;
  10745. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10746. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10747. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10748. this._scene = scene;
  10749. }
  10750. RenderingGroup.prototype.render = function (customRenderFunction) {
  10751. if (customRenderFunction) {
  10752. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10753. return true;
  10754. }
  10755. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10756. return false;
  10757. }
  10758. var engine = this._scene.getEngine();
  10759. // Opaque
  10760. var subIndex;
  10761. var submesh;
  10762. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10763. submesh = this._opaqueSubMeshes.data[subIndex];
  10764. submesh.render();
  10765. }
  10766. // Alpha test
  10767. engine.setAlphaTesting(true);
  10768. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10769. submesh = this._alphaTestSubMeshes.data[subIndex];
  10770. submesh.render();
  10771. }
  10772. engine.setAlphaTesting(false);
  10773. // Transparent
  10774. if (this._transparentSubMeshes.length) {
  10775. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10776. submesh = this._transparentSubMeshes.data[subIndex];
  10777. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10778. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10779. }
  10780. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10781. sortedArray.sort(function (a, b) {
  10782. // Alpha index first
  10783. if (a._alphaIndex > b._alphaIndex) {
  10784. return 1;
  10785. }
  10786. if (a._alphaIndex < b._alphaIndex) {
  10787. return -1;
  10788. }
  10789. // Then distance to camera
  10790. if (a._distanceToCamera < b._distanceToCamera) {
  10791. return 1;
  10792. }
  10793. if (a._distanceToCamera > b._distanceToCamera) {
  10794. return -1;
  10795. }
  10796. return 0;
  10797. });
  10798. // Rendering
  10799. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10800. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10801. submesh = sortedArray[subIndex];
  10802. submesh.render();
  10803. }
  10804. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10805. }
  10806. return true;
  10807. };
  10808. RenderingGroup.prototype.prepare = function () {
  10809. this._opaqueSubMeshes.reset();
  10810. this._transparentSubMeshes.reset();
  10811. this._alphaTestSubMeshes.reset();
  10812. };
  10813. RenderingGroup.prototype.dispatch = function (subMesh) {
  10814. var material = subMesh.getMaterial();
  10815. var mesh = subMesh.getMesh();
  10816. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10817. this._transparentSubMeshes.push(subMesh);
  10818. } else if (material.needAlphaTesting()) {
  10819. this._alphaTestSubMeshes.push(subMesh);
  10820. } else {
  10821. this._opaqueSubMeshes.push(subMesh); // Opaque
  10822. }
  10823. };
  10824. return RenderingGroup;
  10825. })();
  10826. BABYLON.RenderingGroup = RenderingGroup;
  10827. })(BABYLON || (BABYLON = {}));
  10828. //# sourceMappingURL=babylon.renderingGroup.js.map
  10829. var BABYLON;
  10830. (function (BABYLON) {
  10831. var RenderingManager = (function () {
  10832. function RenderingManager(scene) {
  10833. this._renderingGroups = new Array();
  10834. this._scene = scene;
  10835. }
  10836. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10837. if (this._scene._activeParticleSystems.length === 0) {
  10838. return;
  10839. }
  10840. // Particles
  10841. var beforeParticlesDate = BABYLON.Tools.Now;
  10842. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10843. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10844. if (particleSystem.renderingGroupId !== index) {
  10845. continue;
  10846. }
  10847. this._clearDepthBuffer();
  10848. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10849. this._scene._activeParticles += particleSystem.render();
  10850. }
  10851. }
  10852. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10853. };
  10854. RenderingManager.prototype._renderSprites = function (index) {
  10855. if (this._scene.spriteManagers.length === 0) {
  10856. return;
  10857. }
  10858. // Sprites
  10859. var beforeSpritessDate = BABYLON.Tools.Now;
  10860. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10861. var spriteManager = this._scene.spriteManagers[id];
  10862. if (spriteManager.renderingGroupId === index) {
  10863. this._clearDepthBuffer();
  10864. spriteManager.render();
  10865. }
  10866. }
  10867. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10868. };
  10869. RenderingManager.prototype._clearDepthBuffer = function () {
  10870. if (this._depthBufferAlreadyCleaned) {
  10871. return;
  10872. }
  10873. this._scene.getEngine().clear(0, false, true);
  10874. this._depthBufferAlreadyCleaned = true;
  10875. };
  10876. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10877. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10878. this._depthBufferAlreadyCleaned = false;
  10879. var renderingGroup = this._renderingGroups[index];
  10880. if (renderingGroup) {
  10881. this._clearDepthBuffer();
  10882. if (!renderingGroup.render(customRenderFunction)) {
  10883. this._renderingGroups.splice(index, 1);
  10884. }
  10885. }
  10886. this._renderSprites(index);
  10887. if (renderParticles) {
  10888. this._renderParticles(index, activeMeshes);
  10889. }
  10890. }
  10891. };
  10892. RenderingManager.prototype.reset = function () {
  10893. for (var index in this._renderingGroups) {
  10894. var renderingGroup = this._renderingGroups[index];
  10895. renderingGroup.prepare();
  10896. }
  10897. };
  10898. RenderingManager.prototype.dispatch = function (subMesh) {
  10899. var mesh = subMesh.getMesh();
  10900. var renderingGroupId = mesh.renderingGroupId || 0;
  10901. if (!this._renderingGroups[renderingGroupId]) {
  10902. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10903. }
  10904. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10905. };
  10906. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10907. return RenderingManager;
  10908. })();
  10909. BABYLON.RenderingManager = RenderingManager;
  10910. })(BABYLON || (BABYLON = {}));
  10911. //# sourceMappingURL=babylon.renderingManager.js.map
  10912. var BABYLON;
  10913. (function (BABYLON) {
  10914. var Texture = (function (_super) {
  10915. __extends(Texture, _super);
  10916. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10917. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10918. if (typeof onLoad === "undefined") { onLoad = null; }
  10919. if (typeof onError === "undefined") { onError = null; }
  10920. if (typeof buffer === "undefined") { buffer = null; }
  10921. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10922. _super.call(this, scene);
  10923. this.uOffset = 0;
  10924. this.vOffset = 0;
  10925. this.uScale = 1.0;
  10926. this.vScale = 1.0;
  10927. this.uAng = 0;
  10928. this.vAng = 0;
  10929. this.wAng = 0;
  10930. this.name = url;
  10931. this.url = url;
  10932. this._noMipmap = noMipmap;
  10933. this._invertY = invertY;
  10934. this._samplingMode = samplingMode;
  10935. this._buffer = buffer;
  10936. this._deleteBuffer = deleteBuffer;
  10937. if (!url) {
  10938. return;
  10939. }
  10940. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10941. if (!this._texture) {
  10942. if (!scene.useDelayedTextureLoading) {
  10943. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10944. if (deleteBuffer) {
  10945. delete this._buffer;
  10946. }
  10947. } else {
  10948. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10949. }
  10950. }
  10951. }
  10952. Texture.prototype.delayLoad = function () {
  10953. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10954. return;
  10955. }
  10956. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10957. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10958. if (!this._texture) {
  10959. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10960. if (this._deleteBuffer) {
  10961. delete this._buffer;
  10962. }
  10963. }
  10964. };
  10965. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10966. x -= this.uOffset + 0.5;
  10967. y -= this.vOffset + 0.5;
  10968. z -= 0.5;
  10969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10970. t.x *= this.uScale;
  10971. t.y *= this.vScale;
  10972. t.x += 0.5;
  10973. t.y += 0.5;
  10974. t.z += 0.5;
  10975. };
  10976. Texture.prototype.getTextureMatrix = function () {
  10977. 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) {
  10978. return this._cachedTextureMatrix;
  10979. }
  10980. this._cachedUOffset = this.uOffset;
  10981. this._cachedVOffset = this.vOffset;
  10982. this._cachedUScale = this.uScale;
  10983. this._cachedVScale = this.vScale;
  10984. this._cachedUAng = this.uAng;
  10985. this._cachedVAng = this.vAng;
  10986. this._cachedWAng = this.wAng;
  10987. if (!this._cachedTextureMatrix) {
  10988. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10989. this._rowGenerationMatrix = new BABYLON.Matrix();
  10990. this._t0 = BABYLON.Vector3.Zero();
  10991. this._t1 = BABYLON.Vector3.Zero();
  10992. this._t2 = BABYLON.Vector3.Zero();
  10993. }
  10994. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10995. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10996. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10997. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10998. this._t1.subtractInPlace(this._t0);
  10999. this._t2.subtractInPlace(this._t0);
  11000. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11001. this._cachedTextureMatrix.m[0] = this._t1.x;
  11002. this._cachedTextureMatrix.m[1] = this._t1.y;
  11003. this._cachedTextureMatrix.m[2] = this._t1.z;
  11004. this._cachedTextureMatrix.m[4] = this._t2.x;
  11005. this._cachedTextureMatrix.m[5] = this._t2.y;
  11006. this._cachedTextureMatrix.m[6] = this._t2.z;
  11007. this._cachedTextureMatrix.m[8] = this._t0.x;
  11008. this._cachedTextureMatrix.m[9] = this._t0.y;
  11009. this._cachedTextureMatrix.m[10] = this._t0.z;
  11010. return this._cachedTextureMatrix;
  11011. };
  11012. Texture.prototype.getReflectionTextureMatrix = function () {
  11013. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11014. return this._cachedTextureMatrix;
  11015. }
  11016. if (!this._cachedTextureMatrix) {
  11017. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11018. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11019. }
  11020. this._cachedCoordinatesMode = this.coordinatesMode;
  11021. switch (this.coordinatesMode) {
  11022. case BABYLON.Texture.SPHERICAL_MODE:
  11023. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11024. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11025. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11026. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11027. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11028. break;
  11029. case BABYLON.Texture.PLANAR_MODE:
  11030. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11031. this._cachedTextureMatrix[0] = this.uScale;
  11032. this._cachedTextureMatrix[5] = this.vScale;
  11033. this._cachedTextureMatrix[12] = this.uOffset;
  11034. this._cachedTextureMatrix[13] = this.vOffset;
  11035. break;
  11036. case BABYLON.Texture.PROJECTION_MODE:
  11037. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11038. this._projectionModeMatrix.m[0] = 0.5;
  11039. this._projectionModeMatrix.m[5] = -0.5;
  11040. this._projectionModeMatrix.m[10] = 0.0;
  11041. this._projectionModeMatrix.m[12] = 0.5;
  11042. this._projectionModeMatrix.m[13] = 0.5;
  11043. this._projectionModeMatrix.m[14] = 1.0;
  11044. this._projectionModeMatrix.m[15] = 1.0;
  11045. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11046. break;
  11047. default:
  11048. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11049. break;
  11050. }
  11051. return this._cachedTextureMatrix;
  11052. };
  11053. Texture.prototype.clone = function () {
  11054. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  11055. // Base texture
  11056. newTexture.hasAlpha = this.hasAlpha;
  11057. newTexture.level = this.level;
  11058. newTexture.wrapU = this.wrapU;
  11059. newTexture.wrapV = this.wrapV;
  11060. newTexture.coordinatesIndex = this.coordinatesIndex;
  11061. newTexture.coordinatesMode = this.coordinatesMode;
  11062. // Texture
  11063. newTexture.uOffset = this.uOffset;
  11064. newTexture.vOffset = this.vOffset;
  11065. newTexture.uScale = this.uScale;
  11066. newTexture.vScale = this.vScale;
  11067. newTexture.uAng = this.uAng;
  11068. newTexture.vAng = this.vAng;
  11069. newTexture.wAng = this.wAng;
  11070. return newTexture;
  11071. };
  11072. // Statics
  11073. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11074. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11075. if (typeof onLoad === "undefined") { onLoad = null; }
  11076. if (typeof onError === "undefined") { onError = null; }
  11077. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11078. };
  11079. Texture.NEAREST_SAMPLINGMODE = 1;
  11080. Texture.BILINEAR_SAMPLINGMODE = 2;
  11081. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11082. Texture.EXPLICIT_MODE = 0;
  11083. Texture.SPHERICAL_MODE = 1;
  11084. Texture.PLANAR_MODE = 2;
  11085. Texture.CUBIC_MODE = 3;
  11086. Texture.PROJECTION_MODE = 4;
  11087. Texture.SKYBOX_MODE = 5;
  11088. Texture.CLAMP_ADDRESSMODE = 0;
  11089. Texture.WRAP_ADDRESSMODE = 1;
  11090. Texture.MIRROR_ADDRESSMODE = 2;
  11091. return Texture;
  11092. })(BABYLON.BaseTexture);
  11093. BABYLON.Texture = Texture;
  11094. })(BABYLON || (BABYLON = {}));
  11095. //# sourceMappingURL=babylon.texture.js.map
  11096. var BABYLON;
  11097. (function (BABYLON) {
  11098. var CubeTexture = (function (_super) {
  11099. __extends(CubeTexture, _super);
  11100. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11101. _super.call(this, scene);
  11102. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11103. this.name = rootUrl;
  11104. this.url = rootUrl;
  11105. this._noMipmap = noMipmap;
  11106. this.hasAlpha = false;
  11107. this._texture = this._getFromCache(rootUrl, noMipmap);
  11108. if (!extensions) {
  11109. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11110. }
  11111. this._extensions = extensions;
  11112. if (!this._texture) {
  11113. if (!scene.useDelayedTextureLoading) {
  11114. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11115. } else {
  11116. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11117. }
  11118. }
  11119. this.isCube = true;
  11120. this._textureMatrix = BABYLON.Matrix.Identity();
  11121. }
  11122. CubeTexture.prototype.clone = function () {
  11123. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11124. // Base texture
  11125. newTexture.level = this.level;
  11126. newTexture.wrapU = this.wrapU;
  11127. newTexture.wrapV = this.wrapV;
  11128. newTexture.coordinatesIndex = this.coordinatesIndex;
  11129. newTexture.coordinatesMode = this.coordinatesMode;
  11130. return newTexture;
  11131. };
  11132. // Methods
  11133. CubeTexture.prototype.delayLoad = function () {
  11134. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11135. return;
  11136. }
  11137. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11138. this._texture = this._getFromCache(this.url, this._noMipmap);
  11139. if (!this._texture) {
  11140. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11141. }
  11142. };
  11143. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11144. return this._textureMatrix;
  11145. };
  11146. return CubeTexture;
  11147. })(BABYLON.BaseTexture);
  11148. BABYLON.CubeTexture = CubeTexture;
  11149. })(BABYLON || (BABYLON = {}));
  11150. //# sourceMappingURL=babylon.cubeTexture.js.map
  11151. var BABYLON;
  11152. (function (BABYLON) {
  11153. var RenderTargetTexture = (function (_super) {
  11154. __extends(RenderTargetTexture, _super);
  11155. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  11156. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  11157. _super.call(this, null, scene, !generateMipMaps);
  11158. this.renderList = new Array();
  11159. this.renderParticles = true;
  11160. this.renderSprites = false;
  11161. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11162. this._currentRefreshId = -1;
  11163. this._refreshRate = 1;
  11164. this.name = name;
  11165. this.isRenderTarget = true;
  11166. this._size = size;
  11167. this._generateMipMaps = generateMipMaps;
  11168. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11169. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11170. // Rendering groups
  11171. this._renderingManager = new BABYLON.RenderingManager(scene);
  11172. }
  11173. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11174. this._currentRefreshId = -1;
  11175. };
  11176. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11177. get: function () {
  11178. return this._refreshRate;
  11179. },
  11180. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11181. set: function (value) {
  11182. this._refreshRate = value;
  11183. this.resetRefreshCounter();
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. RenderTargetTexture.prototype._shouldRender = function () {
  11189. if (this._currentRefreshId === -1) {
  11190. this._currentRefreshId = 1;
  11191. return true;
  11192. }
  11193. if (this.refreshRate == this._currentRefreshId) {
  11194. this._currentRefreshId = 1;
  11195. return true;
  11196. }
  11197. this._currentRefreshId++;
  11198. return false;
  11199. };
  11200. RenderTargetTexture.prototype.isReady = function () {
  11201. if (!this.getScene().renderTargetsEnabled) {
  11202. return false;
  11203. }
  11204. return _super.prototype.isReady.call(this);
  11205. };
  11206. RenderTargetTexture.prototype.getRenderSize = function () {
  11207. return this._size;
  11208. };
  11209. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11210. get: function () {
  11211. return true;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. RenderTargetTexture.prototype.scale = function (ratio) {
  11217. var newSize = this._size * ratio;
  11218. this.resize(newSize, this._generateMipMaps);
  11219. };
  11220. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11221. this.releaseInternalTexture();
  11222. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11223. };
  11224. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11225. var scene = this.getScene();
  11226. var engine = scene.getEngine();
  11227. if (this._waitingRenderList) {
  11228. this.renderList = [];
  11229. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11230. var id = this._waitingRenderList[index];
  11231. this.renderList.push(scene.getMeshByID(id));
  11232. }
  11233. delete this._waitingRenderList;
  11234. }
  11235. if (!this.renderList) {
  11236. return;
  11237. }
  11238. // Bind
  11239. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11240. engine.bindFramebuffer(this._texture);
  11241. }
  11242. // Clear
  11243. engine.clear(scene.clearColor, true, true);
  11244. this._renderingManager.reset();
  11245. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11246. var mesh = this.renderList[meshIndex];
  11247. if (mesh) {
  11248. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11249. // Reset _currentRefreshId
  11250. this.resetRefreshCounter();
  11251. continue;
  11252. }
  11253. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11254. mesh._activate(scene.getRenderId());
  11255. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11256. var subMesh = mesh.subMeshes[subIndex];
  11257. scene._activeVertices += subMesh.indexCount;
  11258. this._renderingManager.dispatch(subMesh);
  11259. }
  11260. }
  11261. }
  11262. }
  11263. if (!this._doNotChangeAspectRatio) {
  11264. scene.updateTransformMatrix(true);
  11265. }
  11266. if (this.onBeforeRender) {
  11267. this.onBeforeRender();
  11268. }
  11269. // Render
  11270. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11271. if (useCameraPostProcess) {
  11272. scene.postProcessManager._finalizeFrame(false, this._texture);
  11273. }
  11274. if (this.onAfterRender) {
  11275. this.onAfterRender();
  11276. }
  11277. // Unbind
  11278. engine.unBindFramebuffer(this._texture);
  11279. if (!this._doNotChangeAspectRatio) {
  11280. scene.updateTransformMatrix(true);
  11281. }
  11282. };
  11283. RenderTargetTexture.prototype.clone = function () {
  11284. var textureSize = this.getSize();
  11285. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11286. // Base texture
  11287. newTexture.hasAlpha = this.hasAlpha;
  11288. newTexture.level = this.level;
  11289. // RenderTarget Texture
  11290. newTexture.coordinatesMode = this.coordinatesMode;
  11291. newTexture.renderList = this.renderList.slice(0);
  11292. return newTexture;
  11293. };
  11294. return RenderTargetTexture;
  11295. })(BABYLON.Texture);
  11296. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11297. })(BABYLON || (BABYLON = {}));
  11298. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11299. var BABYLON;
  11300. (function (BABYLON) {
  11301. var ProceduralTexture = (function (_super) {
  11302. __extends(ProceduralTexture, _super);
  11303. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11304. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11305. _super.call(this, null, scene, !generateMipMaps);
  11306. this._currentRefreshId = -1;
  11307. this._refreshRate = 1;
  11308. this._vertexDeclaration = [2];
  11309. this._vertexStrideSize = 2 * 4;
  11310. this._uniforms = new Array();
  11311. this._samplers = new Array();
  11312. this._textures = new Array();
  11313. this._floats = new Array();
  11314. this._floatsArrays = {};
  11315. this._colors3 = new Array();
  11316. this._colors4 = new Array();
  11317. this._vectors2 = new Array();
  11318. this._vectors3 = new Array();
  11319. this._matrices = new Array();
  11320. this._fallbackTextureUsed = false;
  11321. scene._proceduralTextures.push(this);
  11322. this.name = name;
  11323. this.isRenderTarget = true;
  11324. this._size = size;
  11325. this._generateMipMaps = generateMipMaps;
  11326. this.setFragment(fragment);
  11327. this._fallbackTexture = fallbackTexture;
  11328. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11329. // VBO
  11330. var vertices = [];
  11331. vertices.push(1, 1);
  11332. vertices.push(-1, 1);
  11333. vertices.push(-1, -1);
  11334. vertices.push(1, -1);
  11335. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11336. // Indices
  11337. var indices = [];
  11338. indices.push(0);
  11339. indices.push(1);
  11340. indices.push(2);
  11341. indices.push(0);
  11342. indices.push(2);
  11343. indices.push(3);
  11344. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11345. }
  11346. ProceduralTexture.prototype.reset = function () {
  11347. if (this._effect === undefined) {
  11348. return;
  11349. }
  11350. var engine = this.getScene().getEngine();
  11351. engine._releaseEffect(this._effect);
  11352. };
  11353. ProceduralTexture.prototype.isReady = function () {
  11354. var _this = this;
  11355. var engine = this.getScene().getEngine();
  11356. var shaders;
  11357. if (!this._fragment) {
  11358. return false;
  11359. }
  11360. if (this._fallbackTextureUsed) {
  11361. return true;
  11362. }
  11363. if (this._fragment.fragmentElement !== undefined) {
  11364. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11365. } else {
  11366. shaders = { vertex: "procedural", fragment: this._fragment };
  11367. }
  11368. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11369. _this.releaseInternalTexture();
  11370. if (_this._fallbackTexture) {
  11371. _this._texture = _this._fallbackTexture._texture;
  11372. _this._texture.references++;
  11373. }
  11374. _this._fallbackTextureUsed = true;
  11375. });
  11376. return this._effect.isReady();
  11377. };
  11378. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11379. this._currentRefreshId = -1;
  11380. };
  11381. ProceduralTexture.prototype.setFragment = function (fragment) {
  11382. this._fragment = fragment;
  11383. };
  11384. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11385. get: function () {
  11386. return this._refreshRate;
  11387. },
  11388. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11389. set: function (value) {
  11390. this._refreshRate = value;
  11391. this.resetRefreshCounter();
  11392. },
  11393. enumerable: true,
  11394. configurable: true
  11395. });
  11396. ProceduralTexture.prototype._shouldRender = function () {
  11397. if (!this.isReady() || !this._texture) {
  11398. return false;
  11399. }
  11400. if (this._fallbackTextureUsed) {
  11401. return false;
  11402. }
  11403. if (this._currentRefreshId === -1) {
  11404. this._currentRefreshId = 1;
  11405. return true;
  11406. }
  11407. if (this.refreshRate === this._currentRefreshId) {
  11408. this._currentRefreshId = 1;
  11409. return true;
  11410. }
  11411. this._currentRefreshId++;
  11412. return false;
  11413. };
  11414. ProceduralTexture.prototype.getRenderSize = function () {
  11415. return this._size;
  11416. };
  11417. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11418. if (this._fallbackTextureUsed) {
  11419. return;
  11420. }
  11421. this.releaseInternalTexture();
  11422. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11423. };
  11424. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11425. if (this._uniforms.indexOf(uniformName) === -1) {
  11426. this._uniforms.push(uniformName);
  11427. }
  11428. };
  11429. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11430. if (this._samplers.indexOf(name) === -1) {
  11431. this._samplers.push(name);
  11432. }
  11433. this._textures[name] = texture;
  11434. return this;
  11435. };
  11436. ProceduralTexture.prototype.setFloat = function (name, value) {
  11437. this._checkUniform(name);
  11438. this._floats[name] = value;
  11439. return this;
  11440. };
  11441. ProceduralTexture.prototype.setFloats = function (name, value) {
  11442. this._checkUniform(name);
  11443. this._floatsArrays[name] = value;
  11444. return this;
  11445. };
  11446. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11447. this._checkUniform(name);
  11448. this._colors3[name] = value;
  11449. return this;
  11450. };
  11451. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11452. this._checkUniform(name);
  11453. this._colors4[name] = value;
  11454. return this;
  11455. };
  11456. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11457. this._checkUniform(name);
  11458. this._vectors2[name] = value;
  11459. return this;
  11460. };
  11461. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11462. this._checkUniform(name);
  11463. this._vectors3[name] = value;
  11464. return this;
  11465. };
  11466. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11467. this._checkUniform(name);
  11468. this._matrices[name] = value;
  11469. return this;
  11470. };
  11471. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11472. var scene = this.getScene();
  11473. var engine = scene.getEngine();
  11474. engine.bindFramebuffer(this._texture);
  11475. // Clear
  11476. engine.clear(scene.clearColor, true, true);
  11477. // Render
  11478. engine.enableEffect(this._effect);
  11479. engine.setState(false);
  11480. for (var name in this._textures) {
  11481. this._effect.setTexture(name, this._textures[name]);
  11482. }
  11483. for (name in this._floats) {
  11484. this._effect.setFloat(name, this._floats[name]);
  11485. }
  11486. for (name in this._floatsArrays) {
  11487. this._effect.setArray(name, this._floatsArrays[name]);
  11488. }
  11489. for (name in this._colors3) {
  11490. this._effect.setColor3(name, this._colors3[name]);
  11491. }
  11492. for (name in this._colors4) {
  11493. var color = this._colors4[name];
  11494. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11495. }
  11496. for (name in this._vectors2) {
  11497. this._effect.setVector2(name, this._vectors2[name]);
  11498. }
  11499. for (name in this._vectors3) {
  11500. this._effect.setVector3(name, this._vectors3[name]);
  11501. }
  11502. for (name in this._matrices) {
  11503. this._effect.setMatrix(name, this._matrices[name]);
  11504. }
  11505. // VBOs
  11506. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11507. // Draw order
  11508. engine.draw(true, 0, 6);
  11509. // Unbind
  11510. engine.unBindFramebuffer(this._texture);
  11511. };
  11512. ProceduralTexture.prototype.clone = function () {
  11513. var textureSize = this.getSize();
  11514. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11515. // Base texture
  11516. newTexture.hasAlpha = this.hasAlpha;
  11517. newTexture.level = this.level;
  11518. // RenderTarget Texture
  11519. newTexture.coordinatesMode = this.coordinatesMode;
  11520. return newTexture;
  11521. };
  11522. ProceduralTexture.prototype.dispose = function () {
  11523. var index = this.getScene()._proceduralTextures.indexOf(this);
  11524. if (index >= 0) {
  11525. this.getScene()._proceduralTextures.splice(index, 1);
  11526. }
  11527. _super.prototype.dispose.call(this);
  11528. };
  11529. return ProceduralTexture;
  11530. })(BABYLON.Texture);
  11531. BABYLON.ProceduralTexture = ProceduralTexture;
  11532. })(BABYLON || (BABYLON = {}));
  11533. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11534. var BABYLON;
  11535. (function (BABYLON) {
  11536. var WoodProceduralTexture = (function (_super) {
  11537. __extends(WoodProceduralTexture, _super);
  11538. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11539. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11540. this._ampScale = 100.0;
  11541. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11542. this.updateShaderUniforms();
  11543. this.refreshRate = 0;
  11544. }
  11545. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11546. this.setFloat("ampScale", this._ampScale);
  11547. this.setColor3("woodColor", this._woodColor);
  11548. };
  11549. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11550. get: function () {
  11551. return this._ampScale;
  11552. },
  11553. set: function (value) {
  11554. this._ampScale = value;
  11555. this.updateShaderUniforms();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11561. get: function () {
  11562. return this._woodColor;
  11563. },
  11564. set: function (value) {
  11565. this._woodColor = value;
  11566. this.updateShaderUniforms();
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. return WoodProceduralTexture;
  11572. })(BABYLON.ProceduralTexture);
  11573. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11574. var FireProceduralTexture = (function (_super) {
  11575. __extends(FireProceduralTexture, _super);
  11576. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11577. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11578. this._time = 0.0;
  11579. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11580. this._shift = 1.6;
  11581. this._autoGenerateTime = true;
  11582. this._alphaThreshold = 0.5;
  11583. this._fireColors = FireProceduralTexture.RedFireColors;
  11584. this.updateShaderUniforms();
  11585. this.refreshRate = 1;
  11586. }
  11587. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11588. this.setFloat("time", this._time);
  11589. this.setVector2("speed", this._speed);
  11590. this.setFloat("shift", this._shift);
  11591. this.setColor3("c1", this._fireColors[0]);
  11592. this.setColor3("c2", this._fireColors[1]);
  11593. this.setColor3("c3", this._fireColors[2]);
  11594. this.setColor3("c4", this._fireColors[3]);
  11595. this.setColor3("c5", this._fireColors[4]);
  11596. this.setColor3("c6", this._fireColors[5]);
  11597. this.setFloat("alphaThreshold", this._alphaThreshold);
  11598. };
  11599. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11600. if (this._autoGenerateTime) {
  11601. this._time += this.getScene().getAnimationRatio() * 0.03;
  11602. this.updateShaderUniforms();
  11603. }
  11604. _super.prototype.render.call(this, useCameraPostProcess);
  11605. };
  11606. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11607. get: function () {
  11608. return [
  11609. new BABYLON.Color3(0.5, 0.0, 1.0),
  11610. new BABYLON.Color3(0.9, 0.0, 1.0),
  11611. new BABYLON.Color3(0.2, 0.0, 1.0),
  11612. new BABYLON.Color3(1.0, 0.9, 1.0),
  11613. new BABYLON.Color3(0.1, 0.1, 1.0),
  11614. new BABYLON.Color3(0.9, 0.9, 1.0)
  11615. ];
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11621. get: function () {
  11622. return [
  11623. new BABYLON.Color3(0.5, 1.0, 0.0),
  11624. new BABYLON.Color3(0.5, 1.0, 0.0),
  11625. new BABYLON.Color3(0.3, 0.4, 0.0),
  11626. new BABYLON.Color3(0.5, 1.0, 0.0),
  11627. new BABYLON.Color3(0.2, 0.0, 0.0),
  11628. new BABYLON.Color3(0.5, 1.0, 0.0)
  11629. ];
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11635. get: function () {
  11636. return [
  11637. new BABYLON.Color3(0.5, 0.0, 0.1),
  11638. new BABYLON.Color3(0.9, 0.0, 0.0),
  11639. new BABYLON.Color3(0.2, 0.0, 0.0),
  11640. new BABYLON.Color3(1.0, 0.9, 0.0),
  11641. new BABYLON.Color3(0.1, 0.1, 0.1),
  11642. new BABYLON.Color3(0.9, 0.9, 0.9)
  11643. ];
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11649. get: function () {
  11650. return [
  11651. new BABYLON.Color3(0.1, 0.0, 0.5),
  11652. new BABYLON.Color3(0.0, 0.0, 0.5),
  11653. new BABYLON.Color3(0.1, 0.0, 0.2),
  11654. new BABYLON.Color3(0.0, 0.0, 1.0),
  11655. new BABYLON.Color3(0.1, 0.2, 0.3),
  11656. new BABYLON.Color3(0.0, 0.2, 0.9)
  11657. ];
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11663. get: function () {
  11664. return this._fireColors;
  11665. },
  11666. set: function (value) {
  11667. this._fireColors = value;
  11668. this.updateShaderUniforms();
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11674. get: function () {
  11675. return this._time;
  11676. },
  11677. set: function (value) {
  11678. this._time = value;
  11679. this.updateShaderUniforms();
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11685. get: function () {
  11686. return this._speed;
  11687. },
  11688. set: function (value) {
  11689. this._speed = value;
  11690. this.updateShaderUniforms();
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11696. get: function () {
  11697. return this._shift;
  11698. },
  11699. set: function (value) {
  11700. this._shift = value;
  11701. this.updateShaderUniforms();
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11707. get: function () {
  11708. return this._alphaThreshold;
  11709. },
  11710. set: function (value) {
  11711. this._alphaThreshold = value;
  11712. this.updateShaderUniforms();
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. return FireProceduralTexture;
  11718. })(BABYLON.ProceduralTexture);
  11719. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11720. var CloudProceduralTexture = (function (_super) {
  11721. __extends(CloudProceduralTexture, _super);
  11722. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11723. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11724. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11725. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11726. this.updateShaderUniforms();
  11727. this.refreshRate = 0;
  11728. }
  11729. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11730. this.setColor3("skyColor", this._skyColor);
  11731. this.setColor3("cloudColor", this._cloudColor);
  11732. };
  11733. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11734. get: function () {
  11735. return this._skyColor;
  11736. },
  11737. set: function (value) {
  11738. this._skyColor = value;
  11739. this.updateShaderUniforms();
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11745. get: function () {
  11746. return this._cloudColor;
  11747. },
  11748. set: function (value) {
  11749. this._cloudColor = value;
  11750. this.updateShaderUniforms();
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. return CloudProceduralTexture;
  11756. })(BABYLON.ProceduralTexture);
  11757. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11758. var GrassProceduralTexture = (function (_super) {
  11759. __extends(GrassProceduralTexture, _super);
  11760. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11761. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11762. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11763. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11764. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11765. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11766. this._grassColors = [
  11767. new BABYLON.Color3(0.29, 0.38, 0.02),
  11768. new BABYLON.Color3(0.36, 0.49, 0.09),
  11769. new BABYLON.Color3(0.51, 0.6, 0.28)
  11770. ];
  11771. this.updateShaderUniforms();
  11772. this.refreshRate = 0;
  11773. }
  11774. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11775. this.setColor3("herb1Color", this._grassColors[0]);
  11776. this.setColor3("herb2Color", this._grassColors[1]);
  11777. this.setColor3("herb3Color", this._grassColors[2]);
  11778. this.setColor3("groundColor", this._groundColor);
  11779. };
  11780. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11781. get: function () {
  11782. return this._grassColors;
  11783. },
  11784. set: function (value) {
  11785. this._grassColors = value;
  11786. this.updateShaderUniforms();
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11792. get: function () {
  11793. return this._groundColor;
  11794. },
  11795. set: function (value) {
  11796. this.groundColor = value;
  11797. this.updateShaderUniforms();
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. return GrassProceduralTexture;
  11803. })(BABYLON.ProceduralTexture);
  11804. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11805. var RoadProceduralTexture = (function (_super) {
  11806. __extends(RoadProceduralTexture, _super);
  11807. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11808. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11809. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11810. this.updateShaderUniforms();
  11811. this.refreshRate = 0;
  11812. }
  11813. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11814. this.setColor3("roadColor", this._roadColor);
  11815. };
  11816. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11817. get: function () {
  11818. return this._roadColor;
  11819. },
  11820. set: function (value) {
  11821. this._roadColor = value;
  11822. this.updateShaderUniforms();
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. return RoadProceduralTexture;
  11828. })(BABYLON.ProceduralTexture);
  11829. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11830. var BrickProceduralTexture = (function (_super) {
  11831. __extends(BrickProceduralTexture, _super);
  11832. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11833. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11834. this._numberOfBricksHeight = 15;
  11835. this._numberOfBricksWidth = 5;
  11836. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11837. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11838. this.updateShaderUniforms();
  11839. this.refreshRate = 0;
  11840. }
  11841. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11842. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11843. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11844. this.setColor3("brickColor", this._brickColor);
  11845. this.setColor3("jointColor", this._jointColor);
  11846. };
  11847. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11848. get: function () {
  11849. return this._numberOfBricksHeight;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11855. set: function (value) {
  11856. this._numberOfBricksHeight = value;
  11857. this.updateShaderUniforms();
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11863. get: function () {
  11864. return this._numberOfBricksWidth;
  11865. },
  11866. set: function (value) {
  11867. this._numberOfBricksHeight = value;
  11868. this.updateShaderUniforms();
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11874. get: function () {
  11875. return this._jointColor;
  11876. },
  11877. set: function (value) {
  11878. this._jointColor = value;
  11879. this.updateShaderUniforms();
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11885. get: function () {
  11886. return this._brickColor;
  11887. },
  11888. set: function (value) {
  11889. this._brickColor = value;
  11890. this.updateShaderUniforms();
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. return BrickProceduralTexture;
  11896. })(BABYLON.ProceduralTexture);
  11897. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11898. var MarbleProceduralTexture = (function (_super) {
  11899. __extends(MarbleProceduralTexture, _super);
  11900. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11901. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11902. this._numberOfTilesHeight = 3;
  11903. this._numberOfTilesWidth = 3;
  11904. this._amplitude = 9.0;
  11905. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11906. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11907. this.updateShaderUniforms();
  11908. this.refreshRate = 0;
  11909. }
  11910. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11911. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11912. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11913. this.setFloat("amplitude", this._amplitude);
  11914. this.setColor3("marbleColor", this._marbleColor);
  11915. this.setColor3("jointColor", this._jointColor);
  11916. };
  11917. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11918. get: function () {
  11919. return this._numberOfTilesHeight;
  11920. },
  11921. set: function (value) {
  11922. this._numberOfTilesHeight = value;
  11923. this.updateShaderUniforms();
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11929. get: function () {
  11930. return this._numberOfTilesWidth;
  11931. },
  11932. set: function (value) {
  11933. this._numberOfTilesWidth = value;
  11934. this.updateShaderUniforms();
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11940. get: function () {
  11941. return this._jointColor;
  11942. },
  11943. set: function (value) {
  11944. this._jointColor = value;
  11945. this.updateShaderUniforms();
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11951. get: function () {
  11952. return this._marbleColor;
  11953. },
  11954. set: function (value) {
  11955. this._marbleColor = value;
  11956. this.updateShaderUniforms();
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. return MarbleProceduralTexture;
  11962. })(BABYLON.ProceduralTexture);
  11963. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11964. })(BABYLON || (BABYLON = {}));
  11965. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11966. var BABYLON;
  11967. (function (BABYLON) {
  11968. var CustomProceduralTexture = (function (_super) {
  11969. __extends(CustomProceduralTexture, _super);
  11970. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11971. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11972. this._animate = true;
  11973. this._time = 0;
  11974. this._texturePath = texturePath;
  11975. //Try to load json
  11976. this.loadJson(texturePath);
  11977. this.refreshRate = 1;
  11978. }
  11979. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11980. var _this = this;
  11981. var that = this;
  11982. function noConfigFile() {
  11983. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11984. try {
  11985. that.setFragment(that._texturePath);
  11986. } catch (ex) {
  11987. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11988. }
  11989. }
  11990. var configFileUrl = jsonUrl + "/config.json";
  11991. var xhr = new XMLHttpRequest();
  11992. xhr.open("GET", configFileUrl, true);
  11993. xhr.addEventListener("load", function () {
  11994. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11995. try {
  11996. _this._config = JSON.parse(xhr.response);
  11997. _this.updateShaderUniforms();
  11998. _this.updateTextures();
  11999. _this.setFragment(_this._texturePath + "/custom");
  12000. _this._animate = _this._config.animate;
  12001. _this.refreshRate = _this._config.refreshrate;
  12002. } catch (ex) {
  12003. noConfigFile();
  12004. }
  12005. } else {
  12006. noConfigFile();
  12007. }
  12008. }, false);
  12009. xhr.addEventListener("error", function (event) {
  12010. noConfigFile();
  12011. }, false);
  12012. try {
  12013. xhr.send();
  12014. } catch (ex) {
  12015. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12016. }
  12017. };
  12018. CustomProceduralTexture.prototype.isReady = function () {
  12019. if (!_super.prototype.isReady.call(this)) {
  12020. return false;
  12021. }
  12022. for (var name in this._textures) {
  12023. var texture = this._textures[name];
  12024. if (!texture.isReady()) {
  12025. return false;
  12026. }
  12027. }
  12028. return true;
  12029. };
  12030. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12031. if (this._animate) {
  12032. this._time += this.getScene().getAnimationRatio() * 0.03;
  12033. this.updateShaderUniforms();
  12034. }
  12035. _super.prototype.render.call(this, useCameraPostProcess);
  12036. };
  12037. CustomProceduralTexture.prototype.updateTextures = function () {
  12038. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12039. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12040. }
  12041. };
  12042. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12043. if (this._config) {
  12044. for (var j = 0; j < this._config.uniforms.length; j++) {
  12045. var uniform = this._config.uniforms[j];
  12046. switch (uniform.type) {
  12047. case "float":
  12048. this.setFloat(uniform.name, uniform.value);
  12049. break;
  12050. case "color3":
  12051. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12052. break;
  12053. case "color4":
  12054. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12055. break;
  12056. case "vector2":
  12057. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12058. break;
  12059. case "vector3":
  12060. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12061. break;
  12062. }
  12063. }
  12064. }
  12065. this.setFloat("time", this._time);
  12066. };
  12067. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12068. get: function () {
  12069. return this._animate;
  12070. },
  12071. set: function (value) {
  12072. this._animate = value;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. return CustomProceduralTexture;
  12078. })(BABYLON.ProceduralTexture);
  12079. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12080. })(BABYLON || (BABYLON = {}));
  12081. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12082. var BABYLON;
  12083. (function (BABYLON) {
  12084. var MirrorTexture = (function (_super) {
  12085. __extends(MirrorTexture, _super);
  12086. function MirrorTexture(name, size, scene, generateMipMaps) {
  12087. var _this = this;
  12088. _super.call(this, name, size, scene, generateMipMaps, true);
  12089. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12090. this._transformMatrix = BABYLON.Matrix.Zero();
  12091. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12092. this.onBeforeRender = function () {
  12093. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12094. _this._savedViewMatrix = scene.getViewMatrix();
  12095. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12096. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12097. scene.clipPlane = _this.mirrorPlane;
  12098. scene.getEngine().cullBackFaces = false;
  12099. };
  12100. this.onAfterRender = function () {
  12101. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12102. scene.getEngine().cullBackFaces = true;
  12103. delete scene.clipPlane;
  12104. };
  12105. }
  12106. MirrorTexture.prototype.clone = function () {
  12107. var textureSize = this.getSize();
  12108. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12109. // Base texture
  12110. newTexture.hasAlpha = this.hasAlpha;
  12111. newTexture.level = this.level;
  12112. // Mirror Texture
  12113. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12114. newTexture.renderList = this.renderList.slice(0);
  12115. return newTexture;
  12116. };
  12117. return MirrorTexture;
  12118. })(BABYLON.RenderTargetTexture);
  12119. BABYLON.MirrorTexture = MirrorTexture;
  12120. })(BABYLON || (BABYLON = {}));
  12121. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12122. var BABYLON;
  12123. (function (BABYLON) {
  12124. var DynamicTexture = (function (_super) {
  12125. __extends(DynamicTexture, _super);
  12126. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12127. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12128. _super.call(this, null, scene, !generateMipMaps);
  12129. this.name = name;
  12130. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12131. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12132. this._generateMipMaps = generateMipMaps;
  12133. if (options.getContext) {
  12134. this._canvas = options;
  12135. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12136. } else {
  12137. this._canvas = document.createElement("canvas");
  12138. if (options.width) {
  12139. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12140. } else {
  12141. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12142. }
  12143. }
  12144. var textureSize = this.getSize();
  12145. this._canvas.width = textureSize.width;
  12146. this._canvas.height = textureSize.height;
  12147. this._context = this._canvas.getContext("2d");
  12148. }
  12149. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12150. get: function () {
  12151. return true;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. DynamicTexture.prototype.scale = function (ratio) {
  12157. var textureSize = this.getSize();
  12158. textureSize.width *= ratio;
  12159. textureSize.height *= ratio;
  12160. this._canvas.width = textureSize.width;
  12161. this._canvas.height = textureSize.height;
  12162. this.releaseInternalTexture();
  12163. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12164. };
  12165. DynamicTexture.prototype.getContext = function () {
  12166. return this._context;
  12167. };
  12168. DynamicTexture.prototype.clear = function () {
  12169. var size = this.getSize();
  12170. this._context.fillRect(0, 0, size.width, size.height);
  12171. };
  12172. DynamicTexture.prototype.update = function (invertY) {
  12173. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12174. };
  12175. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12176. if (typeof update === "undefined") { update = true; }
  12177. var size = this.getSize();
  12178. if (clearColor) {
  12179. this._context.fillStyle = clearColor;
  12180. this._context.fillRect(0, 0, size.width, size.height);
  12181. }
  12182. this._context.font = font;
  12183. if (x === null) {
  12184. var textSize = this._context.measureText(text);
  12185. x = (size.width - textSize.width) / 2;
  12186. }
  12187. this._context.fillStyle = color;
  12188. this._context.fillText(text, x, y);
  12189. if (update) {
  12190. this.update(invertY);
  12191. }
  12192. };
  12193. DynamicTexture.prototype.clone = function () {
  12194. var textureSize = this.getSize();
  12195. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12196. // Base texture
  12197. newTexture.hasAlpha = this.hasAlpha;
  12198. newTexture.level = this.level;
  12199. // Dynamic Texture
  12200. newTexture.wrapU = this.wrapU;
  12201. newTexture.wrapV = this.wrapV;
  12202. return newTexture;
  12203. };
  12204. return DynamicTexture;
  12205. })(BABYLON.Texture);
  12206. BABYLON.DynamicTexture = DynamicTexture;
  12207. })(BABYLON || (BABYLON = {}));
  12208. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12209. var BABYLON;
  12210. (function (BABYLON) {
  12211. var VideoTexture = (function (_super) {
  12212. __extends(VideoTexture, _super);
  12213. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12214. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12215. var _this = this;
  12216. _super.call(this, null, scene, !generateMipMaps, invertY);
  12217. this._autoLaunch = true;
  12218. this.name = name;
  12219. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12220. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12221. var requiredWidth = size.width || size;
  12222. var requiredHeight = size.height || size;
  12223. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12224. var textureSize = this.getSize();
  12225. this.video = document.createElement("video");
  12226. this.video.width = textureSize.width;
  12227. this.video.height = textureSize.height;
  12228. this.video.autoplay = false;
  12229. this.video.loop = true;
  12230. this.video.addEventListener("canplaythrough", function () {
  12231. if (_this._texture) {
  12232. _this._texture.isReady = true;
  12233. }
  12234. });
  12235. urls.forEach(function (url) {
  12236. var source = document.createElement("source");
  12237. source.src = url;
  12238. _this.video.appendChild(source);
  12239. });
  12240. this._lastUpdate = BABYLON.Tools.Now;
  12241. }
  12242. VideoTexture.prototype.update = function () {
  12243. if (this._autoLaunch) {
  12244. this._autoLaunch = false;
  12245. this.video.play();
  12246. }
  12247. var now = BABYLON.Tools.Now;
  12248. if (now - this._lastUpdate < 15) {
  12249. return false;
  12250. }
  12251. this._lastUpdate = now;
  12252. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12253. return true;
  12254. };
  12255. return VideoTexture;
  12256. })(BABYLON.Texture);
  12257. BABYLON.VideoTexture = VideoTexture;
  12258. })(BABYLON || (BABYLON = {}));
  12259. //# sourceMappingURL=babylon.videoTexture.js.map
  12260. var BABYLON;
  12261. (function (BABYLON) {
  12262. var EffectFallbacks = (function () {
  12263. function EffectFallbacks() {
  12264. this._defines = {};
  12265. this._currentRank = 32;
  12266. this._maxRank = -1;
  12267. }
  12268. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12269. if (!this._defines[rank]) {
  12270. if (rank < this._currentRank) {
  12271. this._currentRank = rank;
  12272. }
  12273. if (rank > this._maxRank) {
  12274. this._maxRank = rank;
  12275. }
  12276. this._defines[rank] = new Array();
  12277. }
  12278. this._defines[rank].push(define);
  12279. };
  12280. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12281. get: function () {
  12282. return this._currentRank <= this._maxRank;
  12283. },
  12284. enumerable: true,
  12285. configurable: true
  12286. });
  12287. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12288. var currentFallbacks = this._defines[this._currentRank];
  12289. for (var index = 0; index < currentFallbacks.length; index++) {
  12290. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12291. }
  12292. this._currentRank++;
  12293. return currentDefines;
  12294. };
  12295. return EffectFallbacks;
  12296. })();
  12297. BABYLON.EffectFallbacks = EffectFallbacks;
  12298. var Effect = (function () {
  12299. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12300. var _this = this;
  12301. this._isReady = false;
  12302. this._compilationError = "";
  12303. this._valueCache = [];
  12304. this._engine = engine;
  12305. this.name = baseName;
  12306. this.defines = defines;
  12307. this._uniformsNames = uniformsNames.concat(samplers);
  12308. this._samplers = samplers;
  12309. this._attributesNames = attributesNames;
  12310. this.onError = onError;
  12311. this.onCompiled = onCompiled;
  12312. var vertexSource;
  12313. var fragmentSource;
  12314. if (baseName.vertexElement) {
  12315. vertexSource = document.getElementById(baseName.vertexElement);
  12316. if (!vertexSource) {
  12317. vertexSource = baseName.vertexElement;
  12318. }
  12319. } else {
  12320. vertexSource = baseName.vertex || baseName;
  12321. }
  12322. if (baseName.fragmentElement) {
  12323. fragmentSource = document.getElementById(baseName.fragmentElement);
  12324. if (!fragmentSource) {
  12325. fragmentSource = baseName.fragmentElement;
  12326. }
  12327. } else {
  12328. fragmentSource = baseName.fragment || baseName;
  12329. }
  12330. this._loadVertexShader(vertexSource, function (vertexCode) {
  12331. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12332. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12333. });
  12334. });
  12335. }
  12336. // Properties
  12337. Effect.prototype.isReady = function () {
  12338. return this._isReady;
  12339. };
  12340. Effect.prototype.getProgram = function () {
  12341. return this._program;
  12342. };
  12343. Effect.prototype.getAttributesNames = function () {
  12344. return this._attributesNames;
  12345. };
  12346. Effect.prototype.getAttributeLocation = function (index) {
  12347. return this._attributes[index];
  12348. };
  12349. Effect.prototype.getAttributeLocationByName = function (name) {
  12350. var index = this._attributesNames.indexOf(name);
  12351. return this._attributes[index];
  12352. };
  12353. Effect.prototype.getAttributesCount = function () {
  12354. return this._attributes.length;
  12355. };
  12356. Effect.prototype.getUniformIndex = function (uniformName) {
  12357. return this._uniformsNames.indexOf(uniformName);
  12358. };
  12359. Effect.prototype.getUniform = function (uniformName) {
  12360. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12361. };
  12362. Effect.prototype.getSamplers = function () {
  12363. return this._samplers;
  12364. };
  12365. Effect.prototype.getCompilationError = function () {
  12366. return this._compilationError;
  12367. };
  12368. // Methods
  12369. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12370. // DOM element ?
  12371. if (vertex instanceof HTMLElement) {
  12372. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12373. callback(vertexCode);
  12374. return;
  12375. }
  12376. // Is in local store ?
  12377. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12378. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12379. return;
  12380. }
  12381. var vertexShaderUrl;
  12382. if (vertex[0] === ".") {
  12383. vertexShaderUrl = vertex;
  12384. } else {
  12385. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12386. }
  12387. // Vertex shader
  12388. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12389. };
  12390. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12391. // DOM element ?
  12392. if (fragment instanceof HTMLElement) {
  12393. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12394. callback(fragmentCode);
  12395. return;
  12396. }
  12397. // Is in local store ?
  12398. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12399. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12400. return;
  12401. }
  12402. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12403. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12404. return;
  12405. }
  12406. var fragmentShaderUrl;
  12407. if (fragment[0] === ".") {
  12408. fragmentShaderUrl = fragment;
  12409. } else {
  12410. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12411. }
  12412. // Fragment shader
  12413. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12414. };
  12415. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12416. try {
  12417. var engine = this._engine;
  12418. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12419. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12420. this._attributes = engine.getAttributes(this._program, attributesNames);
  12421. for (var index = 0; index < this._samplers.length; index++) {
  12422. var sampler = this.getUniform(this._samplers[index]);
  12423. if (sampler == null) {
  12424. this._samplers.splice(index, 1);
  12425. index--;
  12426. }
  12427. }
  12428. engine.bindSamplers(this);
  12429. this._isReady = true;
  12430. if (this.onCompiled) {
  12431. this.onCompiled(this);
  12432. }
  12433. } catch (e) {
  12434. // Is it a problem with precision?
  12435. if (e.message.indexOf("highp") !== -1) {
  12436. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12437. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12438. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12439. return;
  12440. }
  12441. // Let's go through fallbacks then
  12442. if (fallbacks && fallbacks.isMoreFallbacks) {
  12443. defines = fallbacks.reduce(defines);
  12444. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12445. } else {
  12446. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12447. BABYLON.Tools.Error("Defines: " + defines);
  12448. BABYLON.Tools.Error("Error: " + e.message);
  12449. this._compilationError = e.message;
  12450. if (this.onError) {
  12451. this.onError(this, this._compilationError);
  12452. }
  12453. }
  12454. }
  12455. };
  12456. Effect.prototype._bindTexture = function (channel, texture) {
  12457. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12458. };
  12459. Effect.prototype.setTexture = function (channel, texture) {
  12460. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12461. };
  12462. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12463. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12464. };
  12465. //public _cacheMatrix(uniformName, matrix) {
  12466. // if (!this._valueCache[uniformName]) {
  12467. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12468. // }
  12469. // for (var index = 0; index < 16; index++) {
  12470. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12471. // }
  12472. //};
  12473. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12474. if (!this._valueCache[uniformName]) {
  12475. this._valueCache[uniformName] = [x, y];
  12476. return;
  12477. }
  12478. this._valueCache[uniformName][0] = x;
  12479. this._valueCache[uniformName][1] = y;
  12480. };
  12481. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12482. if (!this._valueCache[uniformName]) {
  12483. this._valueCache[uniformName] = [x, y, z];
  12484. return;
  12485. }
  12486. this._valueCache[uniformName][0] = x;
  12487. this._valueCache[uniformName][1] = y;
  12488. this._valueCache[uniformName][2] = z;
  12489. };
  12490. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12491. if (!this._valueCache[uniformName]) {
  12492. this._valueCache[uniformName] = [x, y, z, w];
  12493. return;
  12494. }
  12495. this._valueCache[uniformName][0] = x;
  12496. this._valueCache[uniformName][1] = y;
  12497. this._valueCache[uniformName][2] = z;
  12498. this._valueCache[uniformName][3] = w;
  12499. };
  12500. Effect.prototype.setArray = function (uniformName, array) {
  12501. this._engine.setArray(this.getUniform(uniformName), array);
  12502. return this;
  12503. };
  12504. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12505. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12506. return this;
  12507. };
  12508. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12509. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12510. // return;
  12511. //this._cacheMatrix(uniformName, matrix);
  12512. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12513. return this;
  12514. };
  12515. Effect.prototype.setFloat = function (uniformName, value) {
  12516. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12517. return this;
  12518. this._valueCache[uniformName] = value;
  12519. this._engine.setFloat(this.getUniform(uniformName), value);
  12520. return this;
  12521. };
  12522. Effect.prototype.setBool = function (uniformName, bool) {
  12523. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12524. return this;
  12525. this._valueCache[uniformName] = bool;
  12526. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12527. return this;
  12528. };
  12529. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12530. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12531. return this;
  12532. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12533. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12534. return this;
  12535. };
  12536. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12537. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12538. return this;
  12539. this._cacheFloat2(uniformName, x, y);
  12540. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12541. return this;
  12542. };
  12543. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12544. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12545. return this;
  12546. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12547. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12548. return this;
  12549. };
  12550. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12551. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12552. return this;
  12553. this._cacheFloat3(uniformName, x, y, z);
  12554. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12555. return this;
  12556. };
  12557. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12558. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12559. return this;
  12560. this._cacheFloat4(uniformName, x, y, z, w);
  12561. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12562. return this;
  12563. };
  12564. Effect.prototype.setColor3 = function (uniformName, color3) {
  12565. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12566. return this;
  12567. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12568. this._engine.setColor3(this.getUniform(uniformName), color3);
  12569. return this;
  12570. };
  12571. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12572. 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)
  12573. return this;
  12574. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12575. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12576. return this;
  12577. };
  12578. 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}",
  12579. 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}",
  12580. 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}",
  12581. 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}",
  12582. 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}",
  12583. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12584. 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}",
  12585. 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}",
  12586. 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}",
  12587. 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}",
  12588. 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}",
  12589. 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}",
  12590. 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}",
  12591. 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}",
  12592. 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}",
  12593. 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}",
  12594. 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}",
  12595. 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}",
  12596. 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}",
  12597. 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}",
  12598. 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}",
  12599. 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}",
  12600. 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}",
  12601. 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}",
  12602. 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}",
  12603. 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}",
  12604. 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}",
  12605. 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}",
  12606. 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}",
  12607. 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}",
  12608. 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}",
  12609. 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}",
  12610. 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}",
  12611. 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}",
  12612. 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}",
  12613. 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}",
  12614. 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}",
  12615. };
  12616. return Effect;
  12617. })();
  12618. BABYLON.Effect = Effect;
  12619. })(BABYLON || (BABYLON = {}));
  12620. //# sourceMappingURL=babylon.effect.js.map
  12621. var BABYLON;
  12622. (function (BABYLON) {
  12623. var Material = (function () {
  12624. function Material(name, scene, doNotAdd) {
  12625. this.name = name;
  12626. this.checkReadyOnEveryCall = true;
  12627. this.checkReadyOnlyOnce = false;
  12628. this.state = "";
  12629. this.alpha = 1.0;
  12630. this.backFaceCulling = true;
  12631. this._wasPreviouslyReady = false;
  12632. this._fillMode = Material.TriangleFillMode;
  12633. this.pointSize = 1.0;
  12634. this.id = name;
  12635. this._scene = scene;
  12636. if (!doNotAdd) {
  12637. scene.materials.push(this);
  12638. }
  12639. }
  12640. Object.defineProperty(Material, "TriangleFillMode", {
  12641. get: function () {
  12642. return Material._TriangleFillMode;
  12643. },
  12644. enumerable: true,
  12645. configurable: true
  12646. });
  12647. Object.defineProperty(Material, "WireFrameFillMode", {
  12648. get: function () {
  12649. return Material._WireFrameFillMode;
  12650. },
  12651. enumerable: true,
  12652. configurable: true
  12653. });
  12654. Object.defineProperty(Material, "PointFillMode", {
  12655. get: function () {
  12656. return Material._PointFillMode;
  12657. },
  12658. enumerable: true,
  12659. configurable: true
  12660. });
  12661. Object.defineProperty(Material.prototype, "wireframe", {
  12662. get: function () {
  12663. return this._fillMode === Material.WireFrameFillMode;
  12664. },
  12665. set: function (value) {
  12666. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12667. },
  12668. enumerable: true,
  12669. configurable: true
  12670. });
  12671. Object.defineProperty(Material.prototype, "pointsCloud", {
  12672. get: function () {
  12673. return this._fillMode === Material.PointFillMode;
  12674. },
  12675. set: function (value) {
  12676. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12677. },
  12678. enumerable: true,
  12679. configurable: true
  12680. });
  12681. Object.defineProperty(Material.prototype, "fillMode", {
  12682. get: function () {
  12683. return this._fillMode;
  12684. },
  12685. set: function (value) {
  12686. this._fillMode = value;
  12687. },
  12688. enumerable: true,
  12689. configurable: true
  12690. });
  12691. Material.prototype.isReady = function (mesh, useInstances) {
  12692. return true;
  12693. };
  12694. Material.prototype.getEffect = function () {
  12695. return this._effect;
  12696. };
  12697. Material.prototype.getScene = function () {
  12698. return this._scene;
  12699. };
  12700. Material.prototype.needAlphaBlending = function () {
  12701. return (this.alpha < 1.0);
  12702. };
  12703. Material.prototype.needAlphaTesting = function () {
  12704. return false;
  12705. };
  12706. Material.prototype.getAlphaTestTexture = function () {
  12707. return null;
  12708. };
  12709. Material.prototype.trackCreation = function (onCompiled, onError) {
  12710. };
  12711. Material.prototype._preBind = function () {
  12712. var engine = this._scene.getEngine();
  12713. engine.enableEffect(this._effect);
  12714. engine.setState(this.backFaceCulling);
  12715. };
  12716. Material.prototype.bind = function (world, mesh) {
  12717. this._scene._cachedMaterial = this;
  12718. if (this.onBind) {
  12719. this.onBind(this);
  12720. }
  12721. };
  12722. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12723. };
  12724. Material.prototype.unbind = function () {
  12725. };
  12726. Material.prototype.dispose = function (forceDisposeEffect) {
  12727. // Remove from scene
  12728. var index = this._scene.materials.indexOf(this);
  12729. this._scene.materials.splice(index, 1);
  12730. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12731. if (forceDisposeEffect && this._effect) {
  12732. this._scene.getEngine()._releaseEffect(this._effect);
  12733. this._effect = null;
  12734. }
  12735. // Callback
  12736. if (this.onDispose) {
  12737. this.onDispose();
  12738. }
  12739. };
  12740. Material._TriangleFillMode = 0;
  12741. Material._WireFrameFillMode = 1;
  12742. Material._PointFillMode = 2;
  12743. return Material;
  12744. })();
  12745. BABYLON.Material = Material;
  12746. })(BABYLON || (BABYLON = {}));
  12747. //# sourceMappingURL=babylon.material.js.map
  12748. var BABYLON;
  12749. (function (BABYLON) {
  12750. var maxSimultaneousLights = 4;
  12751. var FresnelParameters = (function () {
  12752. function FresnelParameters() {
  12753. this.isEnabled = true;
  12754. this.leftColor = BABYLON.Color3.White();
  12755. this.rightColor = BABYLON.Color3.Black();
  12756. this.bias = 0;
  12757. this.power = 1;
  12758. }
  12759. return FresnelParameters;
  12760. })();
  12761. BABYLON.FresnelParameters = FresnelParameters;
  12762. var StandardMaterial = (function (_super) {
  12763. __extends(StandardMaterial, _super);
  12764. function StandardMaterial(name, scene) {
  12765. var _this = this;
  12766. _super.call(this, name, scene);
  12767. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12768. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12769. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12770. this.specularPower = 64;
  12771. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12772. this.useAlphaFromDiffuseTexture = false;
  12773. this.useSpecularOverAlpha = true;
  12774. this.fogEnabled = true;
  12775. this._cachedDefines = null;
  12776. this._renderTargets = new BABYLON.SmartArray(16);
  12777. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12778. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12779. this._scaledDiffuse = new BABYLON.Color3();
  12780. this._scaledSpecular = new BABYLON.Color3();
  12781. this.getRenderTargetTextures = function () {
  12782. _this._renderTargets.reset();
  12783. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12784. _this._renderTargets.push(_this.reflectionTexture);
  12785. }
  12786. return _this._renderTargets;
  12787. };
  12788. }
  12789. StandardMaterial.prototype.needAlphaBlending = function () {
  12790. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12791. };
  12792. StandardMaterial.prototype.needAlphaTesting = function () {
  12793. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12794. };
  12795. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12796. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12797. };
  12798. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12799. return this.diffuseTexture;
  12800. };
  12801. // Methods
  12802. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12803. if (this.checkReadyOnlyOnce) {
  12804. if (this._wasPreviouslyReady) {
  12805. return true;
  12806. }
  12807. }
  12808. var scene = this.getScene();
  12809. if (!this.checkReadyOnEveryCall) {
  12810. if (this._renderId === scene.getRenderId()) {
  12811. return true;
  12812. }
  12813. }
  12814. var engine = scene.getEngine();
  12815. var defines = [];
  12816. var fallbacks = new BABYLON.EffectFallbacks();
  12817. // Textures
  12818. if (scene.texturesEnabled) {
  12819. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12820. if (!this.diffuseTexture.isReady()) {
  12821. return false;
  12822. } else {
  12823. defines.push("#define DIFFUSE");
  12824. }
  12825. }
  12826. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12827. if (!this.ambientTexture.isReady()) {
  12828. return false;
  12829. } else {
  12830. defines.push("#define AMBIENT");
  12831. }
  12832. }
  12833. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12834. if (!this.opacityTexture.isReady()) {
  12835. return false;
  12836. } else {
  12837. defines.push("#define OPACITY");
  12838. if (this.opacityTexture.getAlphaFromRGB) {
  12839. defines.push("#define OPACITYRGB");
  12840. }
  12841. }
  12842. }
  12843. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12844. if (!this.reflectionTexture.isReady()) {
  12845. return false;
  12846. } else {
  12847. defines.push("#define REFLECTION");
  12848. fallbacks.addFallback(0, "REFLECTION");
  12849. }
  12850. }
  12851. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12852. if (!this.emissiveTexture.isReady()) {
  12853. return false;
  12854. } else {
  12855. defines.push("#define EMISSIVE");
  12856. }
  12857. }
  12858. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12859. if (!this.specularTexture.isReady()) {
  12860. return false;
  12861. } else {
  12862. defines.push("#define SPECULAR");
  12863. fallbacks.addFallback(0, "SPECULAR");
  12864. }
  12865. }
  12866. }
  12867. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12868. if (!this.bumpTexture.isReady()) {
  12869. return false;
  12870. } else {
  12871. defines.push("#define BUMP");
  12872. fallbacks.addFallback(0, "BUMP");
  12873. }
  12874. }
  12875. // Effect
  12876. if (this.useSpecularOverAlpha) {
  12877. defines.push("#define SPECULAROVERALPHA");
  12878. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12879. }
  12880. if (scene.clipPlane) {
  12881. defines.push("#define CLIPPLANE");
  12882. }
  12883. if (engine.getAlphaTesting()) {
  12884. defines.push("#define ALPHATEST");
  12885. }
  12886. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12887. defines.push("#define ALPHAFROMDIFFUSE");
  12888. }
  12889. // Point size
  12890. if (this.pointsCloud || scene.forcePointsCloud) {
  12891. defines.push("#define POINTSIZE");
  12892. }
  12893. // Fog
  12894. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12895. defines.push("#define FOG");
  12896. fallbacks.addFallback(1, "FOG");
  12897. }
  12898. var shadowsActivated = false;
  12899. var lightIndex = 0;
  12900. if (scene.lightsEnabled) {
  12901. for (var index = 0; index < scene.lights.length; index++) {
  12902. var light = scene.lights[index];
  12903. if (!light.isEnabled()) {
  12904. continue;
  12905. }
  12906. // Excluded check
  12907. if (light._excludedMeshesIds.length > 0) {
  12908. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12909. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12910. if (excludedMesh) {
  12911. light.excludedMeshes.push(excludedMesh);
  12912. }
  12913. }
  12914. light._excludedMeshesIds = [];
  12915. }
  12916. // Included check
  12917. if (light._includedOnlyMeshesIds.length > 0) {
  12918. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12919. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12920. if (includedOnlyMesh) {
  12921. light.includedOnlyMeshes.push(includedOnlyMesh);
  12922. }
  12923. }
  12924. light._includedOnlyMeshesIds = [];
  12925. }
  12926. if (!light.canAffectMesh(mesh)) {
  12927. continue;
  12928. }
  12929. defines.push("#define LIGHT" + lightIndex);
  12930. if (lightIndex > 0) {
  12931. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12932. }
  12933. var type;
  12934. if (light instanceof BABYLON.SpotLight) {
  12935. type = "#define SPOTLIGHT" + lightIndex;
  12936. } else if (light instanceof BABYLON.HemisphericLight) {
  12937. type = "#define HEMILIGHT" + lightIndex;
  12938. } else {
  12939. type = "#define POINTDIRLIGHT" + lightIndex;
  12940. }
  12941. defines.push(type);
  12942. if (lightIndex > 0) {
  12943. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12944. }
  12945. // Shadows
  12946. if (scene.shadowsEnabled) {
  12947. var shadowGenerator = light.getShadowGenerator();
  12948. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12949. defines.push("#define SHADOW" + lightIndex);
  12950. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12951. if (!shadowsActivated) {
  12952. defines.push("#define SHADOWS");
  12953. shadowsActivated = true;
  12954. }
  12955. if (shadowGenerator.useVarianceShadowMap) {
  12956. defines.push("#define SHADOWVSM" + lightIndex);
  12957. if (lightIndex > 0) {
  12958. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12959. }
  12960. }
  12961. if (shadowGenerator.usePoissonSampling) {
  12962. defines.push("#define SHADOWPCF" + lightIndex);
  12963. if (lightIndex > 0) {
  12964. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12965. }
  12966. }
  12967. }
  12968. }
  12969. lightIndex++;
  12970. if (lightIndex === maxSimultaneousLights)
  12971. break;
  12972. }
  12973. }
  12974. if (StandardMaterial.FresnelEnabled) {
  12975. // Fresnel
  12976. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12977. var fresnelRank = 1;
  12978. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12979. defines.push("#define DIFFUSEFRESNEL");
  12980. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12981. fresnelRank++;
  12982. }
  12983. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12984. defines.push("#define OPACITYFRESNEL");
  12985. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12986. fresnelRank++;
  12987. }
  12988. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12989. defines.push("#define REFLECTIONFRESNEL");
  12990. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12991. fresnelRank++;
  12992. }
  12993. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12994. defines.push("#define EMISSIVEFRESNEL");
  12995. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12996. fresnelRank++;
  12997. }
  12998. defines.push("#define FRESNEL");
  12999. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13000. }
  13001. }
  13002. // Attribs
  13003. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13004. if (mesh) {
  13005. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13006. attribs.push(BABYLON.VertexBuffer.UVKind);
  13007. defines.push("#define UV1");
  13008. }
  13009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13010. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13011. defines.push("#define UV2");
  13012. }
  13013. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13014. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13015. defines.push("#define VERTEXCOLOR");
  13016. if (mesh.hasVertexAlpha) {
  13017. defines.push("#define VERTEXALPHA");
  13018. }
  13019. }
  13020. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13021. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13022. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13023. defines.push("#define BONES");
  13024. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13025. defines.push("#define BONES4");
  13026. fallbacks.addFallback(0, "BONES4");
  13027. }
  13028. // Instances
  13029. if (useInstances) {
  13030. defines.push("#define INSTANCES");
  13031. attribs.push("world0");
  13032. attribs.push("world1");
  13033. attribs.push("world2");
  13034. attribs.push("world3");
  13035. }
  13036. }
  13037. // Get correct effect
  13038. var join = defines.join("\n");
  13039. if (this._cachedDefines !== join) {
  13040. this._cachedDefines = join;
  13041. scene.resetCachedMaterial();
  13042. // Legacy browser patch
  13043. var shaderName = "default";
  13044. if (!scene.getEngine().getCaps().standardDerivatives) {
  13045. shaderName = "legacydefault";
  13046. }
  13047. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  13048. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  13049. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  13050. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  13051. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  13052. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  13053. "vFogInfos", "vFogColor", "pointSize",
  13054. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  13055. "mBones",
  13056. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  13057. "darkness0", "darkness1", "darkness2", "darkness3",
  13058. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  13059. ], [
  13060. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  13061. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  13062. ], join, fallbacks, this.onCompiled, this.onError);
  13063. }
  13064. if (!this._effect.isReady()) {
  13065. return false;
  13066. }
  13067. this._renderId = scene.getRenderId();
  13068. this._wasPreviouslyReady = true;
  13069. return true;
  13070. };
  13071. StandardMaterial.prototype.unbind = function () {
  13072. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13073. this._effect.setTexture("reflection2DSampler", null);
  13074. }
  13075. };
  13076. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13077. this._effect.setMatrix("world", world);
  13078. };
  13079. StandardMaterial.prototype.bind = function (world, mesh) {
  13080. var scene = this.getScene();
  13081. // Matrices
  13082. this.bindOnlyWorldMatrix(world);
  13083. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13084. // Bones
  13085. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13086. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13087. }
  13088. if (scene.getCachedMaterial() !== this) {
  13089. if (StandardMaterial.FresnelEnabled) {
  13090. // Fresnel
  13091. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13092. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13093. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13094. }
  13095. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13096. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13097. }
  13098. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13099. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13100. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13101. }
  13102. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13103. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13104. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13105. }
  13106. }
  13107. // Textures
  13108. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13109. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13110. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13111. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13112. }
  13113. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13114. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13115. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13116. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13117. }
  13118. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13119. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13120. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13121. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13122. }
  13123. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13124. if (this.reflectionTexture.isCube) {
  13125. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13126. } else {
  13127. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13128. }
  13129. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13130. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13131. }
  13132. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13133. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13134. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13135. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13136. }
  13137. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13138. this._effect.setTexture("specularSampler", this.specularTexture);
  13139. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13140. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13141. }
  13142. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13143. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13144. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13145. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13146. }
  13147. // Clip plane
  13148. if (scene.clipPlane) {
  13149. var clipPlane = scene.clipPlane;
  13150. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13151. }
  13152. // Point size
  13153. if (this.pointsCloud) {
  13154. this._effect.setFloat("pointSize", this.pointSize);
  13155. }
  13156. // Colors
  13157. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13158. // Scaling down color according to emissive
  13159. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13160. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13161. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13162. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13163. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13164. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13165. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13166. }
  13167. // Scaling down color according to emissive
  13168. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13169. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13170. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13171. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13172. if (scene.lightsEnabled) {
  13173. var lightIndex = 0;
  13174. for (var index = 0; index < scene.lights.length; index++) {
  13175. var light = scene.lights[index];
  13176. if (!light.isEnabled()) {
  13177. continue;
  13178. }
  13179. if (!light.canAffectMesh(mesh)) {
  13180. continue;
  13181. }
  13182. if (light instanceof BABYLON.PointLight) {
  13183. // Point Light
  13184. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13185. } else if (light instanceof BABYLON.DirectionalLight) {
  13186. // Directional Light
  13187. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13188. } else if (light instanceof BABYLON.SpotLight) {
  13189. // Spot Light
  13190. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13191. } else if (light instanceof BABYLON.HemisphericLight) {
  13192. // Hemispheric Light
  13193. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13194. }
  13195. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13196. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13197. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13198. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13199. // Shadows
  13200. if (scene.shadowsEnabled) {
  13201. var shadowGenerator = light.getShadowGenerator();
  13202. if (mesh.receiveShadows && shadowGenerator) {
  13203. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13204. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13205. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13206. }
  13207. }
  13208. lightIndex++;
  13209. if (lightIndex === maxSimultaneousLights)
  13210. break;
  13211. }
  13212. }
  13213. // View
  13214. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13215. this._effect.setMatrix("view", scene.getViewMatrix());
  13216. }
  13217. // Fog
  13218. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13219. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13220. this._effect.setColor3("vFogColor", scene.fogColor);
  13221. }
  13222. _super.prototype.bind.call(this, world, mesh);
  13223. };
  13224. StandardMaterial.prototype.getAnimatables = function () {
  13225. var results = [];
  13226. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13227. results.push(this.diffuseTexture);
  13228. }
  13229. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13230. results.push(this.ambientTexture);
  13231. }
  13232. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13233. results.push(this.opacityTexture);
  13234. }
  13235. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13236. results.push(this.reflectionTexture);
  13237. }
  13238. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13239. results.push(this.emissiveTexture);
  13240. }
  13241. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13242. results.push(this.specularTexture);
  13243. }
  13244. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13245. results.push(this.bumpTexture);
  13246. }
  13247. return results;
  13248. };
  13249. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13250. if (this.diffuseTexture) {
  13251. this.diffuseTexture.dispose();
  13252. }
  13253. if (this.ambientTexture) {
  13254. this.ambientTexture.dispose();
  13255. }
  13256. if (this.opacityTexture) {
  13257. this.opacityTexture.dispose();
  13258. }
  13259. if (this.reflectionTexture) {
  13260. this.reflectionTexture.dispose();
  13261. }
  13262. if (this.emissiveTexture) {
  13263. this.emissiveTexture.dispose();
  13264. }
  13265. if (this.specularTexture) {
  13266. this.specularTexture.dispose();
  13267. }
  13268. if (this.bumpTexture) {
  13269. this.bumpTexture.dispose();
  13270. }
  13271. _super.prototype.dispose.call(this, forceDisposeEffect);
  13272. };
  13273. StandardMaterial.prototype.clone = function (name) {
  13274. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13275. // Base material
  13276. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13277. newStandardMaterial.alpha = this.alpha;
  13278. newStandardMaterial.fillMode = this.fillMode;
  13279. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13280. // Standard material
  13281. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13282. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13283. }
  13284. if (this.ambientTexture && this.ambientTexture.clone) {
  13285. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13286. }
  13287. if (this.opacityTexture && this.opacityTexture.clone) {
  13288. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13289. }
  13290. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13291. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13292. }
  13293. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13294. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13295. }
  13296. if (this.specularTexture && this.specularTexture.clone) {
  13297. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13298. }
  13299. if (this.bumpTexture && this.bumpTexture.clone) {
  13300. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13301. }
  13302. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13303. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13304. newStandardMaterial.specularColor = this.specularColor.clone();
  13305. newStandardMaterial.specularPower = this.specularPower;
  13306. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13307. return newStandardMaterial;
  13308. };
  13309. StandardMaterial.DiffuseTextureEnabled = true;
  13310. StandardMaterial.AmbientTextureEnabled = true;
  13311. StandardMaterial.OpacityTextureEnabled = true;
  13312. StandardMaterial.ReflectionTextureEnabled = true;
  13313. StandardMaterial.EmissiveTextureEnabled = true;
  13314. StandardMaterial.SpecularTextureEnabled = true;
  13315. StandardMaterial.BumpTextureEnabled = true;
  13316. StandardMaterial.FresnelEnabled = true;
  13317. return StandardMaterial;
  13318. })(BABYLON.Material);
  13319. BABYLON.StandardMaterial = StandardMaterial;
  13320. })(BABYLON || (BABYLON = {}));
  13321. //# sourceMappingURL=babylon.standardMaterial.js.map
  13322. var BABYLON;
  13323. (function (BABYLON) {
  13324. var MultiMaterial = (function (_super) {
  13325. __extends(MultiMaterial, _super);
  13326. function MultiMaterial(name, scene) {
  13327. _super.call(this, name, scene, true);
  13328. this.subMaterials = new Array();
  13329. scene.multiMaterials.push(this);
  13330. }
  13331. // Properties
  13332. MultiMaterial.prototype.getSubMaterial = function (index) {
  13333. if (index < 0 || index >= this.subMaterials.length) {
  13334. return this.getScene().defaultMaterial;
  13335. }
  13336. return this.subMaterials[index];
  13337. };
  13338. // Methods
  13339. MultiMaterial.prototype.isReady = function (mesh) {
  13340. for (var index = 0; index < this.subMaterials.length; index++) {
  13341. var subMaterial = this.subMaterials[index];
  13342. if (subMaterial) {
  13343. if (!this.subMaterials[index].isReady(mesh)) {
  13344. return false;
  13345. }
  13346. }
  13347. }
  13348. return true;
  13349. };
  13350. return MultiMaterial;
  13351. })(BABYLON.Material);
  13352. BABYLON.MultiMaterial = MultiMaterial;
  13353. })(BABYLON || (BABYLON = {}));
  13354. //# sourceMappingURL=babylon.multiMaterial.js.map
  13355. var BABYLON;
  13356. (function (BABYLON) {
  13357. var Database = (function () {
  13358. function Database(urlToScene, callbackManifestChecked) {
  13359. // Handling various flavors of prefixed version of IndexedDB
  13360. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13361. this.callbackManifestChecked = callbackManifestChecked;
  13362. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13363. this.db = null;
  13364. this.enableSceneOffline = false;
  13365. this.enableTexturesOffline = false;
  13366. this.manifestVersionFound = 0;
  13367. this.mustUpdateRessources = false;
  13368. this.hasReachedQuota = false;
  13369. this.checkManifestFile();
  13370. }
  13371. Database.prototype.checkManifestFile = function () {
  13372. var _this = this;
  13373. function noManifestFile() {
  13374. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13375. that.enableSceneOffline = false;
  13376. that.enableTexturesOffline = false;
  13377. that.callbackManifestChecked(false);
  13378. }
  13379. var that = this;
  13380. var manifestURL = this.currentSceneUrl + ".manifest";
  13381. var xhr = new XMLHttpRequest();
  13382. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13383. xhr.open("GET", manifestURLTimeStamped, true);
  13384. xhr.addEventListener("load", function () {
  13385. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13386. try {
  13387. var manifestFile = JSON.parse(xhr.response);
  13388. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13389. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13390. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13391. _this.manifestVersionFound = manifestFile.version;
  13392. }
  13393. if (_this.callbackManifestChecked) {
  13394. _this.callbackManifestChecked(true);
  13395. }
  13396. } catch (ex) {
  13397. noManifestFile();
  13398. }
  13399. } else {
  13400. noManifestFile();
  13401. }
  13402. }, false);
  13403. xhr.addEventListener("error", function (event) {
  13404. noManifestFile();
  13405. }, false);
  13406. try {
  13407. xhr.send();
  13408. } catch (ex) {
  13409. BABYLON.Tools.Error("Error on XHR send request.");
  13410. that.callbackManifestChecked(false);
  13411. }
  13412. };
  13413. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13414. var _this = this;
  13415. function handleError() {
  13416. that.isSupported = false;
  13417. if (errorCallback)
  13418. errorCallback();
  13419. }
  13420. var that = this;
  13421. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13422. // Your browser doesn't support IndexedDB
  13423. this.isSupported = false;
  13424. if (errorCallback)
  13425. errorCallback();
  13426. } else {
  13427. // If the DB hasn't been opened or created yet
  13428. if (!this.db) {
  13429. this.hasReachedQuota = false;
  13430. this.isSupported = true;
  13431. var request = this.idbFactory.open("babylonjs", 1);
  13432. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13433. request.onerror = function (event) {
  13434. handleError();
  13435. };
  13436. // executes when a version change transaction cannot complete due to other active transactions
  13437. request.onblocked = function (event) {
  13438. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13439. handleError();
  13440. };
  13441. // DB has been opened successfully
  13442. request.onsuccess = function (event) {
  13443. _this.db = request.result;
  13444. successCallback();
  13445. };
  13446. // Initialization of the DB. Creating Scenes & Textures stores
  13447. request.onupgradeneeded = function (event) {
  13448. _this.db = (event.target).result;
  13449. try {
  13450. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13451. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13452. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13453. } catch (ex) {
  13454. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13455. handleError();
  13456. }
  13457. };
  13458. } else {
  13459. if (successCallback)
  13460. successCallback();
  13461. }
  13462. }
  13463. };
  13464. Database.prototype.loadImageFromDB = function (url, image) {
  13465. var _this = this;
  13466. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13467. var saveAndLoadImage = function () {
  13468. if (!_this.hasReachedQuota && _this.db !== null) {
  13469. // the texture is not yet in the DB, let's try to save it
  13470. _this._saveImageIntoDBAsync(completeURL, image);
  13471. } else {
  13472. image.src = url;
  13473. }
  13474. };
  13475. if (!this.mustUpdateRessources) {
  13476. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13477. } else {
  13478. saveAndLoadImage();
  13479. }
  13480. };
  13481. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13482. if (this.isSupported && this.db !== null) {
  13483. var texture;
  13484. var transaction = this.db.transaction(["textures"]);
  13485. transaction.onabort = function (event) {
  13486. image.src = url;
  13487. };
  13488. transaction.oncomplete = function (event) {
  13489. var blobTextureURL;
  13490. if (texture) {
  13491. var URL = window.URL || window.webkitURL;
  13492. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13493. image.onerror = function () {
  13494. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13495. image.src = url;
  13496. };
  13497. image.src = blobTextureURL;
  13498. } else {
  13499. notInDBCallback();
  13500. }
  13501. };
  13502. var getRequest = transaction.objectStore("textures").get(url);
  13503. getRequest.onsuccess = function (event) {
  13504. texture = (event.target).result;
  13505. };
  13506. getRequest.onerror = function (event) {
  13507. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13508. image.src = url;
  13509. };
  13510. } else {
  13511. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13512. image.src = url;
  13513. }
  13514. };
  13515. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13516. var _this = this;
  13517. if (this.isSupported) {
  13518. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13519. var generateBlobUrl = function () {
  13520. var blobTextureURL;
  13521. if (blob) {
  13522. var URL = window.URL || window.webkitURL;
  13523. try {
  13524. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13525. } catch (ex) {
  13526. blobTextureURL = URL.createObjectURL(blob);
  13527. }
  13528. }
  13529. image.src = blobTextureURL;
  13530. };
  13531. if (BABYLON.Database.isUASupportingBlobStorage) {
  13532. var xhr = new XMLHttpRequest(), blob;
  13533. xhr.open("GET", url, true);
  13534. xhr.responseType = "blob";
  13535. xhr.addEventListener("load", function () {
  13536. if (xhr.status === 200) {
  13537. // Blob as response (XHR2)
  13538. blob = xhr.response;
  13539. var transaction = _this.db.transaction(["textures"], "readwrite");
  13540. // the transaction could abort because of a QuotaExceededError error
  13541. transaction.onabort = function (event) {
  13542. try {
  13543. if (event.srcElement.error.name === "QuotaExceededError") {
  13544. this.hasReachedQuota = true;
  13545. }
  13546. } catch (ex) {
  13547. }
  13548. generateBlobUrl();
  13549. };
  13550. transaction.oncomplete = function (event) {
  13551. generateBlobUrl();
  13552. };
  13553. var newTexture = { textureUrl: url, data: blob };
  13554. try {
  13555. // Put the blob into the dabase
  13556. var addRequest = transaction.objectStore("textures").put(newTexture);
  13557. addRequest.onsuccess = function (event) {
  13558. };
  13559. addRequest.onerror = function (event) {
  13560. generateBlobUrl();
  13561. };
  13562. } catch (ex) {
  13563. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13564. if (ex.code === 25) {
  13565. BABYLON.Database.isUASupportingBlobStorage = false;
  13566. }
  13567. image.src = url;
  13568. }
  13569. } else {
  13570. image.src = url;
  13571. }
  13572. }, false);
  13573. xhr.addEventListener("error", function (event) {
  13574. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13575. image.src = url;
  13576. }, false);
  13577. xhr.send();
  13578. } else {
  13579. image.src = url;
  13580. }
  13581. } else {
  13582. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13583. image.src = url;
  13584. }
  13585. };
  13586. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13587. var _this = this;
  13588. var updateVersion = function (event) {
  13589. // the version is not yet in the DB or we need to update it
  13590. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13591. };
  13592. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13593. };
  13594. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13595. var _this = this;
  13596. if (this.isSupported) {
  13597. var version;
  13598. try {
  13599. var transaction = this.db.transaction(["versions"]);
  13600. transaction.oncomplete = function (event) {
  13601. if (version) {
  13602. // If the version in the JSON file is > than the version in DB
  13603. if (_this.manifestVersionFound > version.data) {
  13604. _this.mustUpdateRessources = true;
  13605. updateInDBCallback();
  13606. } else {
  13607. callback(version.data);
  13608. }
  13609. } else {
  13610. _this.mustUpdateRessources = true;
  13611. updateInDBCallback();
  13612. }
  13613. };
  13614. transaction.onabort = function (event) {
  13615. callback(-1);
  13616. };
  13617. var getRequest = transaction.objectStore("versions").get(url);
  13618. getRequest.onsuccess = function (event) {
  13619. version = (event.target).result;
  13620. };
  13621. getRequest.onerror = function (event) {
  13622. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13623. callback(-1);
  13624. };
  13625. } catch (ex) {
  13626. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13627. callback(-1);
  13628. }
  13629. } else {
  13630. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13631. callback(-1);
  13632. }
  13633. };
  13634. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13635. var _this = this;
  13636. if (this.isSupported && !this.hasReachedQuota) {
  13637. try {
  13638. // Open a transaction to the database
  13639. var transaction = this.db.transaction(["versions"], "readwrite");
  13640. // the transaction could abort because of a QuotaExceededError error
  13641. transaction.onabort = function (event) {
  13642. try {
  13643. if (event.srcElement.error.name === "QuotaExceededError") {
  13644. _this.hasReachedQuota = true;
  13645. }
  13646. } catch (ex) {
  13647. }
  13648. callback(-1);
  13649. };
  13650. transaction.oncomplete = function (event) {
  13651. callback(_this.manifestVersionFound);
  13652. };
  13653. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13654. // Put the scene into the database
  13655. var addRequest = transaction.objectStore("versions").put(newVersion);
  13656. addRequest.onsuccess = function (event) {
  13657. };
  13658. addRequest.onerror = function (event) {
  13659. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13660. };
  13661. } catch (ex) {
  13662. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13663. callback(-1);
  13664. }
  13665. } else {
  13666. callback(-1);
  13667. }
  13668. };
  13669. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13670. var _this = this;
  13671. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13672. var saveAndLoadFile = function (event) {
  13673. // the scene is not yet in the DB, let's try to save it
  13674. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13675. };
  13676. this._checkVersionFromDB(completeUrl, function (version) {
  13677. if (version !== -1) {
  13678. if (!_this.mustUpdateRessources) {
  13679. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13680. } else {
  13681. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13682. }
  13683. } else {
  13684. errorCallback();
  13685. }
  13686. });
  13687. };
  13688. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13689. if (this.isSupported) {
  13690. var targetStore;
  13691. if (url.indexOf(".babylon") !== -1) {
  13692. targetStore = "scenes";
  13693. } else {
  13694. targetStore = "textures";
  13695. }
  13696. var file;
  13697. var transaction = this.db.transaction([targetStore]);
  13698. transaction.oncomplete = function (event) {
  13699. if (file) {
  13700. callback(file.data);
  13701. } else {
  13702. notInDBCallback();
  13703. }
  13704. };
  13705. transaction.onabort = function (event) {
  13706. notInDBCallback();
  13707. };
  13708. var getRequest = transaction.objectStore(targetStore).get(url);
  13709. getRequest.onsuccess = function (event) {
  13710. file = (event.target).result;
  13711. };
  13712. getRequest.onerror = function (event) {
  13713. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13714. notInDBCallback();
  13715. };
  13716. } else {
  13717. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13718. callback();
  13719. }
  13720. };
  13721. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13722. var _this = this;
  13723. if (this.isSupported) {
  13724. var targetStore;
  13725. if (url.indexOf(".babylon") !== -1) {
  13726. targetStore = "scenes";
  13727. } else {
  13728. targetStore = "textures";
  13729. }
  13730. // Create XHR
  13731. var xhr = new XMLHttpRequest(), fileData;
  13732. xhr.open("GET", url, true);
  13733. if (useArrayBuffer) {
  13734. xhr.responseType = "arraybuffer";
  13735. }
  13736. xhr.onprogress = progressCallback;
  13737. xhr.addEventListener("load", function () {
  13738. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13739. // Blob as response (XHR2)
  13740. //fileData = xhr.responseText;
  13741. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13742. if (!_this.hasReachedQuota) {
  13743. // Open a transaction to the database
  13744. var transaction = _this.db.transaction([targetStore], "readwrite");
  13745. // the transaction could abort because of a QuotaExceededError error
  13746. transaction.onabort = function (event) {
  13747. try {
  13748. if (event.srcElement.error.name === "QuotaExceededError") {
  13749. this.hasReachedQuota = true;
  13750. }
  13751. } catch (ex) {
  13752. }
  13753. callback(fileData);
  13754. };
  13755. transaction.oncomplete = function (event) {
  13756. callback(fileData);
  13757. };
  13758. var newFile;
  13759. if (targetStore === "scenes") {
  13760. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13761. } else {
  13762. newFile = { textureUrl: url, data: fileData };
  13763. }
  13764. try {
  13765. // Put the scene into the database
  13766. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13767. addRequest.onsuccess = function (event) {
  13768. };
  13769. addRequest.onerror = function (event) {
  13770. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13771. };
  13772. } catch (ex) {
  13773. callback(fileData);
  13774. }
  13775. } else {
  13776. callback(fileData);
  13777. }
  13778. } else {
  13779. callback();
  13780. }
  13781. }, false);
  13782. xhr.addEventListener("error", function (event) {
  13783. BABYLON.Tools.Error("error on XHR request.");
  13784. callback();
  13785. }, false);
  13786. xhr.send();
  13787. } else {
  13788. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13789. callback();
  13790. }
  13791. };
  13792. Database.isUASupportingBlobStorage = true;
  13793. Database.parseURL = function (url) {
  13794. var a = document.createElement('a');
  13795. a.href = url;
  13796. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13797. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13798. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13799. return absLocation;
  13800. };
  13801. Database.ReturnFullUrlLocation = function (url) {
  13802. if (url.indexOf("http:/") === -1) {
  13803. return (BABYLON.Database.parseURL(window.location.href) + url);
  13804. } else {
  13805. return url;
  13806. }
  13807. };
  13808. return Database;
  13809. })();
  13810. BABYLON.Database = Database;
  13811. })(BABYLON || (BABYLON = {}));
  13812. //# sourceMappingURL=babylon.database.js.map
  13813. var BABYLON;
  13814. (function (BABYLON) {
  13815. var SpriteManager = (function () {
  13816. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13817. this.name = name;
  13818. this.cellSize = cellSize;
  13819. this.sprites = new Array();
  13820. this.renderingGroupId = 0;
  13821. this.fogEnabled = true;
  13822. this._vertexDeclaration = [3, 4, 4, 4];
  13823. this._vertexStrideSize = 15 * 4;
  13824. this._capacity = capacity;
  13825. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13826. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13827. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13828. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13829. this._scene = scene;
  13830. this._scene.spriteManagers.push(this);
  13831. // VBO
  13832. this._vertexDeclaration = [3, 4, 4, 4];
  13833. this._vertexStrideSize = 15 * 4;
  13834. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13835. var indices = [];
  13836. var index = 0;
  13837. for (var count = 0; count < capacity; count++) {
  13838. indices.push(index);
  13839. indices.push(index + 1);
  13840. indices.push(index + 2);
  13841. indices.push(index);
  13842. indices.push(index + 2);
  13843. indices.push(index + 3);
  13844. index += 4;
  13845. }
  13846. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13847. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13848. // Effects
  13849. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13850. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13851. }
  13852. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13853. var arrayOffset = index * 15;
  13854. if (offsetX == 0)
  13855. offsetX = this._epsilon;
  13856. else if (offsetX == 1)
  13857. offsetX = 1 - this._epsilon;
  13858. if (offsetY == 0)
  13859. offsetY = this._epsilon;
  13860. else if (offsetY == 1)
  13861. offsetY = 1 - this._epsilon;
  13862. this._vertices[arrayOffset] = sprite.position.x;
  13863. this._vertices[arrayOffset + 1] = sprite.position.y;
  13864. this._vertices[arrayOffset + 2] = sprite.position.z;
  13865. this._vertices[arrayOffset + 3] = sprite.angle;
  13866. this._vertices[arrayOffset + 4] = sprite.size;
  13867. this._vertices[arrayOffset + 5] = offsetX;
  13868. this._vertices[arrayOffset + 6] = offsetY;
  13869. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13870. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13871. var offset = (sprite.cellIndex / rowSize) >> 0;
  13872. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13873. this._vertices[arrayOffset + 10] = offset;
  13874. // Color
  13875. this._vertices[arrayOffset + 11] = sprite.color.r;
  13876. this._vertices[arrayOffset + 12] = sprite.color.g;
  13877. this._vertices[arrayOffset + 13] = sprite.color.b;
  13878. this._vertices[arrayOffset + 14] = sprite.color.a;
  13879. };
  13880. SpriteManager.prototype.render = function () {
  13881. // Check
  13882. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13883. return;
  13884. var engine = this._scene.getEngine();
  13885. var baseSize = this._spriteTexture.getBaseSize();
  13886. // Sprites
  13887. var deltaTime = engine.getDeltaTime();
  13888. var max = Math.min(this._capacity, this.sprites.length);
  13889. var rowSize = baseSize.width / this.cellSize;
  13890. var offset = 0;
  13891. for (var index = 0; index < max; index++) {
  13892. var sprite = this.sprites[index];
  13893. if (!sprite) {
  13894. continue;
  13895. }
  13896. sprite._animate(deltaTime);
  13897. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13898. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13899. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13900. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13901. }
  13902. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13903. // Render
  13904. var effect = this._effectBase;
  13905. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13906. effect = this._effectFog;
  13907. }
  13908. engine.enableEffect(effect);
  13909. var viewMatrix = this._scene.getViewMatrix();
  13910. effect.setTexture("diffuseSampler", this._spriteTexture);
  13911. effect.setMatrix("view", viewMatrix);
  13912. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13913. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13914. // Fog
  13915. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13916. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13917. effect.setColor3("vFogColor", this._scene.fogColor);
  13918. }
  13919. // VBOs
  13920. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13921. // Draw order
  13922. effect.setBool("alphaTest", true);
  13923. engine.setColorWrite(false);
  13924. engine.draw(true, 0, max * 6);
  13925. engine.setColorWrite(true);
  13926. effect.setBool("alphaTest", false);
  13927. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13928. engine.draw(true, 0, max * 6);
  13929. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13930. };
  13931. SpriteManager.prototype.dispose = function () {
  13932. if (this._vertexBuffer) {
  13933. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13934. this._vertexBuffer = null;
  13935. }
  13936. if (this._indexBuffer) {
  13937. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13938. this._indexBuffer = null;
  13939. }
  13940. if (this._spriteTexture) {
  13941. this._spriteTexture.dispose();
  13942. this._spriteTexture = null;
  13943. }
  13944. // Remove from scene
  13945. var index = this._scene.spriteManagers.indexOf(this);
  13946. this._scene.spriteManagers.splice(index, 1);
  13947. // Callback
  13948. if (this.onDispose) {
  13949. this.onDispose();
  13950. }
  13951. };
  13952. return SpriteManager;
  13953. })();
  13954. BABYLON.SpriteManager = SpriteManager;
  13955. })(BABYLON || (BABYLON = {}));
  13956. //# sourceMappingURL=babylon.spriteManager.js.map
  13957. var BABYLON;
  13958. (function (BABYLON) {
  13959. var Sprite = (function () {
  13960. function Sprite(name, manager) {
  13961. this.name = name;
  13962. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13963. this.size = 1.0;
  13964. this.angle = 0;
  13965. this.cellIndex = 0;
  13966. this.invertU = 0;
  13967. this.invertV = 0;
  13968. this.animations = new Array();
  13969. this._animationStarted = false;
  13970. this._loopAnimation = false;
  13971. this._fromIndex = 0;
  13972. this._toIndex = 0;
  13973. this._delay = 0;
  13974. this._direction = 1;
  13975. this._frameCount = 0;
  13976. this._time = 0;
  13977. this._manager = manager;
  13978. this._manager.sprites.push(this);
  13979. this.position = BABYLON.Vector3.Zero();
  13980. }
  13981. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13982. this._fromIndex = from;
  13983. this._toIndex = to;
  13984. this._loopAnimation = loop;
  13985. this._delay = delay;
  13986. this._animationStarted = true;
  13987. this._direction = from < to ? 1 : -1;
  13988. this.cellIndex = from;
  13989. this._time = 0;
  13990. };
  13991. Sprite.prototype.stopAnimation = function () {
  13992. this._animationStarted = false;
  13993. };
  13994. Sprite.prototype._animate = function (deltaTime) {
  13995. if (!this._animationStarted)
  13996. return;
  13997. this._time += deltaTime;
  13998. if (this._time > this._delay) {
  13999. this._time = this._time % this._delay;
  14000. this.cellIndex += this._direction;
  14001. if (this.cellIndex == this._toIndex) {
  14002. if (this._loopAnimation) {
  14003. this.cellIndex = this._fromIndex;
  14004. } else {
  14005. this._animationStarted = false;
  14006. if (this.disposeWhenFinishedAnimating) {
  14007. this.dispose();
  14008. }
  14009. }
  14010. }
  14011. }
  14012. };
  14013. Sprite.prototype.dispose = function () {
  14014. for (var i = 0; i < this._manager.sprites.length; i++) {
  14015. if (this._manager.sprites[i] == this) {
  14016. this._manager.sprites.splice(i, 1);
  14017. }
  14018. }
  14019. };
  14020. return Sprite;
  14021. })();
  14022. BABYLON.Sprite = Sprite;
  14023. })(BABYLON || (BABYLON = {}));
  14024. //# sourceMappingURL=babylon.sprite.js.map
  14025. var BABYLON;
  14026. (function (BABYLON) {
  14027. var Layer = (function () {
  14028. function Layer(name, imgUrl, scene, isBackground, color) {
  14029. this.name = name;
  14030. this._vertexDeclaration = [2];
  14031. this._vertexStrideSize = 2 * 4;
  14032. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14033. this.isBackground = isBackground === undefined ? true : isBackground;
  14034. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14035. this._scene = scene;
  14036. this._scene.layers.push(this);
  14037. // VBO
  14038. var vertices = [];
  14039. vertices.push(1, 1);
  14040. vertices.push(-1, 1);
  14041. vertices.push(-1, -1);
  14042. vertices.push(1, -1);
  14043. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14044. // Indices
  14045. var indices = [];
  14046. indices.push(0);
  14047. indices.push(1);
  14048. indices.push(2);
  14049. indices.push(0);
  14050. indices.push(2);
  14051. indices.push(3);
  14052. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14053. // Effects
  14054. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14055. }
  14056. Layer.prototype.render = function () {
  14057. // Check
  14058. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14059. return;
  14060. var engine = this._scene.getEngine();
  14061. // Render
  14062. engine.enableEffect(this._effect);
  14063. engine.setState(false);
  14064. // Texture
  14065. this._effect.setTexture("textureSampler", this.texture);
  14066. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14067. // Color
  14068. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14069. // VBOs
  14070. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14071. // Draw order
  14072. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14073. engine.draw(true, 0, 6);
  14074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14075. };
  14076. Layer.prototype.dispose = function () {
  14077. if (this._vertexBuffer) {
  14078. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14079. this._vertexBuffer = null;
  14080. }
  14081. if (this._indexBuffer) {
  14082. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14083. this._indexBuffer = null;
  14084. }
  14085. if (this.texture) {
  14086. this.texture.dispose();
  14087. this.texture = null;
  14088. }
  14089. // Remove from scene
  14090. var index = this._scene.layers.indexOf(this);
  14091. this._scene.layers.splice(index, 1);
  14092. // Callback
  14093. if (this.onDispose) {
  14094. this.onDispose();
  14095. }
  14096. };
  14097. return Layer;
  14098. })();
  14099. BABYLON.Layer = Layer;
  14100. })(BABYLON || (BABYLON = {}));
  14101. //# sourceMappingURL=babylon.layer.js.map
  14102. var BABYLON;
  14103. (function (BABYLON) {
  14104. var Particle = (function () {
  14105. function Particle() {
  14106. this.position = BABYLON.Vector3.Zero();
  14107. this.direction = BABYLON.Vector3.Zero();
  14108. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14109. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14110. this.lifeTime = 1.0;
  14111. this.age = 0;
  14112. this.size = 0;
  14113. this.angle = 0;
  14114. this.angularSpeed = 0;
  14115. }
  14116. Particle.prototype.copyTo = function (other) {
  14117. other.position.copyFrom(this.position);
  14118. other.direction.copyFrom(this.direction);
  14119. other.color.copyFrom(this.color);
  14120. other.colorStep.copyFrom(this.colorStep);
  14121. other.lifeTime = this.lifeTime;
  14122. other.age = this.age;
  14123. other.size = this.size;
  14124. other.angle = this.angle;
  14125. other.angularSpeed = this.angularSpeed;
  14126. };
  14127. return Particle;
  14128. })();
  14129. BABYLON.Particle = Particle;
  14130. })(BABYLON || (BABYLON = {}));
  14131. //# sourceMappingURL=babylon.particle.js.map
  14132. var BABYLON;
  14133. (function (BABYLON) {
  14134. var randomNumber = function (min, max) {
  14135. if (min === max) {
  14136. return (min);
  14137. }
  14138. var random = Math.random();
  14139. return ((random * (max - min)) + min);
  14140. };
  14141. var ParticleSystem = (function () {
  14142. function ParticleSystem(name, capacity, scene, customEffect) {
  14143. var _this = this;
  14144. this.name = name;
  14145. this.renderingGroupId = 0;
  14146. this.emitter = null;
  14147. this.emitRate = 10;
  14148. this.manualEmitCount = -1;
  14149. this.updateSpeed = 0.01;
  14150. this.targetStopDuration = 0;
  14151. this.disposeOnStop = false;
  14152. this.minEmitPower = 1;
  14153. this.maxEmitPower = 1;
  14154. this.minLifeTime = 1;
  14155. this.maxLifeTime = 1;
  14156. this.minSize = 1;
  14157. this.maxSize = 1;
  14158. this.minAngularSpeed = 0;
  14159. this.maxAngularSpeed = 0;
  14160. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14161. this.forceDepthWrite = false;
  14162. this.gravity = BABYLON.Vector3.Zero();
  14163. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14164. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14165. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14166. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14167. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14168. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14169. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14170. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14171. this.particles = new Array();
  14172. this._vertexDeclaration = [3, 4, 4];
  14173. this._vertexStrideSize = 11 * 4;
  14174. this._stockParticles = new Array();
  14175. this._newPartsExcess = 0;
  14176. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14177. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14178. this._scaledDirection = BABYLON.Vector3.Zero();
  14179. this._scaledGravity = BABYLON.Vector3.Zero();
  14180. this._currentRenderId = -1;
  14181. this._started = false;
  14182. this._stopped = false;
  14183. this._actualFrame = 0;
  14184. this.id = name;
  14185. this._capacity = capacity;
  14186. this._scene = scene;
  14187. this._customEffect = customEffect;
  14188. scene.particleSystems.push(this);
  14189. // VBO
  14190. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14191. var indices = [];
  14192. var index = 0;
  14193. for (var count = 0; count < capacity; count++) {
  14194. indices.push(index);
  14195. indices.push(index + 1);
  14196. indices.push(index + 2);
  14197. indices.push(index);
  14198. indices.push(index + 2);
  14199. indices.push(index + 3);
  14200. index += 4;
  14201. }
  14202. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14203. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14204. // Default behaviors
  14205. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14206. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14207. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14208. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14209. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14210. };
  14211. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14212. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14213. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14214. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14215. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14216. };
  14217. this.updateFunction = function (particles) {
  14218. for (var index = 0; index < particles.length; index++) {
  14219. var particle = particles[index];
  14220. particle.age += _this._scaledUpdateSpeed;
  14221. if (particle.age >= particle.lifeTime) {
  14222. _this.recycleParticle(particle);
  14223. index--;
  14224. continue;
  14225. } else {
  14226. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14227. particle.color.addInPlace(_this._scaledColorStep);
  14228. if (particle.color.a < 0)
  14229. particle.color.a = 0;
  14230. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14231. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14232. particle.position.addInPlace(_this._scaledDirection);
  14233. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14234. particle.direction.addInPlace(_this._scaledGravity);
  14235. }
  14236. }
  14237. };
  14238. }
  14239. ParticleSystem.prototype.recycleParticle = function (particle) {
  14240. var lastParticle = this.particles.pop();
  14241. if (lastParticle !== particle) {
  14242. lastParticle.copyTo(particle);
  14243. this._stockParticles.push(lastParticle);
  14244. }
  14245. };
  14246. ParticleSystem.prototype.getCapacity = function () {
  14247. return this._capacity;
  14248. };
  14249. ParticleSystem.prototype.isAlive = function () {
  14250. return this._alive;
  14251. };
  14252. ParticleSystem.prototype.isStarted = function () {
  14253. return this._started;
  14254. };
  14255. ParticleSystem.prototype.start = function () {
  14256. this._started = true;
  14257. this._stopped = false;
  14258. this._actualFrame = 0;
  14259. };
  14260. ParticleSystem.prototype.stop = function () {
  14261. this._stopped = true;
  14262. };
  14263. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14264. var offset = index * 11;
  14265. this._vertices[offset] = particle.position.x;
  14266. this._vertices[offset + 1] = particle.position.y;
  14267. this._vertices[offset + 2] = particle.position.z;
  14268. this._vertices[offset + 3] = particle.color.r;
  14269. this._vertices[offset + 4] = particle.color.g;
  14270. this._vertices[offset + 5] = particle.color.b;
  14271. this._vertices[offset + 6] = particle.color.a;
  14272. this._vertices[offset + 7] = particle.angle;
  14273. this._vertices[offset + 8] = particle.size;
  14274. this._vertices[offset + 9] = offsetX;
  14275. this._vertices[offset + 10] = offsetY;
  14276. };
  14277. ParticleSystem.prototype._update = function (newParticles) {
  14278. // Update current
  14279. this._alive = this.particles.length > 0;
  14280. this.updateFunction(this.particles);
  14281. // Add new ones
  14282. var worldMatrix;
  14283. if (this.emitter.position) {
  14284. worldMatrix = this.emitter.getWorldMatrix();
  14285. } else {
  14286. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14287. }
  14288. for (var index = 0; index < newParticles; index++) {
  14289. if (this.particles.length === this._capacity) {
  14290. break;
  14291. }
  14292. if (this._stockParticles.length !== 0) {
  14293. var particle = this._stockParticles.pop();
  14294. particle.age = 0;
  14295. } else {
  14296. particle = new BABYLON.Particle();
  14297. }
  14298. this.particles.push(particle);
  14299. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14300. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14301. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14302. particle.size = randomNumber(this.minSize, this.maxSize);
  14303. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14304. this.startPositionFunction(worldMatrix, particle.position);
  14305. var step = randomNumber(0, 1.0);
  14306. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14307. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14308. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14309. }
  14310. };
  14311. ParticleSystem.prototype._getEffect = function () {
  14312. if (this._customEffect) {
  14313. return this._customEffect;
  14314. }
  14315. ;
  14316. var defines = [];
  14317. if (this._scene.clipPlane) {
  14318. defines.push("#define CLIPPLANE");
  14319. }
  14320. // Effect
  14321. var join = defines.join("\n");
  14322. if (this._cachedDefines !== join) {
  14323. this._cachedDefines = join;
  14324. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14325. }
  14326. return this._effect;
  14327. };
  14328. ParticleSystem.prototype.animate = function () {
  14329. if (!this._started)
  14330. return;
  14331. var effect = this._getEffect();
  14332. // Check
  14333. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14334. return;
  14335. if (this._currentRenderId === this._scene.getRenderId()) {
  14336. return;
  14337. }
  14338. this._currentRenderId = this._scene.getRenderId();
  14339. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14340. // determine the number of particles we need to create
  14341. var emitCout;
  14342. if (this.manualEmitCount > -1) {
  14343. emitCout = this.manualEmitCount;
  14344. this.manualEmitCount = 0;
  14345. } else {
  14346. emitCout = this.emitRate;
  14347. }
  14348. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14349. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14350. if (this._newPartsExcess > 1.0) {
  14351. newParticles += this._newPartsExcess >> 0;
  14352. this._newPartsExcess -= this._newPartsExcess >> 0;
  14353. }
  14354. this._alive = false;
  14355. if (!this._stopped) {
  14356. this._actualFrame += this._scaledUpdateSpeed;
  14357. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14358. this.stop();
  14359. } else {
  14360. newParticles = 0;
  14361. }
  14362. this._update(newParticles);
  14363. // Stopped?
  14364. if (this._stopped) {
  14365. if (!this._alive) {
  14366. this._started = false;
  14367. if (this.disposeOnStop) {
  14368. this._scene._toBeDisposed.push(this);
  14369. }
  14370. }
  14371. }
  14372. // Update VBO
  14373. var offset = 0;
  14374. for (var index = 0; index < this.particles.length; index++) {
  14375. var particle = this.particles[index];
  14376. this._appendParticleVertex(offset++, particle, 0, 0);
  14377. this._appendParticleVertex(offset++, particle, 1, 0);
  14378. this._appendParticleVertex(offset++, particle, 1, 1);
  14379. this._appendParticleVertex(offset++, particle, 0, 1);
  14380. }
  14381. var engine = this._scene.getEngine();
  14382. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14383. };
  14384. ParticleSystem.prototype.render = function () {
  14385. var effect = this._getEffect();
  14386. // Check
  14387. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14388. return 0;
  14389. var engine = this._scene.getEngine();
  14390. // Render
  14391. engine.enableEffect(effect);
  14392. engine.setState(false);
  14393. var viewMatrix = this._scene.getViewMatrix();
  14394. effect.setTexture("diffuseSampler", this.particleTexture);
  14395. effect.setMatrix("view", viewMatrix);
  14396. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14397. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14398. if (this._scene.clipPlane) {
  14399. var clipPlane = this._scene.clipPlane;
  14400. var invView = viewMatrix.clone();
  14401. invView.invert();
  14402. effect.setMatrix("invView", invView);
  14403. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14404. }
  14405. // VBOs
  14406. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14407. // Draw order
  14408. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14409. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14410. } else {
  14411. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14412. }
  14413. if (this.forceDepthWrite) {
  14414. engine.setDepthWrite(true);
  14415. }
  14416. engine.draw(true, 0, this.particles.length * 6);
  14417. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14418. return this.particles.length;
  14419. };
  14420. ParticleSystem.prototype.dispose = function () {
  14421. if (this._vertexBuffer) {
  14422. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14423. this._vertexBuffer = null;
  14424. }
  14425. if (this._indexBuffer) {
  14426. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14427. this._indexBuffer = null;
  14428. }
  14429. if (this.particleTexture) {
  14430. this.particleTexture.dispose();
  14431. this.particleTexture = null;
  14432. }
  14433. // Remove from scene
  14434. var index = this._scene.particleSystems.indexOf(this);
  14435. this._scene.particleSystems.splice(index, 1);
  14436. // Callback
  14437. if (this.onDispose) {
  14438. this.onDispose();
  14439. }
  14440. };
  14441. // Clone
  14442. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14443. var result = new ParticleSystem(name, this._capacity, this._scene);
  14444. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14445. if (newEmitter === undefined) {
  14446. newEmitter = this.emitter;
  14447. }
  14448. result.emitter = newEmitter;
  14449. if (this.particleTexture) {
  14450. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14451. }
  14452. result.start();
  14453. return result;
  14454. };
  14455. ParticleSystem.BLENDMODE_ONEONE = 0;
  14456. ParticleSystem.BLENDMODE_STANDARD = 1;
  14457. return ParticleSystem;
  14458. })();
  14459. BABYLON.ParticleSystem = ParticleSystem;
  14460. })(BABYLON || (BABYLON = {}));
  14461. //# sourceMappingURL=babylon.particleSystem.js.map
  14462. var BABYLON;
  14463. (function (BABYLON) {
  14464. var Animation = (function () {
  14465. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14466. this.name = name;
  14467. this.targetProperty = targetProperty;
  14468. this.framePerSecond = framePerSecond;
  14469. this.dataType = dataType;
  14470. this.loopMode = loopMode;
  14471. this._offsetsCache = {};
  14472. this._highLimitsCache = {};
  14473. this._stopped = false;
  14474. this.targetPropertyPath = targetProperty.split(".");
  14475. this.dataType = dataType;
  14476. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14477. }
  14478. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14479. var dataType = undefined;
  14480. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14481. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14482. } else if (from instanceof BABYLON.Quaternion) {
  14483. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14484. } else if (from instanceof BABYLON.Vector3) {
  14485. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14486. } else if (from instanceof BABYLON.Vector2) {
  14487. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14488. } else if (from instanceof BABYLON.Color3) {
  14489. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14490. }
  14491. if (dataType == undefined) {
  14492. return;
  14493. }
  14494. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14495. var keys = [];
  14496. keys.push({ frame: 0, value: from });
  14497. keys.push({ frame: totalFrame, value: to });
  14498. animation.setKeys(keys);
  14499. mesh.animations.push(animation);
  14500. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14501. };
  14502. // Methods
  14503. Animation.prototype.isStopped = function () {
  14504. return this._stopped;
  14505. };
  14506. Animation.prototype.getKeys = function () {
  14507. return this._keys;
  14508. };
  14509. Animation.prototype.getEasingFunction = function () {
  14510. return this._easingFunction;
  14511. };
  14512. Animation.prototype.setEasingFunction = function (easingFunction) {
  14513. this._easingFunction = easingFunction;
  14514. };
  14515. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14516. return startValue + (endValue - startValue) * gradient;
  14517. };
  14518. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14519. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14520. };
  14521. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14522. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14523. };
  14524. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14525. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14526. };
  14527. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14528. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14529. };
  14530. Animation.prototype.clone = function () {
  14531. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14532. clone.setKeys(this._keys);
  14533. return clone;
  14534. };
  14535. Animation.prototype.setKeys = function (values) {
  14536. this._keys = values.slice(0);
  14537. this._offsetsCache = {};
  14538. this._highLimitsCache = {};
  14539. };
  14540. Animation.prototype._getKeyValue = function (value) {
  14541. if (typeof value === "function") {
  14542. return value();
  14543. }
  14544. return value;
  14545. };
  14546. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14547. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14548. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14549. }
  14550. this.currentFrame = currentFrame;
  14551. for (var key = 0; key < this._keys.length; key++) {
  14552. // for each frame, we need the key just before the frame superior
  14553. if (this._keys[key + 1].frame >= currentFrame) {
  14554. var startValue = this._getKeyValue(this._keys[key].value);
  14555. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14556. // gradient : percent of currentFrame between the frame inf and the frame sup
  14557. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14558. // check for easingFunction and correction of gradient
  14559. if (this._easingFunction != null) {
  14560. gradient = this._easingFunction.ease(gradient);
  14561. }
  14562. switch (this.dataType) {
  14563. case Animation.ANIMATIONTYPE_FLOAT:
  14564. switch (loopMode) {
  14565. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14566. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14567. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14568. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14569. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14570. }
  14571. break;
  14572. case Animation.ANIMATIONTYPE_QUATERNION:
  14573. var quaternion = null;
  14574. switch (loopMode) {
  14575. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14576. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14577. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14578. break;
  14579. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14580. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14581. break;
  14582. }
  14583. return quaternion;
  14584. case Animation.ANIMATIONTYPE_VECTOR3:
  14585. switch (loopMode) {
  14586. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14587. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14588. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14589. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14590. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14591. }
  14592. case Animation.ANIMATIONTYPE_VECTOR2:
  14593. switch (loopMode) {
  14594. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14595. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14596. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14597. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14598. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14599. }
  14600. case Animation.ANIMATIONTYPE_COLOR3:
  14601. switch (loopMode) {
  14602. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14603. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14604. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14605. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14606. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14607. }
  14608. case Animation.ANIMATIONTYPE_MATRIX:
  14609. switch (loopMode) {
  14610. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14611. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14612. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14613. return startValue;
  14614. }
  14615. default:
  14616. break;
  14617. }
  14618. break;
  14619. }
  14620. }
  14621. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14622. };
  14623. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14624. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14625. this._stopped = true;
  14626. return false;
  14627. }
  14628. var returnValue = true;
  14629. // Adding a start key at frame 0 if missing
  14630. if (this._keys[0].frame !== 0) {
  14631. var newKey = { frame: 0, value: this._keys[0].value };
  14632. this._keys.splice(0, 0, newKey);
  14633. }
  14634. // Check limits
  14635. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14636. from = this._keys[0].frame;
  14637. }
  14638. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14639. to = this._keys[this._keys.length - 1].frame;
  14640. }
  14641. // Compute ratio
  14642. var range = to - from;
  14643. var offsetValue;
  14644. // ratio represents the frame delta between from and to
  14645. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14646. var highLimitValue = 0;
  14647. if (ratio > range && !loop) {
  14648. returnValue = false;
  14649. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14650. } else {
  14651. // Get max value if required
  14652. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14653. var keyOffset = to.toString() + from.toString();
  14654. if (!this._offsetsCache[keyOffset]) {
  14655. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14656. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14657. switch (this.dataType) {
  14658. case Animation.ANIMATIONTYPE_FLOAT:
  14659. this._offsetsCache[keyOffset] = toValue - fromValue;
  14660. break;
  14661. case Animation.ANIMATIONTYPE_QUATERNION:
  14662. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14663. break;
  14664. case Animation.ANIMATIONTYPE_VECTOR3:
  14665. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14666. case Animation.ANIMATIONTYPE_VECTOR2:
  14667. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14668. case Animation.ANIMATIONTYPE_COLOR3:
  14669. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14670. default:
  14671. break;
  14672. }
  14673. this._highLimitsCache[keyOffset] = toValue;
  14674. }
  14675. highLimitValue = this._highLimitsCache[keyOffset];
  14676. offsetValue = this._offsetsCache[keyOffset];
  14677. }
  14678. }
  14679. if (offsetValue === undefined) {
  14680. switch (this.dataType) {
  14681. case Animation.ANIMATIONTYPE_FLOAT:
  14682. offsetValue = 0;
  14683. break;
  14684. case Animation.ANIMATIONTYPE_QUATERNION:
  14685. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14686. break;
  14687. case Animation.ANIMATIONTYPE_VECTOR3:
  14688. offsetValue = BABYLON.Vector3.Zero();
  14689. break;
  14690. case Animation.ANIMATIONTYPE_VECTOR2:
  14691. offsetValue = BABYLON.Vector2.Zero();
  14692. break;
  14693. case Animation.ANIMATIONTYPE_COLOR3:
  14694. offsetValue = BABYLON.Color3.Black();
  14695. }
  14696. }
  14697. // Compute value
  14698. var repeatCount = (ratio / range) >> 0;
  14699. var currentFrame = returnValue ? from + ratio % range : to;
  14700. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14701. // Set value
  14702. if (this.targetPropertyPath.length > 1) {
  14703. var property = this._target[this.targetPropertyPath[0]];
  14704. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14705. property = property[this.targetPropertyPath[index]];
  14706. }
  14707. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14708. } else {
  14709. this._target[this.targetPropertyPath[0]] = currentValue;
  14710. }
  14711. if (this._target.markAsDirty) {
  14712. this._target.markAsDirty(this.targetProperty);
  14713. }
  14714. if (!returnValue) {
  14715. this._stopped = true;
  14716. }
  14717. return returnValue;
  14718. };
  14719. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14720. get: function () {
  14721. return Animation._ANIMATIONTYPE_FLOAT;
  14722. },
  14723. enumerable: true,
  14724. configurable: true
  14725. });
  14726. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14727. get: function () {
  14728. return Animation._ANIMATIONTYPE_VECTOR3;
  14729. },
  14730. enumerable: true,
  14731. configurable: true
  14732. });
  14733. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14734. get: function () {
  14735. return Animation._ANIMATIONTYPE_VECTOR2;
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14741. get: function () {
  14742. return Animation._ANIMATIONTYPE_QUATERNION;
  14743. },
  14744. enumerable: true,
  14745. configurable: true
  14746. });
  14747. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14748. get: function () {
  14749. return Animation._ANIMATIONTYPE_MATRIX;
  14750. },
  14751. enumerable: true,
  14752. configurable: true
  14753. });
  14754. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14755. get: function () {
  14756. return Animation._ANIMATIONTYPE_COLOR3;
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14762. get: function () {
  14763. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14769. get: function () {
  14770. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14776. get: function () {
  14777. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Animation._ANIMATIONTYPE_FLOAT = 0;
  14783. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14784. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14785. Animation._ANIMATIONTYPE_MATRIX = 3;
  14786. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14787. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14788. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14789. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14790. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14791. return Animation;
  14792. })();
  14793. BABYLON.Animation = Animation;
  14794. })(BABYLON || (BABYLON = {}));
  14795. //# sourceMappingURL=babylon.animation.js.map
  14796. var BABYLON;
  14797. (function (BABYLON) {
  14798. var Animatable = (function () {
  14799. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14800. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14801. if (typeof toFrame === "undefined") { toFrame = 100; }
  14802. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14803. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14804. this.target = target;
  14805. this.fromFrame = fromFrame;
  14806. this.toFrame = toFrame;
  14807. this.loopAnimation = loopAnimation;
  14808. this.speedRatio = speedRatio;
  14809. this.onAnimationEnd = onAnimationEnd;
  14810. this._animations = new Array();
  14811. this._paused = false;
  14812. this.animationStarted = false;
  14813. if (animations) {
  14814. this.appendAnimations(target, animations);
  14815. }
  14816. this._scene = scene;
  14817. scene._activeAnimatables.push(this);
  14818. }
  14819. // Methods
  14820. Animatable.prototype.appendAnimations = function (target, animations) {
  14821. for (var index = 0; index < animations.length; index++) {
  14822. var animation = animations[index];
  14823. animation._target = target;
  14824. this._animations.push(animation);
  14825. }
  14826. };
  14827. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14828. var animations = this._animations;
  14829. for (var index = 0; index < animations.length; index++) {
  14830. if (animations[index].targetProperty === property) {
  14831. return animations[index];
  14832. }
  14833. }
  14834. return null;
  14835. };
  14836. Animatable.prototype.pause = function () {
  14837. if (this._paused) {
  14838. return;
  14839. }
  14840. this._paused = true;
  14841. };
  14842. Animatable.prototype.restart = function () {
  14843. this._paused = false;
  14844. };
  14845. Animatable.prototype.stop = function () {
  14846. var index = this._scene._activeAnimatables.indexOf(this);
  14847. if (index > -1) {
  14848. this._scene._activeAnimatables.splice(index, 1);
  14849. }
  14850. if (this.onAnimationEnd) {
  14851. this.onAnimationEnd();
  14852. }
  14853. };
  14854. Animatable.prototype._animate = function (delay) {
  14855. if (this._paused) {
  14856. if (!this._pausedDelay) {
  14857. this._pausedDelay = delay;
  14858. }
  14859. return true;
  14860. }
  14861. if (!this._localDelayOffset) {
  14862. this._localDelayOffset = delay;
  14863. } else if (this._pausedDelay) {
  14864. this._localDelayOffset += delay - this._pausedDelay;
  14865. this._pausedDelay = null;
  14866. }
  14867. // Animating
  14868. var running = false;
  14869. var animations = this._animations;
  14870. for (var index = 0; index < animations.length; index++) {
  14871. var animation = animations[index];
  14872. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14873. running = running || isRunning;
  14874. }
  14875. if (!running && this.onAnimationEnd) {
  14876. this.onAnimationEnd();
  14877. }
  14878. return running;
  14879. };
  14880. return Animatable;
  14881. })();
  14882. BABYLON.Animatable = Animatable;
  14883. })(BABYLON || (BABYLON = {}));
  14884. //# sourceMappingURL=babylon.animatable.js.map
  14885. var BABYLON;
  14886. (function (BABYLON) {
  14887. var EasingFunction = (function () {
  14888. function EasingFunction() {
  14889. // Properties
  14890. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14891. }
  14892. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14893. get: function () {
  14894. return EasingFunction._EASINGMODE_EASEIN;
  14895. },
  14896. enumerable: true,
  14897. configurable: true
  14898. });
  14899. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14900. get: function () {
  14901. return EasingFunction._EASINGMODE_EASEOUT;
  14902. },
  14903. enumerable: true,
  14904. configurable: true
  14905. });
  14906. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14907. get: function () {
  14908. return EasingFunction._EASINGMODE_EASEINOUT;
  14909. },
  14910. enumerable: true,
  14911. configurable: true
  14912. });
  14913. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14914. var n = Math.min(Math.max(easingMode, 0), 2);
  14915. this._easingMode = n;
  14916. };
  14917. EasingFunction.prototype.getEasingMode = function () {
  14918. return this._easingMode;
  14919. };
  14920. EasingFunction.prototype.easeInCore = function (gradient) {
  14921. throw new Error('You must implement this method');
  14922. };
  14923. EasingFunction.prototype.ease = function (gradient) {
  14924. switch (this._easingMode) {
  14925. case EasingFunction.EASINGMODE_EASEIN:
  14926. return this.easeInCore(gradient);
  14927. case EasingFunction.EASINGMODE_EASEOUT:
  14928. return (1 - this.easeInCore(1 - gradient));
  14929. }
  14930. if (gradient >= 0.5) {
  14931. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14932. }
  14933. return (this.easeInCore(gradient * 2) * 0.5);
  14934. };
  14935. EasingFunction._EASINGMODE_EASEIN = 0;
  14936. EasingFunction._EASINGMODE_EASEOUT = 1;
  14937. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14938. return EasingFunction;
  14939. })();
  14940. BABYLON.EasingFunction = EasingFunction;
  14941. var CircleEase = (function (_super) {
  14942. __extends(CircleEase, _super);
  14943. function CircleEase() {
  14944. _super.apply(this, arguments);
  14945. }
  14946. CircleEase.prototype.easeInCore = function (gradient) {
  14947. gradient = Math.max(0, Math.min(1, gradient));
  14948. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14949. };
  14950. return CircleEase;
  14951. })(EasingFunction);
  14952. BABYLON.CircleEase = CircleEase;
  14953. var BackEase = (function (_super) {
  14954. __extends(BackEase, _super);
  14955. function BackEase(amplitude) {
  14956. if (typeof amplitude === "undefined") { amplitude = 1; }
  14957. _super.call(this);
  14958. this.amplitude = amplitude;
  14959. }
  14960. BackEase.prototype.easeInCore = function (gradient) {
  14961. var num = Math.max(0, this.amplitude);
  14962. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14963. };
  14964. return BackEase;
  14965. })(EasingFunction);
  14966. BABYLON.BackEase = BackEase;
  14967. var BounceEase = (function (_super) {
  14968. __extends(BounceEase, _super);
  14969. function BounceEase(bounces, bounciness) {
  14970. if (typeof bounces === "undefined") { bounces = 3; }
  14971. if (typeof bounciness === "undefined") { bounciness = 2; }
  14972. _super.call(this);
  14973. this.bounces = bounces;
  14974. this.bounciness = bounciness;
  14975. }
  14976. BounceEase.prototype.easeInCore = function (gradient) {
  14977. var y = Math.max(0.0, this.bounces);
  14978. var bounciness = this.bounciness;
  14979. if (bounciness <= 1.0) {
  14980. bounciness = 1.001;
  14981. }
  14982. var num9 = Math.pow(bounciness, y);
  14983. var num5 = 1.0 - bounciness;
  14984. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14985. var num15 = gradient * num4;
  14986. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14987. var num3 = Math.floor(num65);
  14988. var num13 = num3 + 1.0;
  14989. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14990. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14991. var num7 = (num8 + num12) * 0.5;
  14992. var num6 = gradient - num7;
  14993. var num2 = num7 - num8;
  14994. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14995. };
  14996. return BounceEase;
  14997. })(EasingFunction);
  14998. BABYLON.BounceEase = BounceEase;
  14999. var CubicEase = (function (_super) {
  15000. __extends(CubicEase, _super);
  15001. function CubicEase() {
  15002. _super.apply(this, arguments);
  15003. }
  15004. CubicEase.prototype.easeInCore = function (gradient) {
  15005. return (gradient * gradient * gradient);
  15006. };
  15007. return CubicEase;
  15008. })(EasingFunction);
  15009. BABYLON.CubicEase = CubicEase;
  15010. var ElasticEase = (function (_super) {
  15011. __extends(ElasticEase, _super);
  15012. function ElasticEase(oscillations, springiness) {
  15013. if (typeof oscillations === "undefined") { oscillations = 3; }
  15014. if (typeof springiness === "undefined") { springiness = 3; }
  15015. _super.call(this);
  15016. this.oscillations = oscillations;
  15017. this.springiness = springiness;
  15018. }
  15019. ElasticEase.prototype.easeInCore = function (gradient) {
  15020. var num2;
  15021. var num3 = Math.max(0.0, this.oscillations);
  15022. var num = Math.max(0.0, this.springiness);
  15023. if (num == 0) {
  15024. num2 = gradient;
  15025. } else {
  15026. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15027. }
  15028. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15029. };
  15030. return ElasticEase;
  15031. })(EasingFunction);
  15032. BABYLON.ElasticEase = ElasticEase;
  15033. var ExponentialEase = (function (_super) {
  15034. __extends(ExponentialEase, _super);
  15035. function ExponentialEase(exponent) {
  15036. if (typeof exponent === "undefined") { exponent = 2; }
  15037. _super.call(this);
  15038. this.exponent = exponent;
  15039. }
  15040. ExponentialEase.prototype.easeInCore = function (gradient) {
  15041. if (this.exponent <= 0) {
  15042. return gradient;
  15043. }
  15044. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15045. };
  15046. return ExponentialEase;
  15047. })(EasingFunction);
  15048. BABYLON.ExponentialEase = ExponentialEase;
  15049. var PowerEase = (function (_super) {
  15050. __extends(PowerEase, _super);
  15051. function PowerEase(power) {
  15052. if (typeof power === "undefined") { power = 2; }
  15053. _super.call(this);
  15054. this.power = power;
  15055. }
  15056. PowerEase.prototype.easeInCore = function (gradient) {
  15057. var y = Math.max(0.0, this.power);
  15058. return Math.pow(gradient, y);
  15059. };
  15060. return PowerEase;
  15061. })(EasingFunction);
  15062. BABYLON.PowerEase = PowerEase;
  15063. var QuadraticEase = (function (_super) {
  15064. __extends(QuadraticEase, _super);
  15065. function QuadraticEase() {
  15066. _super.apply(this, arguments);
  15067. }
  15068. QuadraticEase.prototype.easeInCore = function (gradient) {
  15069. return (gradient * gradient);
  15070. };
  15071. return QuadraticEase;
  15072. })(EasingFunction);
  15073. BABYLON.QuadraticEase = QuadraticEase;
  15074. var QuarticEase = (function (_super) {
  15075. __extends(QuarticEase, _super);
  15076. function QuarticEase() {
  15077. _super.apply(this, arguments);
  15078. }
  15079. QuarticEase.prototype.easeInCore = function (gradient) {
  15080. return (gradient * gradient * gradient * gradient);
  15081. };
  15082. return QuarticEase;
  15083. })(EasingFunction);
  15084. BABYLON.QuarticEase = QuarticEase;
  15085. var QuinticEase = (function (_super) {
  15086. __extends(QuinticEase, _super);
  15087. function QuinticEase() {
  15088. _super.apply(this, arguments);
  15089. }
  15090. QuinticEase.prototype.easeInCore = function (gradient) {
  15091. return (gradient * gradient * gradient * gradient * gradient);
  15092. };
  15093. return QuinticEase;
  15094. })(EasingFunction);
  15095. BABYLON.QuinticEase = QuinticEase;
  15096. var SineEase = (function (_super) {
  15097. __extends(SineEase, _super);
  15098. function SineEase() {
  15099. _super.apply(this, arguments);
  15100. }
  15101. SineEase.prototype.easeInCore = function (gradient) {
  15102. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15103. };
  15104. return SineEase;
  15105. })(EasingFunction);
  15106. BABYLON.SineEase = SineEase;
  15107. var BezierCurveEase = (function (_super) {
  15108. __extends(BezierCurveEase, _super);
  15109. function BezierCurveEase(x1, y1, x2, y2) {
  15110. if (typeof x1 === "undefined") { x1 = 0; }
  15111. if (typeof y1 === "undefined") { y1 = 0; }
  15112. if (typeof x2 === "undefined") { x2 = 1; }
  15113. if (typeof y2 === "undefined") { y2 = 1; }
  15114. _super.call(this);
  15115. this.x1 = x1;
  15116. this.y1 = y1;
  15117. this.x2 = x2;
  15118. this.y2 = y2;
  15119. }
  15120. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15121. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15122. };
  15123. return BezierCurveEase;
  15124. })(EasingFunction);
  15125. BABYLON.BezierCurveEase = BezierCurveEase;
  15126. })(BABYLON || (BABYLON = {}));
  15127. //# sourceMappingURL=babylon.easing.js.map
  15128. var BABYLON;
  15129. (function (BABYLON) {
  15130. var Octree = (function () {
  15131. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15132. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  15133. this.maxDepth = maxDepth;
  15134. this.dynamicContent = new Array();
  15135. this._maxBlockCapacity = maxBlockCapacity || 64;
  15136. this._selectionContent = new BABYLON.SmartArray(1024);
  15137. this._creationFunc = creationFunc;
  15138. }
  15139. // Methods
  15140. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15141. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15142. };
  15143. Octree.prototype.addMesh = function (entry) {
  15144. for (var index = 0; index < this.blocks.length; index++) {
  15145. var block = this.blocks[index];
  15146. block.addEntry(entry);
  15147. }
  15148. };
  15149. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15150. this._selectionContent.reset();
  15151. for (var index = 0; index < this.blocks.length; index++) {
  15152. var block = this.blocks[index];
  15153. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15154. }
  15155. if (allowDuplicate) {
  15156. this._selectionContent.concat(this.dynamicContent);
  15157. } else {
  15158. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15159. }
  15160. return this._selectionContent;
  15161. };
  15162. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15163. this._selectionContent.reset();
  15164. for (var index = 0; index < this.blocks.length; index++) {
  15165. var block = this.blocks[index];
  15166. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15167. }
  15168. if (allowDuplicate) {
  15169. this._selectionContent.concat(this.dynamicContent);
  15170. } else {
  15171. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15172. }
  15173. return this._selectionContent;
  15174. };
  15175. Octree.prototype.intersectsRay = function (ray) {
  15176. this._selectionContent.reset();
  15177. for (var index = 0; index < this.blocks.length; index++) {
  15178. var block = this.blocks[index];
  15179. block.intersectsRay(ray, this._selectionContent);
  15180. }
  15181. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15182. return this._selectionContent;
  15183. };
  15184. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15185. target.blocks = new Array();
  15186. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15187. for (var x = 0; x < 2; x++) {
  15188. for (var y = 0; y < 2; y++) {
  15189. for (var z = 0; z < 2; z++) {
  15190. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15191. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15192. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15193. block.addEntries(entries);
  15194. target.blocks.push(block);
  15195. }
  15196. }
  15197. }
  15198. };
  15199. Octree.CreationFuncForMeshes = function (entry, block) {
  15200. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15201. block.entries.push(entry);
  15202. }
  15203. };
  15204. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15205. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15206. block.entries.push(entry);
  15207. }
  15208. };
  15209. return Octree;
  15210. })();
  15211. BABYLON.Octree = Octree;
  15212. })(BABYLON || (BABYLON = {}));
  15213. //# sourceMappingURL=babylon.octree.js.map
  15214. var BABYLON;
  15215. (function (BABYLON) {
  15216. var OctreeBlock = (function () {
  15217. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15218. this.entries = new Array();
  15219. this._boundingVectors = new Array();
  15220. this._capacity = capacity;
  15221. this._depth = depth;
  15222. this._maxDepth = maxDepth;
  15223. this._creationFunc = creationFunc;
  15224. this._minPoint = minPoint;
  15225. this._maxPoint = maxPoint;
  15226. this._boundingVectors.push(minPoint.clone());
  15227. this._boundingVectors.push(maxPoint.clone());
  15228. this._boundingVectors.push(minPoint.clone());
  15229. this._boundingVectors[2].x = maxPoint.x;
  15230. this._boundingVectors.push(minPoint.clone());
  15231. this._boundingVectors[3].y = maxPoint.y;
  15232. this._boundingVectors.push(minPoint.clone());
  15233. this._boundingVectors[4].z = maxPoint.z;
  15234. this._boundingVectors.push(maxPoint.clone());
  15235. this._boundingVectors[5].z = minPoint.z;
  15236. this._boundingVectors.push(maxPoint.clone());
  15237. this._boundingVectors[6].x = minPoint.x;
  15238. this._boundingVectors.push(maxPoint.clone());
  15239. this._boundingVectors[7].y = minPoint.y;
  15240. }
  15241. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15242. // Property
  15243. get: function () {
  15244. return this._capacity;
  15245. },
  15246. enumerable: true,
  15247. configurable: true
  15248. });
  15249. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15250. get: function () {
  15251. return this._minPoint;
  15252. },
  15253. enumerable: true,
  15254. configurable: true
  15255. });
  15256. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15257. get: function () {
  15258. return this._maxPoint;
  15259. },
  15260. enumerable: true,
  15261. configurable: true
  15262. });
  15263. // Methods
  15264. OctreeBlock.prototype.addEntry = function (entry) {
  15265. if (this.blocks) {
  15266. for (var index = 0; index < this.blocks.length; index++) {
  15267. var block = this.blocks[index];
  15268. block.addEntry(entry);
  15269. }
  15270. return;
  15271. }
  15272. this._creationFunc(entry, this);
  15273. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15274. this.createInnerBlocks();
  15275. }
  15276. };
  15277. OctreeBlock.prototype.addEntries = function (entries) {
  15278. for (var index = 0; index < entries.length; index++) {
  15279. var mesh = entries[index];
  15280. this.addEntry(mesh);
  15281. }
  15282. };
  15283. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15284. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15285. if (this.blocks) {
  15286. for (var index = 0; index < this.blocks.length; index++) {
  15287. var block = this.blocks[index];
  15288. block.select(frustumPlanes, selection, allowDuplicate);
  15289. }
  15290. return;
  15291. }
  15292. if (allowDuplicate) {
  15293. selection.concat(this.entries);
  15294. } else {
  15295. selection.concatWithNoDuplicate(this.entries);
  15296. }
  15297. }
  15298. };
  15299. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15300. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15301. if (this.blocks) {
  15302. for (var index = 0; index < this.blocks.length; index++) {
  15303. var block = this.blocks[index];
  15304. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15305. }
  15306. return;
  15307. }
  15308. if (allowDuplicate) {
  15309. selection.concat(this.entries);
  15310. } else {
  15311. selection.concatWithNoDuplicate(this.entries);
  15312. }
  15313. }
  15314. };
  15315. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15316. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15317. if (this.blocks) {
  15318. for (var index = 0; index < this.blocks.length; index++) {
  15319. var block = this.blocks[index];
  15320. block.intersectsRay(ray, selection);
  15321. }
  15322. return;
  15323. }
  15324. selection.concatWithNoDuplicate(this.entries);
  15325. }
  15326. };
  15327. OctreeBlock.prototype.createInnerBlocks = function () {
  15328. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15329. };
  15330. return OctreeBlock;
  15331. })();
  15332. BABYLON.OctreeBlock = OctreeBlock;
  15333. })(BABYLON || (BABYLON = {}));
  15334. //# sourceMappingURL=babylon.octreeBlock.js.map
  15335. var BABYLON;
  15336. (function (BABYLON) {
  15337. var Bone = (function () {
  15338. function Bone(name, skeleton, parentBone, matrix) {
  15339. this.name = name;
  15340. this.children = new Array();
  15341. this.animations = new Array();
  15342. this._worldTransform = new BABYLON.Matrix();
  15343. this._absoluteTransform = new BABYLON.Matrix();
  15344. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15345. this._skeleton = skeleton;
  15346. this._matrix = matrix;
  15347. this._baseMatrix = matrix;
  15348. skeleton.bones.push(this);
  15349. if (parentBone) {
  15350. this._parent = parentBone;
  15351. parentBone.children.push(this);
  15352. } else {
  15353. this._parent = null;
  15354. }
  15355. this._updateDifferenceMatrix();
  15356. }
  15357. // Members
  15358. Bone.prototype.getParent = function () {
  15359. return this._parent;
  15360. };
  15361. Bone.prototype.getLocalMatrix = function () {
  15362. return this._matrix;
  15363. };
  15364. Bone.prototype.getBaseMatrix = function () {
  15365. return this._baseMatrix;
  15366. };
  15367. Bone.prototype.getWorldMatrix = function () {
  15368. return this._worldTransform;
  15369. };
  15370. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15371. return this._invertedAbsoluteTransform;
  15372. };
  15373. Bone.prototype.getAbsoluteMatrix = function () {
  15374. var matrix = this._matrix.clone();
  15375. var parent = this._parent;
  15376. while (parent) {
  15377. matrix = matrix.multiply(parent.getLocalMatrix());
  15378. parent = parent.getParent();
  15379. }
  15380. return matrix;
  15381. };
  15382. // Methods
  15383. Bone.prototype.updateMatrix = function (matrix) {
  15384. this._matrix = matrix;
  15385. this._skeleton._markAsDirty();
  15386. this._updateDifferenceMatrix();
  15387. };
  15388. Bone.prototype._updateDifferenceMatrix = function () {
  15389. if (this._parent) {
  15390. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15391. } else {
  15392. this._absoluteTransform.copyFrom(this._matrix);
  15393. }
  15394. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15395. for (var index = 0; index < this.children.length; index++) {
  15396. this.children[index]._updateDifferenceMatrix();
  15397. }
  15398. };
  15399. Bone.prototype.markAsDirty = function () {
  15400. this._skeleton._markAsDirty();
  15401. };
  15402. return Bone;
  15403. })();
  15404. BABYLON.Bone = Bone;
  15405. })(BABYLON || (BABYLON = {}));
  15406. //# sourceMappingURL=babylon.bone.js.map
  15407. var BABYLON;
  15408. (function (BABYLON) {
  15409. var Skeleton = (function () {
  15410. function Skeleton(name, id, scene) {
  15411. this.name = name;
  15412. this.id = id;
  15413. this.bones = new Array();
  15414. this._isDirty = true;
  15415. this._identity = BABYLON.Matrix.Identity();
  15416. this.bones = [];
  15417. this._scene = scene;
  15418. scene.skeletons.push(this);
  15419. }
  15420. // Members
  15421. Skeleton.prototype.getTransformMatrices = function () {
  15422. return this._transformMatrices;
  15423. };
  15424. // Methods
  15425. Skeleton.prototype._markAsDirty = function () {
  15426. this._isDirty = true;
  15427. };
  15428. Skeleton.prototype.prepare = function () {
  15429. if (!this._isDirty) {
  15430. return;
  15431. }
  15432. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15433. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15434. }
  15435. for (var index = 0; index < this.bones.length; index++) {
  15436. var bone = this.bones[index];
  15437. var parentBone = bone.getParent();
  15438. if (parentBone) {
  15439. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15440. } else {
  15441. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15442. }
  15443. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15444. }
  15445. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15446. this._isDirty = false;
  15447. };
  15448. Skeleton.prototype.getAnimatables = function () {
  15449. if (!this._animatables || this._animatables.length != this.bones.length) {
  15450. this._animatables = [];
  15451. for (var index = 0; index < this.bones.length; index++) {
  15452. this._animatables.push(this.bones[index]);
  15453. }
  15454. }
  15455. return this._animatables;
  15456. };
  15457. Skeleton.prototype.clone = function (name, id) {
  15458. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15459. for (var index = 0; index < this.bones.length; index++) {
  15460. var source = this.bones[index];
  15461. var parentBone = null;
  15462. if (source.getParent()) {
  15463. var parentIndex = this.bones.indexOf(source.getParent());
  15464. parentBone = result.bones[parentIndex];
  15465. }
  15466. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15467. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15468. }
  15469. return result;
  15470. };
  15471. return Skeleton;
  15472. })();
  15473. BABYLON.Skeleton = Skeleton;
  15474. })(BABYLON || (BABYLON = {}));
  15475. //# sourceMappingURL=babylon.skeleton.js.map
  15476. var BABYLON;
  15477. (function (BABYLON) {
  15478. var PostProcess = (function () {
  15479. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15480. this.name = name;
  15481. this.width = -1;
  15482. this.height = -1;
  15483. this._reusable = false;
  15484. this._textures = new BABYLON.SmartArray(2);
  15485. this._currentRenderTextureInd = 0;
  15486. if (camera != null) {
  15487. this._camera = camera;
  15488. this._scene = camera.getScene();
  15489. camera.attachPostProcess(this);
  15490. this._engine = this._scene.getEngine();
  15491. } else {
  15492. this._engine = engine;
  15493. }
  15494. this._renderRatio = ratio;
  15495. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15496. this._reusable = reusable || false;
  15497. samplers = samplers || [];
  15498. samplers.push("textureSampler");
  15499. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15500. }
  15501. PostProcess.prototype.isReusable = function () {
  15502. return this._reusable;
  15503. };
  15504. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15505. camera = camera || this._camera;
  15506. var scene = camera.getScene();
  15507. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15508. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15509. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15510. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15511. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15512. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15513. if (this._textures.length > 0) {
  15514. for (var i = 0; i < this._textures.length; i++) {
  15515. this._engine._releaseTexture(this._textures.data[i]);
  15516. }
  15517. this._textures.reset();
  15518. }
  15519. this.width = desiredWidth;
  15520. this.height = desiredHeight;
  15521. 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 }));
  15522. if (this._reusable) {
  15523. 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 }));
  15524. }
  15525. if (this.onSizeChanged) {
  15526. this.onSizeChanged();
  15527. }
  15528. }
  15529. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15530. if (this.onActivate) {
  15531. this.onActivate(camera);
  15532. }
  15533. // Clear
  15534. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15535. if (this._reusable) {
  15536. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15537. }
  15538. };
  15539. PostProcess.prototype.apply = function () {
  15540. // Check
  15541. if (!this._effect.isReady())
  15542. return null;
  15543. // States
  15544. this._engine.enableEffect(this._effect);
  15545. this._engine.setState(false);
  15546. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15547. this._engine.setDepthBuffer(false);
  15548. this._engine.setDepthWrite(false);
  15549. // Texture
  15550. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15551. // Parameters
  15552. if (this.onApply) {
  15553. this.onApply(this._effect);
  15554. }
  15555. return this._effect;
  15556. };
  15557. PostProcess.prototype.dispose = function (camera) {
  15558. camera = camera || this._camera;
  15559. if (this._textures.length > 0) {
  15560. for (var i = 0; i < this._textures.length; i++) {
  15561. this._engine._releaseTexture(this._textures.data[i]);
  15562. }
  15563. this._textures.reset();
  15564. }
  15565. camera.detachPostProcess(this);
  15566. var index = camera._postProcesses.indexOf(this);
  15567. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15568. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15569. }
  15570. };
  15571. return PostProcess;
  15572. })();
  15573. BABYLON.PostProcess = PostProcess;
  15574. })(BABYLON || (BABYLON = {}));
  15575. //# sourceMappingURL=babylon.postProcess.js.map
  15576. var BABYLON;
  15577. (function (BABYLON) {
  15578. var PostProcessManager = (function () {
  15579. function PostProcessManager(scene) {
  15580. this._vertexDeclaration = [2];
  15581. this._vertexStrideSize = 2 * 4;
  15582. this._scene = scene;
  15583. // VBO
  15584. var vertices = [];
  15585. vertices.push(1, 1);
  15586. vertices.push(-1, 1);
  15587. vertices.push(-1, -1);
  15588. vertices.push(1, -1);
  15589. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15590. // Indices
  15591. var indices = [];
  15592. indices.push(0);
  15593. indices.push(1);
  15594. indices.push(2);
  15595. indices.push(0);
  15596. indices.push(2);
  15597. indices.push(3);
  15598. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15599. }
  15600. // Methods
  15601. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15602. var postProcesses = this._scene.activeCamera._postProcesses;
  15603. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15604. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15605. return false;
  15606. }
  15607. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15608. return true;
  15609. };
  15610. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15611. var postProcesses = this._scene.activeCamera._postProcesses;
  15612. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15613. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15614. return;
  15615. }
  15616. var engine = this._scene.getEngine();
  15617. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15618. if (index < postProcessesTakenIndices.length - 1) {
  15619. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15620. } else {
  15621. if (targetTexture) {
  15622. engine.bindFramebuffer(targetTexture);
  15623. } else {
  15624. engine.restoreDefaultFramebuffer();
  15625. }
  15626. }
  15627. if (doNotPresent) {
  15628. break;
  15629. }
  15630. var pp = postProcesses[postProcessesTakenIndices[index]];
  15631. var effect = pp.apply();
  15632. if (effect) {
  15633. if (pp.onBeforeRender) {
  15634. pp.onBeforeRender(effect);
  15635. }
  15636. // VBOs
  15637. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15638. // Draw order
  15639. engine.draw(true, 0, 6);
  15640. }
  15641. }
  15642. // Restore depth buffer
  15643. engine.setDepthBuffer(true);
  15644. engine.setDepthWrite(true);
  15645. };
  15646. PostProcessManager.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. };
  15656. return PostProcessManager;
  15657. })();
  15658. BABYLON.PostProcessManager = PostProcessManager;
  15659. })(BABYLON || (BABYLON = {}));
  15660. //# sourceMappingURL=babylon.postProcessManager.js.map
  15661. var BABYLON;
  15662. (function (BABYLON) {
  15663. var PassPostProcess = (function (_super) {
  15664. __extends(PassPostProcess, _super);
  15665. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15666. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15667. }
  15668. return PassPostProcess;
  15669. })(BABYLON.PostProcess);
  15670. BABYLON.PassPostProcess = PassPostProcess;
  15671. })(BABYLON || (BABYLON = {}));
  15672. //# sourceMappingURL=babylon.passPostProcess.js.map
  15673. var BABYLON;
  15674. (function (BABYLON) {
  15675. var BlurPostProcess = (function (_super) {
  15676. __extends(BlurPostProcess, _super);
  15677. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15678. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15679. var _this = this;
  15680. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15681. this.direction = direction;
  15682. this.blurWidth = blurWidth;
  15683. this.onApply = function (effect) {
  15684. effect.setFloat2("screenSize", _this.width, _this.height);
  15685. effect.setVector2("direction", _this.direction);
  15686. effect.setFloat("blurWidth", _this.blurWidth);
  15687. };
  15688. }
  15689. return BlurPostProcess;
  15690. })(BABYLON.PostProcess);
  15691. BABYLON.BlurPostProcess = BlurPostProcess;
  15692. })(BABYLON || (BABYLON = {}));
  15693. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15694. var BABYLON;
  15695. (function (BABYLON) {
  15696. var FilterPostProcess = (function (_super) {
  15697. __extends(FilterPostProcess, _super);
  15698. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15699. var _this = this;
  15700. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15701. this.kernelMatrix = kernelMatrix;
  15702. this.onApply = function (effect) {
  15703. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15704. };
  15705. }
  15706. return FilterPostProcess;
  15707. })(BABYLON.PostProcess);
  15708. BABYLON.FilterPostProcess = FilterPostProcess;
  15709. })(BABYLON || (BABYLON = {}));
  15710. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15711. var BABYLON;
  15712. (function (BABYLON) {
  15713. var RefractionPostProcess = (function (_super) {
  15714. __extends(RefractionPostProcess, _super);
  15715. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15716. var _this = this;
  15717. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15718. this.color = color;
  15719. this.depth = depth;
  15720. this.colorLevel = colorLevel;
  15721. this.onActivate = function (cam) {
  15722. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15723. };
  15724. this.onApply = function (effect) {
  15725. effect.setColor3("baseColor", _this.color);
  15726. effect.setFloat("depth", _this.depth);
  15727. effect.setFloat("colorLevel", _this.colorLevel);
  15728. effect.setTexture("refractionSampler", _this._refRexture);
  15729. };
  15730. }
  15731. // Methods
  15732. RefractionPostProcess.prototype.dispose = function (camera) {
  15733. if (this._refRexture) {
  15734. this._refRexture.dispose();
  15735. }
  15736. _super.prototype.dispose.call(this, camera);
  15737. };
  15738. return RefractionPostProcess;
  15739. })(BABYLON.PostProcess);
  15740. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15741. })(BABYLON || (BABYLON = {}));
  15742. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15743. var BABYLON;
  15744. (function (BABYLON) {
  15745. var BlackAndWhitePostProcess = (function (_super) {
  15746. __extends(BlackAndWhitePostProcess, _super);
  15747. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15748. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15749. }
  15750. return BlackAndWhitePostProcess;
  15751. })(BABYLON.PostProcess);
  15752. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15753. })(BABYLON || (BABYLON = {}));
  15754. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15755. var BABYLON;
  15756. (function (BABYLON) {
  15757. var ConvolutionPostProcess = (function (_super) {
  15758. __extends(ConvolutionPostProcess, _super);
  15759. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15760. var _this = this;
  15761. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15762. this.kernel = kernel;
  15763. this.onApply = function (effect) {
  15764. effect.setFloat2("screenSize", _this.width, _this.height);
  15765. effect.setArray("kernel", _this.kernel);
  15766. };
  15767. }
  15768. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15769. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15770. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15771. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15772. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15773. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15774. return ConvolutionPostProcess;
  15775. })(BABYLON.PostProcess);
  15776. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15777. })(BABYLON || (BABYLON = {}));
  15778. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15779. var BABYLON;
  15780. (function (BABYLON) {
  15781. var FxaaPostProcess = (function (_super) {
  15782. __extends(FxaaPostProcess, _super);
  15783. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15784. var _this = this;
  15785. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15786. this.onSizeChanged = function () {
  15787. _this.texelWidth = 1.0 / _this.width;
  15788. _this.texelHeight = 1.0 / _this.height;
  15789. };
  15790. this.onApply = function (effect) {
  15791. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15792. };
  15793. }
  15794. return FxaaPostProcess;
  15795. })(BABYLON.PostProcess);
  15796. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15797. })(BABYLON || (BABYLON = {}));
  15798. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15799. var BABYLON;
  15800. (function (BABYLON) {
  15801. var LensFlare = (function () {
  15802. function LensFlare(size, position, color, imgUrl, system) {
  15803. this.size = size;
  15804. this.position = position;
  15805. this.dispose = function () {
  15806. if (this.texture) {
  15807. this.texture.dispose();
  15808. }
  15809. // Remove from scene
  15810. var index = this._system.lensFlares.indexOf(this);
  15811. this._system.lensFlares.splice(index, 1);
  15812. };
  15813. this.color = color || new BABYLON.Color3(1, 1, 1);
  15814. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15815. this._system = system;
  15816. system.lensFlares.push(this);
  15817. }
  15818. return LensFlare;
  15819. })();
  15820. BABYLON.LensFlare = LensFlare;
  15821. })(BABYLON || (BABYLON = {}));
  15822. //# sourceMappingURL=babylon.lensFlare.js.map
  15823. var BABYLON;
  15824. (function (BABYLON) {
  15825. var LensFlareSystem = (function () {
  15826. function LensFlareSystem(name, emitter, scene) {
  15827. this.name = name;
  15828. this.lensFlares = new Array();
  15829. this.borderLimit = 300;
  15830. this._vertexDeclaration = [2];
  15831. this._vertexStrideSize = 2 * 4;
  15832. this._isEnabled = true;
  15833. this._scene = scene;
  15834. this._emitter = emitter;
  15835. scene.lensFlareSystems.push(this);
  15836. this.meshesSelectionPredicate = function (m) {
  15837. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15838. };
  15839. // VBO
  15840. var vertices = [];
  15841. vertices.push(1, 1);
  15842. vertices.push(-1, 1);
  15843. vertices.push(-1, -1);
  15844. vertices.push(1, -1);
  15845. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15846. // Indices
  15847. var indices = [];
  15848. indices.push(0);
  15849. indices.push(1);
  15850. indices.push(2);
  15851. indices.push(0);
  15852. indices.push(2);
  15853. indices.push(3);
  15854. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15855. // Effects
  15856. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15857. }
  15858. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15859. get: function () {
  15860. return this._isEnabled;
  15861. },
  15862. set: function (value) {
  15863. this._isEnabled = value;
  15864. },
  15865. enumerable: true,
  15866. configurable: true
  15867. });
  15868. LensFlareSystem.prototype.getScene = function () {
  15869. return this._scene;
  15870. };
  15871. LensFlareSystem.prototype.getEmitter = function () {
  15872. return this._emitter;
  15873. };
  15874. LensFlareSystem.prototype.getEmitterPosition = function () {
  15875. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15876. };
  15877. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15878. var position = this.getEmitterPosition();
  15879. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15880. this._positionX = position.x;
  15881. this._positionY = position.y;
  15882. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15883. if (position.z > 0) {
  15884. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15885. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15886. return true;
  15887. }
  15888. }
  15889. return false;
  15890. };
  15891. LensFlareSystem.prototype._isVisible = function () {
  15892. if (!this._isEnabled) {
  15893. return false;
  15894. }
  15895. var emitterPosition = this.getEmitterPosition();
  15896. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15897. var distance = direction.length();
  15898. direction.normalize();
  15899. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15900. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15901. return !pickInfo.hit || pickInfo.distance > distance;
  15902. };
  15903. LensFlareSystem.prototype.render = function () {
  15904. if (!this._effect.isReady())
  15905. return false;
  15906. var engine = this._scene.getEngine();
  15907. var viewport = this._scene.activeCamera.viewport;
  15908. var globalViewport = viewport.toGlobal(engine);
  15909. // Position
  15910. if (!this.computeEffectivePosition(globalViewport)) {
  15911. return false;
  15912. }
  15913. // Visibility
  15914. if (!this._isVisible()) {
  15915. return false;
  15916. }
  15917. // Intensity
  15918. var awayX;
  15919. var awayY;
  15920. if (this._positionX < this.borderLimit + globalViewport.x) {
  15921. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15922. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15923. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15924. } else {
  15925. awayX = 0;
  15926. }
  15927. if (this._positionY < this.borderLimit + globalViewport.y) {
  15928. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15929. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15930. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15931. } else {
  15932. awayY = 0;
  15933. }
  15934. var away = (awayX > awayY) ? awayX : awayY;
  15935. if (away > this.borderLimit) {
  15936. away = this.borderLimit;
  15937. }
  15938. var intensity = 1.0 - (away / this.borderLimit);
  15939. if (intensity < 0) {
  15940. return false;
  15941. }
  15942. if (intensity > 1.0) {
  15943. intensity = 1.0;
  15944. }
  15945. // Position
  15946. var centerX = globalViewport.x + globalViewport.width / 2;
  15947. var centerY = globalViewport.y + globalViewport.height / 2;
  15948. var distX = centerX - this._positionX;
  15949. var distY = centerY - this._positionY;
  15950. // Effects
  15951. engine.enableEffect(this._effect);
  15952. engine.setState(false);
  15953. engine.setDepthBuffer(false);
  15954. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15955. // VBOs
  15956. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15957. for (var index = 0; index < this.lensFlares.length; index++) {
  15958. var flare = this.lensFlares[index];
  15959. var x = centerX - (distX * flare.position);
  15960. var y = centerY - (distY * flare.position);
  15961. var cw = flare.size;
  15962. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15963. var cx = 2 * (x / globalViewport.width) - 1.0;
  15964. var cy = 1.0 - 2 * (y / globalViewport.height);
  15965. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15966. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15967. // Texture
  15968. this._effect.setTexture("textureSampler", flare.texture);
  15969. // Color
  15970. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15971. // Draw order
  15972. engine.draw(true, 0, 6);
  15973. }
  15974. engine.setDepthBuffer(true);
  15975. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15976. return true;
  15977. };
  15978. LensFlareSystem.prototype.dispose = function () {
  15979. if (this._vertexBuffer) {
  15980. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15981. this._vertexBuffer = null;
  15982. }
  15983. if (this._indexBuffer) {
  15984. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15985. this._indexBuffer = null;
  15986. }
  15987. while (this.lensFlares.length) {
  15988. this.lensFlares[0].dispose();
  15989. }
  15990. // Remove from scene
  15991. var index = this._scene.lensFlareSystems.indexOf(this);
  15992. this._scene.lensFlareSystems.splice(index, 1);
  15993. };
  15994. return LensFlareSystem;
  15995. })();
  15996. BABYLON.LensFlareSystem = LensFlareSystem;
  15997. })(BABYLON || (BABYLON = {}));
  15998. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15999. var BABYLON;
  16000. (function (BABYLON) {
  16001. var IntersectionInfo = (function () {
  16002. function IntersectionInfo(bu, bv, distance) {
  16003. this.bu = bu;
  16004. this.bv = bv;
  16005. this.distance = distance;
  16006. this.faceId = 0;
  16007. }
  16008. return IntersectionInfo;
  16009. })();
  16010. BABYLON.IntersectionInfo = IntersectionInfo;
  16011. var PickingInfo = (function () {
  16012. function PickingInfo() {
  16013. this.hit = false;
  16014. this.distance = 0;
  16015. this.pickedPoint = null;
  16016. this.pickedMesh = null;
  16017. this.bu = 0;
  16018. this.bv = 0;
  16019. this.faceId = -1;
  16020. }
  16021. // Methods
  16022. PickingInfo.prototype.getNormal = function () {
  16023. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16024. return null;
  16025. }
  16026. var indices = this.pickedMesh.getIndices();
  16027. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16028. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16029. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16030. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16031. normal0 = normal0.scale(this.bu);
  16032. normal1 = normal1.scale(this.bv);
  16033. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16034. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16035. };
  16036. PickingInfo.prototype.getTextureCoordinates = function () {
  16037. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16038. return null;
  16039. }
  16040. var indices = this.pickedMesh.getIndices();
  16041. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16042. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16043. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16044. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16045. uv0 = uv0.scale(this.bu);
  16046. uv1 = uv1.scale(this.bv);
  16047. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16048. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16049. };
  16050. return PickingInfo;
  16051. })();
  16052. BABYLON.PickingInfo = PickingInfo;
  16053. })(BABYLON || (BABYLON = {}));
  16054. //# sourceMappingURL=babylon.pickingInfo.js.map
  16055. var BABYLON;
  16056. (function (BABYLON) {
  16057. var FilesInput = (function () {
  16058. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16059. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16060. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16061. this.engine = p_engine;
  16062. this.canvas = p_canvas;
  16063. this.currentScene = p_scene;
  16064. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16065. this.progressCallback = p_progressCallback;
  16066. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16067. this.textureLoadingCallback = p_textureLoadingCallback;
  16068. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16069. }
  16070. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16071. var _this = this;
  16072. if (p_elementToMonitor) {
  16073. this.elementToMonitor = p_elementToMonitor;
  16074. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16075. _this.drag(e);
  16076. }, false);
  16077. this.elementToMonitor.addEventListener("dragover", function (e) {
  16078. _this.drag(e);
  16079. }, false);
  16080. this.elementToMonitor.addEventListener("drop", function (e) {
  16081. _this.drop(e);
  16082. }, false);
  16083. }
  16084. };
  16085. FilesInput.prototype.renderFunction = function () {
  16086. if (this.additionnalRenderLoopLogicCallback) {
  16087. this.additionnalRenderLoopLogicCallback();
  16088. }
  16089. if (this.currentScene) {
  16090. if (this.textureLoadingCallback) {
  16091. var remaining = this.currentScene.getWaitingItemsCount();
  16092. if (remaining > 0) {
  16093. this.textureLoadingCallback(remaining);
  16094. }
  16095. }
  16096. this.currentScene.render();
  16097. }
  16098. };
  16099. FilesInput.prototype.drag = function (e) {
  16100. e.stopPropagation();
  16101. e.preventDefault();
  16102. };
  16103. FilesInput.prototype.drop = function (eventDrop) {
  16104. eventDrop.stopPropagation();
  16105. eventDrop.preventDefault();
  16106. this.loadFiles(eventDrop);
  16107. };
  16108. FilesInput.prototype.loadFiles = function (event) {
  16109. var _this = this;
  16110. var that = this;
  16111. if (this.startingProcessingFilesCallback)
  16112. this.startingProcessingFilesCallback();
  16113. var sceneFileToLoad;
  16114. var filesToLoad;
  16115. // Handling data transfer via drag'n'drop
  16116. if (event && event.dataTransfer && event.dataTransfer.files) {
  16117. filesToLoad = event.dataTransfer.files;
  16118. }
  16119. // Handling files from input files
  16120. if (event && event.target && event.target.files) {
  16121. filesToLoad = event.target.files;
  16122. }
  16123. if (filesToLoad && filesToLoad.length > 0) {
  16124. for (var i = 0; i < filesToLoad.length; i++) {
  16125. switch (filesToLoad[i].type) {
  16126. case "image/jpeg":
  16127. case "image/png":
  16128. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16129. break;
  16130. case "image/targa":
  16131. case "image/vnd.ms-dds":
  16132. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16133. break;
  16134. default:
  16135. 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) {
  16136. sceneFileToLoad = filesToLoad[i];
  16137. }
  16138. break;
  16139. }
  16140. }
  16141. // If a ".babylon" file has been provided
  16142. if (sceneFileToLoad) {
  16143. if (this.currentScene) {
  16144. this.engine.stopRenderLoop();
  16145. this.currentScene.dispose();
  16146. }
  16147. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16148. that.currentScene = newScene;
  16149. // Wait for textures and shaders to be ready
  16150. that.currentScene.executeWhenReady(function () {
  16151. // Attach camera to canvas inputs
  16152. if (that.currentScene.activeCamera) {
  16153. that.currentScene.activeCamera.attachControl(that.canvas);
  16154. }
  16155. if (that.sceneLoadedCallback) {
  16156. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16157. }
  16158. that.engine.runRenderLoop(function () {
  16159. that.renderFunction();
  16160. });
  16161. });
  16162. }, function (progress) {
  16163. if (_this.progressCallback) {
  16164. _this.progressCallback(progress);
  16165. }
  16166. });
  16167. } else {
  16168. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16169. }
  16170. }
  16171. };
  16172. FilesInput.FilesTextures = new Array();
  16173. FilesInput.FilesToLoad = new Array();
  16174. return FilesInput;
  16175. })();
  16176. BABYLON.FilesInput = FilesInput;
  16177. })(BABYLON || (BABYLON = {}));
  16178. //# sourceMappingURL=babylon.filesInput.js.map
  16179. var BABYLON;
  16180. (function (BABYLON) {
  16181. var OimoJSPlugin = (function () {
  16182. function OimoJSPlugin() {
  16183. this._registeredMeshes = [];
  16184. /**
  16185. * Update the body position according to the mesh position
  16186. * @param mesh
  16187. */
  16188. this.updateBodyPosition = function (mesh) {
  16189. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16190. var registeredMesh = this._registeredMeshes[index];
  16191. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16192. var body = registeredMesh.body.body;
  16193. mesh.computeWorldMatrix(true);
  16194. var center = mesh.getBoundingInfo().boundingBox.center;
  16195. body.setPosition(center.x, center.y, center.z);
  16196. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16197. return;
  16198. }
  16199. // Case where the parent has been updated
  16200. if (registeredMesh.mesh.parent === mesh) {
  16201. mesh.computeWorldMatrix(true);
  16202. registeredMesh.mesh.computeWorldMatrix(true);
  16203. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16204. var absoluteRotation = mesh.rotation;
  16205. body = registeredMesh.body.body;
  16206. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16207. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16208. return;
  16209. }
  16210. }
  16211. };
  16212. }
  16213. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16214. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16215. };
  16216. OimoJSPlugin.prototype.initialize = function (iterations) {
  16217. this._world = new OIMO.World();
  16218. this._world.clear();
  16219. };
  16220. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16221. this._world.gravity = gravity;
  16222. };
  16223. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16224. var body = null;
  16225. this.unregisterMesh(mesh);
  16226. mesh.computeWorldMatrix(true);
  16227. switch (impostor) {
  16228. case BABYLON.PhysicsEngine.SphereImpostor:
  16229. var initialRotation = null;
  16230. if (mesh.rotationQuaternion) {
  16231. initialRotation = mesh.rotationQuaternion.clone();
  16232. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16233. mesh.computeWorldMatrix(true);
  16234. }
  16235. var bbox = mesh.getBoundingInfo().boundingBox;
  16236. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16237. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16238. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16239. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16240. // The delta between the mesh position and the mesh bounding box center
  16241. var deltaPosition = mesh.position.subtract(bbox.center);
  16242. // Transform delta position with the rotation
  16243. if (initialRotation) {
  16244. var m = new BABYLON.Matrix();
  16245. initialRotation.toRotationMatrix(m);
  16246. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16247. }
  16248. body = new OIMO.Body({
  16249. type: 'sphere',
  16250. size: [size],
  16251. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16252. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16253. move: options.mass != 0,
  16254. config: [options.mass, options.friction, options.restitution],
  16255. world: this._world
  16256. });
  16257. // Restore rotation
  16258. if (initialRotation) {
  16259. body.setQuaternion(initialRotation);
  16260. }
  16261. this._registeredMeshes.push({
  16262. mesh: mesh,
  16263. body: body,
  16264. delta: deltaPosition
  16265. });
  16266. break;
  16267. case BABYLON.PhysicsEngine.PlaneImpostor:
  16268. case BABYLON.PhysicsEngine.BoxImpostor:
  16269. initialRotation = null;
  16270. if (mesh.rotationQuaternion) {
  16271. initialRotation = mesh.rotationQuaternion.clone();
  16272. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16273. mesh.computeWorldMatrix(true);
  16274. }
  16275. bbox = mesh.getBoundingInfo().boundingBox;
  16276. var min = bbox.minimumWorld;
  16277. var max = bbox.maximumWorld;
  16278. var box = max.subtract(min);
  16279. var sizeX = this._checkWithEpsilon(box.x);
  16280. var sizeY = this._checkWithEpsilon(box.y);
  16281. var sizeZ = this._checkWithEpsilon(box.z);
  16282. // The delta between the mesh position and the mesh boudning box center
  16283. deltaPosition = mesh.position.subtract(bbox.center);
  16284. // Transform delta position with the rotation
  16285. if (initialRotation) {
  16286. m = new BABYLON.Matrix();
  16287. initialRotation.toRotationMatrix(m);
  16288. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16289. }
  16290. body = new OIMO.Body({
  16291. type: 'box',
  16292. size: [sizeX, sizeY, sizeZ],
  16293. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16294. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16295. move: options.mass != 0,
  16296. config: [options.mass, options.friction, options.restitution],
  16297. world: this._world
  16298. });
  16299. if (initialRotation) {
  16300. body.setQuaternion(initialRotation);
  16301. }
  16302. this._registeredMeshes.push({
  16303. mesh: mesh,
  16304. body: body,
  16305. delta: deltaPosition
  16306. });
  16307. break;
  16308. }
  16309. return body;
  16310. };
  16311. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16312. var types = [], sizes = [], positions = [], rotations = [];
  16313. var initialMesh = parts[0].mesh;
  16314. for (var index = 0; index < parts.length; index++) {
  16315. var part = parts[index];
  16316. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16317. types.push(bodyParameters.type);
  16318. sizes.push.apply(sizes, bodyParameters.size);
  16319. positions.push.apply(positions, bodyParameters.pos);
  16320. rotations.push.apply(rotations, bodyParameters.rot);
  16321. }
  16322. var body = new OIMO.Body({
  16323. type: types,
  16324. size: sizes,
  16325. pos: positions,
  16326. rot: rotations,
  16327. move: options.mass != 0,
  16328. config: [options.mass, options.friction, options.restitution],
  16329. world: this._world
  16330. });
  16331. this._registeredMeshes.push({
  16332. mesh: initialMesh,
  16333. body: body
  16334. });
  16335. return body;
  16336. };
  16337. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16338. var bodyParameters = null;
  16339. var mesh = part.mesh;
  16340. switch (part.impostor) {
  16341. case BABYLON.PhysicsEngine.SphereImpostor:
  16342. var bbox = mesh.getBoundingInfo().boundingBox;
  16343. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16344. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16345. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16346. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16347. bodyParameters = {
  16348. type: 'sphere',
  16349. /* bug with oimo : sphere needs 3 sizes in this case */
  16350. size: [size, -1, -1],
  16351. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16352. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16353. };
  16354. break;
  16355. case BABYLON.PhysicsEngine.PlaneImpostor:
  16356. case BABYLON.PhysicsEngine.BoxImpostor:
  16357. bbox = mesh.getBoundingInfo().boundingBox;
  16358. var min = bbox.minimumWorld;
  16359. var max = bbox.maximumWorld;
  16360. var box = max.subtract(min);
  16361. var sizeX = this._checkWithEpsilon(box.x);
  16362. var sizeY = this._checkWithEpsilon(box.y);
  16363. var sizeZ = this._checkWithEpsilon(box.z);
  16364. var relativePosition = mesh.position;
  16365. bodyParameters = {
  16366. type: 'box',
  16367. size: [sizeX, sizeY, sizeZ],
  16368. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16369. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16370. };
  16371. break;
  16372. }
  16373. return bodyParameters;
  16374. };
  16375. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16376. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16377. var registeredMesh = this._registeredMeshes[index];
  16378. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16379. if (registeredMesh.body) {
  16380. this._world.removeRigidBody(registeredMesh.body.body);
  16381. this._unbindBody(registeredMesh.body);
  16382. }
  16383. this._registeredMeshes.splice(index, 1);
  16384. return;
  16385. }
  16386. }
  16387. };
  16388. OimoJSPlugin.prototype._unbindBody = function (body) {
  16389. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16390. var registeredMesh = this._registeredMeshes[index];
  16391. if (registeredMesh.body === body) {
  16392. registeredMesh.body = null;
  16393. }
  16394. }
  16395. };
  16396. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16397. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16398. var registeredMesh = this._registeredMeshes[index];
  16399. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16400. // Get object mass to have a behaviour similar to cannon.js
  16401. var mass = registeredMesh.body.body.massInfo.mass;
  16402. // The force is scaled with the mass of object
  16403. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16404. return;
  16405. }
  16406. }
  16407. };
  16408. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16409. var body1 = null, body2 = null;
  16410. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16411. var registeredMesh = this._registeredMeshes[index];
  16412. if (registeredMesh.mesh === mesh1) {
  16413. body1 = registeredMesh.body.body;
  16414. } else if (registeredMesh.mesh === mesh2) {
  16415. body2 = registeredMesh.body.body;
  16416. }
  16417. }
  16418. if (!body1 || !body2) {
  16419. return false;
  16420. }
  16421. if (!options) {
  16422. options = {};
  16423. }
  16424. new OIMO.Link({
  16425. type: options.type,
  16426. body1: body1,
  16427. body2: body2,
  16428. min: options.min,
  16429. max: options.max,
  16430. axe1: options.axe1,
  16431. axe2: options.axe2,
  16432. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16433. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16434. collision: options.collision,
  16435. spring: options.spring,
  16436. world: this._world
  16437. });
  16438. return true;
  16439. };
  16440. OimoJSPlugin.prototype.dispose = function () {
  16441. this._world.clear();
  16442. while (this._registeredMeshes.length) {
  16443. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16444. }
  16445. };
  16446. OimoJSPlugin.prototype.isSupported = function () {
  16447. return OIMO !== undefined;
  16448. };
  16449. OimoJSPlugin.prototype._getLastShape = function (body) {
  16450. var lastShape = body.shapes;
  16451. while (lastShape.next) {
  16452. lastShape = lastShape.next;
  16453. }
  16454. return lastShape;
  16455. };
  16456. OimoJSPlugin.prototype.runOneStep = function (time) {
  16457. this._world.step();
  16458. // Update the position of all registered meshes
  16459. var i = this._registeredMeshes.length;
  16460. var m;
  16461. while (i--) {
  16462. var body = this._registeredMeshes[i].body.body;
  16463. var mesh = this._registeredMeshes[i].mesh;
  16464. var delta = this._registeredMeshes[i].delta;
  16465. if (!body.sleeping) {
  16466. if (body.shapes.next) {
  16467. var parentShape = this._getLastShape(body);
  16468. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16469. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16470. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16471. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16472. if (!mesh.rotationQuaternion) {
  16473. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16474. }
  16475. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16476. mesh.computeWorldMatrix();
  16477. } else {
  16478. m = body.getMatrix();
  16479. mtx = BABYLON.Matrix.FromArray(m);
  16480. // Body position
  16481. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16482. if (!delta) {
  16483. mesh.position.x = bodyX;
  16484. mesh.position.y = bodyY;
  16485. mesh.position.z = bodyZ;
  16486. } else {
  16487. mesh.position.x = bodyX + delta.x;
  16488. mesh.position.y = bodyY + delta.y;
  16489. mesh.position.z = bodyZ + delta.z;
  16490. }
  16491. if (!mesh.rotationQuaternion) {
  16492. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16493. }
  16494. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16495. mesh.computeWorldMatrix();
  16496. }
  16497. }
  16498. }
  16499. };
  16500. return OimoJSPlugin;
  16501. })();
  16502. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16503. })(BABYLON || (BABYLON = {}));
  16504. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16505. var BABYLON;
  16506. (function (BABYLON) {
  16507. var PhysicsEngine = (function () {
  16508. function PhysicsEngine(plugin) {
  16509. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16510. }
  16511. PhysicsEngine.prototype._initialize = function (gravity) {
  16512. this._currentPlugin.initialize();
  16513. this._setGravity(gravity);
  16514. };
  16515. PhysicsEngine.prototype._runOneStep = function (delta) {
  16516. if (delta > 0.1) {
  16517. delta = 0.1;
  16518. } else if (delta <= 0) {
  16519. delta = 1.0 / 60.0;
  16520. }
  16521. this._currentPlugin.runOneStep(delta);
  16522. };
  16523. PhysicsEngine.prototype._setGravity = function (gravity) {
  16524. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16525. this._currentPlugin.setGravity(this.gravity);
  16526. };
  16527. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16528. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16529. };
  16530. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16531. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16532. };
  16533. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16534. this._currentPlugin.unregisterMesh(mesh);
  16535. };
  16536. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16537. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16538. };
  16539. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16540. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16541. };
  16542. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16543. this._currentPlugin.updateBodyPosition(mesh);
  16544. };
  16545. PhysicsEngine.prototype.dispose = function () {
  16546. this._currentPlugin.dispose();
  16547. };
  16548. PhysicsEngine.prototype.isSupported = function () {
  16549. return this._currentPlugin.isSupported();
  16550. };
  16551. PhysicsEngine.NoImpostor = 0;
  16552. PhysicsEngine.SphereImpostor = 1;
  16553. PhysicsEngine.BoxImpostor = 2;
  16554. PhysicsEngine.PlaneImpostor = 3;
  16555. PhysicsEngine.MeshImpostor = 4;
  16556. PhysicsEngine.CapsuleImpostor = 5;
  16557. PhysicsEngine.ConeImpostor = 6;
  16558. PhysicsEngine.CylinderImpostor = 7;
  16559. PhysicsEngine.ConvexHullImpostor = 8;
  16560. PhysicsEngine.Epsilon = 0.001;
  16561. return PhysicsEngine;
  16562. })();
  16563. BABYLON.PhysicsEngine = PhysicsEngine;
  16564. })(BABYLON || (BABYLON = {}));
  16565. //# sourceMappingURL=babylon.physicsEngine.js.map
  16566. var BABYLON;
  16567. (function (BABYLON) {
  16568. var serializeLight = function (light) {
  16569. var serializationObject = {};
  16570. serializationObject.name = light.name;
  16571. serializationObject.id = light.id;
  16572. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16573. if (light instanceof BABYLON.PointLight) {
  16574. serializationObject.type = 0;
  16575. serializationObject.position = light.position.asArray();
  16576. } else if (light instanceof BABYLON.DirectionalLight) {
  16577. serializationObject.type = 1;
  16578. var directionalLight = light;
  16579. serializationObject.position = directionalLight.position.asArray();
  16580. serializationObject.direction = directionalLight.direction.asArray();
  16581. } else if (light instanceof BABYLON.SpotLight) {
  16582. serializationObject.type = 2;
  16583. var spotLight = light;
  16584. serializationObject.position = spotLight.position.asArray();
  16585. serializationObject.direction = spotLight.position.asArray();
  16586. serializationObject.angle = spotLight.angle;
  16587. serializationObject.exponent = spotLight.exponent;
  16588. } else if (light instanceof BABYLON.HemisphericLight) {
  16589. serializationObject.type = 3;
  16590. var hemisphericLight = light;
  16591. serializationObject.direction = hemisphericLight.direction.asArray();
  16592. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16593. }
  16594. if (light.intensity) {
  16595. serializationObject.intensity = light.intensity;
  16596. }
  16597. serializationObject.range = light.range;
  16598. serializationObject.diffuse = light.diffuse.asArray();
  16599. serializationObject.specular = light.specular.asArray();
  16600. return serializationObject;
  16601. };
  16602. var serializeFresnelParameter = function (fresnelParameter) {
  16603. var serializationObject = {};
  16604. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16605. serializationObject.leftColor = fresnelParameter.leftColor;
  16606. serializationObject.rightColor = fresnelParameter.rightColor;
  16607. serializationObject.bias = fresnelParameter.bias;
  16608. serializationObject.power = fresnelParameter.power;
  16609. return serializationObject;
  16610. };
  16611. var serializeCamera = function (camera) {
  16612. var serializationObject = {};
  16613. serializationObject.name = camera.name;
  16614. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16615. serializationObject.id = camera.id;
  16616. serializationObject.position = camera.position.asArray();
  16617. // Parent
  16618. if (camera.parent) {
  16619. serializationObject.parentId = camera.parent.id;
  16620. }
  16621. // Target
  16622. serializationObject.rotation = camera.rotation.asArray();
  16623. // Locked target
  16624. if (camera.lockedTarget && camera.lockedTarget.id) {
  16625. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16626. }
  16627. serializationObject.fov = camera.fov;
  16628. serializationObject.minZ = camera.minZ;
  16629. serializationObject.maxZ = camera.maxZ;
  16630. serializationObject.speed = camera.speed;
  16631. serializationObject.inertia = camera.inertia;
  16632. serializationObject.checkCollisions = camera.checkCollisions;
  16633. serializationObject.applyGravity = camera.applyGravity;
  16634. if (camera.ellipsoid) {
  16635. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16636. }
  16637. // Animations
  16638. appendAnimations(camera, serializationObject);
  16639. // Layer mask
  16640. serializationObject.layerMask = camera.layerMask;
  16641. return serializationObject;
  16642. };
  16643. var appendAnimations = function (source, destination) {
  16644. if (source.animations) {
  16645. destination.animations = [];
  16646. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16647. var animation = source.animations[animationIndex];
  16648. destination.animations.push(serializeAnimation(animation));
  16649. }
  16650. }
  16651. };
  16652. var serializeAnimation = function (animation) {
  16653. var serializationObject = {};
  16654. serializationObject.name = animation.name;
  16655. serializationObject.property = animation.targetProperty;
  16656. serializationObject.framePerSecond = animation.framePerSecond;
  16657. serializationObject.dataType = animation.dataType;
  16658. serializationObject.loopBehavior = animation.loopMode;
  16659. var dataType = animation.dataType;
  16660. serializationObject.keys = [];
  16661. var keys = animation.getKeys();
  16662. for (var index = 0; index < keys.length; index++) {
  16663. var animationKey = keys[index];
  16664. var key = {};
  16665. key.frame = animationKey.frame;
  16666. switch (dataType) {
  16667. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16668. key.values = [animationKey.value];
  16669. break;
  16670. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16671. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16672. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16673. key.values = animationKey.value.asArray();
  16674. break;
  16675. }
  16676. serializationObject.keys.push(key);
  16677. }
  16678. return serializationObject;
  16679. };
  16680. var serializeMultiMaterial = function (material) {
  16681. var serializationObject = {};
  16682. serializationObject.name = material.name;
  16683. serializationObject.id = material.id;
  16684. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16685. serializationObject.materials = [];
  16686. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16687. var subMat = material.subMaterials[matIndex];
  16688. if (subMat) {
  16689. serializationObject.materials.push(subMat.id);
  16690. } else {
  16691. serializationObject.materials.push(null);
  16692. }
  16693. }
  16694. return serializationObject;
  16695. };
  16696. var serializeMaterial = function (material) {
  16697. var serializationObject = {};
  16698. serializationObject.name = material.name;
  16699. serializationObject.ambient = material.ambientColor.asArray();
  16700. serializationObject.diffuse = material.diffuseColor.asArray();
  16701. serializationObject.specular = material.specularColor.asArray();
  16702. serializationObject.specularPower = material.specularPower;
  16703. serializationObject.emissive = material.emissiveColor.asArray();
  16704. serializationObject.alpha = material.alpha;
  16705. serializationObject.id = material.id;
  16706. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16707. serializationObject.backFaceCulling = material.backFaceCulling;
  16708. if (material.diffuseTexture) {
  16709. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16710. }
  16711. if (material.diffuseFresnelParameters) {
  16712. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16713. }
  16714. if (material.ambientTexture) {
  16715. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16716. }
  16717. if (material.opacityTexture) {
  16718. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16719. }
  16720. if (material.opacityFresnelParameters) {
  16721. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16722. }
  16723. if (material.reflectionTexture) {
  16724. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16725. }
  16726. if (material.reflectionFresnelParameters) {
  16727. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16728. }
  16729. if (material.emissiveTexture) {
  16730. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16731. }
  16732. if (material.emissiveFresnelParameters) {
  16733. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16734. }
  16735. if (material.specularTexture) {
  16736. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16737. }
  16738. if (material.bumpTexture) {
  16739. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16740. }
  16741. return serializationObject;
  16742. };
  16743. var serializeTexture = function (texture) {
  16744. var serializationObject = {};
  16745. if (!texture.name) {
  16746. return null;
  16747. }
  16748. if (texture instanceof BABYLON.CubeTexture) {
  16749. serializationObject.name = texture.name;
  16750. serializationObject.hasAlpha = texture.hasAlpha;
  16751. serializationObject.level = texture.level;
  16752. serializationObject.coordinatesMode = texture.coordinatesMode;
  16753. return serializationObject;
  16754. }
  16755. if (texture instanceof BABYLON.MirrorTexture) {
  16756. var mirrorTexture = texture;
  16757. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16758. serializationObject.renderList = [];
  16759. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16760. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16761. }
  16762. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16763. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16764. var renderTargetTexture = texture;
  16765. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16766. serializationObject.renderList = [];
  16767. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16768. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16769. }
  16770. }
  16771. var regularTexture = texture;
  16772. serializationObject.name = texture.name;
  16773. serializationObject.hasAlpha = texture.hasAlpha;
  16774. serializationObject.level = texture.level;
  16775. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16776. serializationObject.coordinatesMode = texture.coordinatesMode;
  16777. serializationObject.uOffset = regularTexture.uOffset;
  16778. serializationObject.vOffset = regularTexture.vOffset;
  16779. serializationObject.uScale = regularTexture.uScale;
  16780. serializationObject.vScale = regularTexture.vScale;
  16781. serializationObject.uAng = regularTexture.uAng;
  16782. serializationObject.vAng = regularTexture.vAng;
  16783. serializationObject.wAng = regularTexture.wAng;
  16784. serializationObject.wrapU = texture.wrapU;
  16785. serializationObject.wrapV = texture.wrapV;
  16786. // Animations
  16787. appendAnimations(texture, serializationObject);
  16788. return serializationObject;
  16789. };
  16790. var serializeSkeleton = function (skeleton) {
  16791. var serializationObject = {};
  16792. serializationObject.name = skeleton.name;
  16793. serializationObject.id = skeleton.id;
  16794. serializationObject.bones = [];
  16795. for (var index = 0; index < skeleton.bones.length; index++) {
  16796. var bone = skeleton.bones[index];
  16797. var serializedBone = {
  16798. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16799. name: bone.name,
  16800. matrix: bone.getLocalMatrix().toArray()
  16801. };
  16802. serializationObject.bones.push(serializedBone);
  16803. if (bone.animations && bone.animations.length > 0) {
  16804. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16805. }
  16806. }
  16807. return serializationObject;
  16808. };
  16809. var serializeParticleSystem = function (particleSystem) {
  16810. var serializationObject = {};
  16811. serializationObject.emitterId = particleSystem.emitter.id;
  16812. serializationObject.capacity = particleSystem.getCapacity();
  16813. if (particleSystem.particleTexture) {
  16814. serializationObject.textureName = particleSystem.particleTexture.name;
  16815. }
  16816. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16817. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16818. serializationObject.minSize = particleSystem.minSize;
  16819. serializationObject.maxSize = particleSystem.maxSize;
  16820. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16821. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16822. serializationObject.emitRate = particleSystem.emitRate;
  16823. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16824. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16825. serializationObject.gravity = particleSystem.gravity.asArray();
  16826. serializationObject.direction1 = particleSystem.direction1.asArray();
  16827. serializationObject.direction2 = particleSystem.direction2.asArray();
  16828. serializationObject.color1 = particleSystem.color1.asArray();
  16829. serializationObject.color2 = particleSystem.color2.asArray();
  16830. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16831. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16832. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16833. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16834. serializationObject.blendMode = particleSystem.blendMode;
  16835. return serializationObject;
  16836. };
  16837. var serializeLensFlareSystem = function (lensFlareSystem) {
  16838. var serializationObject = {};
  16839. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16840. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16841. serializationObject.flares = [];
  16842. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16843. var flare = lensFlareSystem.lensFlares[index];
  16844. serializationObject.flares.push({
  16845. size: flare.size,
  16846. position: flare.position,
  16847. color: flare.color.asArray(),
  16848. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16849. });
  16850. }
  16851. return serializationObject;
  16852. };
  16853. var serializeShadowGenerator = function (light) {
  16854. var serializationObject = {};
  16855. var shadowGenerator = light.getShadowGenerator();
  16856. serializationObject.lightId = light.id;
  16857. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16858. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16859. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16860. serializationObject.renderList = [];
  16861. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16862. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16863. serializationObject.renderList.push(mesh.id);
  16864. }
  16865. return serializationObject;
  16866. };
  16867. var serializedGeometries = [];
  16868. var serializeGeometry = function (geometry, serializationGeometries) {
  16869. if (serializedGeometries[geometry.id]) {
  16870. return;
  16871. }
  16872. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16873. serializationGeometries.boxes.push(serializeBox(geometry));
  16874. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16875. serializationGeometries.spheres.push(serializeSphere(geometry));
  16876. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16877. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16878. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16879. serializationGeometries.toruses.push(serializeTorus(geometry));
  16880. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16881. serializationGeometries.grounds.push(serializeGround(geometry));
  16882. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16883. serializationGeometries.planes.push(serializePlane(geometry));
  16884. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16885. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16886. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16887. throw new Error("Unknow primitive type");
  16888. } else {
  16889. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16890. }
  16891. serializedGeometries[geometry.id] = true;
  16892. };
  16893. var serializeGeometryBase = function (geometry) {
  16894. var serializationObject = {};
  16895. serializationObject.id = geometry.id;
  16896. if (BABYLON.Tags.HasTags(geometry)) {
  16897. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16898. }
  16899. return serializationObject;
  16900. };
  16901. var serializeVertexData = function (vertexData) {
  16902. var serializationObject = serializeGeometryBase(vertexData);
  16903. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16904. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16905. }
  16906. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16907. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16908. }
  16909. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16910. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16911. }
  16912. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16913. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16914. }
  16915. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16916. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16917. }
  16918. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16919. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16920. serializationObject.matricesIndices._isExpanded = true;
  16921. }
  16922. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16923. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16924. }
  16925. serializationObject.indices = vertexData.getIndices();
  16926. return serializationObject;
  16927. };
  16928. var serializePrimitive = function (primitive) {
  16929. var serializationObject = serializeGeometryBase(primitive);
  16930. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16931. return serializationObject;
  16932. };
  16933. var serializeBox = function (box) {
  16934. var serializationObject = serializePrimitive(box);
  16935. serializationObject.size = box.size;
  16936. return serializationObject;
  16937. };
  16938. var serializeSphere = function (sphere) {
  16939. var serializationObject = serializePrimitive(sphere);
  16940. serializationObject.segments = sphere.segments;
  16941. serializationObject.diameter = sphere.diameter;
  16942. return serializationObject;
  16943. };
  16944. var serializeCylinder = function (cylinder) {
  16945. var serializationObject = serializePrimitive(cylinder);
  16946. serializationObject.height = cylinder.height;
  16947. serializationObject.diameterTop = cylinder.diameterTop;
  16948. serializationObject.diameterBottom = cylinder.diameterBottom;
  16949. serializationObject.tessellation = cylinder.tessellation;
  16950. return serializationObject;
  16951. };
  16952. var serializeTorus = function (torus) {
  16953. var serializationObject = serializePrimitive(torus);
  16954. serializationObject.diameter = torus.diameter;
  16955. serializationObject.thickness = torus.thickness;
  16956. serializationObject.tessellation = torus.tessellation;
  16957. return serializationObject;
  16958. };
  16959. var serializeGround = function (ground) {
  16960. var serializationObject = serializePrimitive(ground);
  16961. serializationObject.width = ground.width;
  16962. serializationObject.height = ground.height;
  16963. serializationObject.subdivisions = ground.subdivisions;
  16964. return serializationObject;
  16965. };
  16966. var serializePlane = function (plane) {
  16967. var serializationObject = serializePrimitive(plane);
  16968. serializationObject.size = plane.size;
  16969. return serializationObject;
  16970. };
  16971. var serializeTorusKnot = function (torusKnot) {
  16972. var serializationObject = serializePrimitive(torusKnot);
  16973. serializationObject.radius = torusKnot.radius;
  16974. serializationObject.tube = torusKnot.tube;
  16975. serializationObject.radialSegments = torusKnot.radialSegments;
  16976. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16977. serializationObject.p = torusKnot.p;
  16978. serializationObject.q = torusKnot.q;
  16979. return serializationObject;
  16980. };
  16981. var serializeMesh = function (mesh, serializationScene) {
  16982. var serializationObject = {};
  16983. serializationObject.name = mesh.name;
  16984. serializationObject.id = mesh.id;
  16985. if (BABYLON.Tags.HasTags(mesh)) {
  16986. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16987. }
  16988. serializationObject.position = mesh.position.asArray();
  16989. if (mesh.rotationQuaternion) {
  16990. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16991. } else if (mesh.rotation) {
  16992. serializationObject.rotation = mesh.rotation.asArray();
  16993. }
  16994. serializationObject.scaling = mesh.scaling.asArray();
  16995. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16996. serializationObject.isEnabled = mesh.isEnabled();
  16997. serializationObject.isVisible = mesh.isVisible;
  16998. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16999. serializationObject.pickable = mesh.isPickable;
  17000. serializationObject.receiveShadows = mesh.receiveShadows;
  17001. serializationObject.billboardMode = mesh.billboardMode;
  17002. serializationObject.visibility = mesh.visibility;
  17003. serializationObject.checkCollisions = mesh.checkCollisions;
  17004. // Parent
  17005. if (mesh.parent) {
  17006. serializationObject.parentId = mesh.parent.id;
  17007. }
  17008. // Geometry
  17009. var geometry = mesh._geometry;
  17010. if (geometry) {
  17011. var geometryId = geometry.id;
  17012. serializationObject.geometryId = geometryId;
  17013. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17014. // 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
  17015. serializeGeometry(geometry, serializationScene.geometries);
  17016. }
  17017. // SubMeshes
  17018. serializationObject.subMeshes = [];
  17019. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17020. var subMesh = mesh.subMeshes[subIndex];
  17021. serializationObject.subMeshes.push({
  17022. materialIndex: subMesh.materialIndex,
  17023. verticesStart: subMesh.verticesStart,
  17024. verticesCount: subMesh.verticesCount,
  17025. indexStart: subMesh.indexStart,
  17026. indexCount: subMesh.indexCount
  17027. });
  17028. }
  17029. }
  17030. // Material
  17031. if (mesh.material) {
  17032. serializationObject.materialId = mesh.material.id;
  17033. } else {
  17034. mesh.material = null;
  17035. }
  17036. // Skeleton
  17037. if (mesh.skeleton) {
  17038. serializationObject.skeletonId = mesh.skeleton.id;
  17039. }
  17040. // Physics
  17041. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17042. serializationObject.physicsMass = mesh.getPhysicsMass();
  17043. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17044. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17045. switch (mesh.getPhysicsImpostor()) {
  17046. case BABYLON.PhysicsEngine.BoxImpostor:
  17047. serializationObject.physicsImpostor = 1;
  17048. break;
  17049. case BABYLON.PhysicsEngine.SphereImpostor:
  17050. serializationObject.physicsImpostor = 2;
  17051. break;
  17052. }
  17053. }
  17054. // Instances
  17055. serializationObject.instances = [];
  17056. for (var index = 0; index < mesh.instances.length; index++) {
  17057. var instance = mesh.instances[index];
  17058. var serializationInstance = {
  17059. name: instance.name,
  17060. position: instance.position,
  17061. rotation: instance.rotation,
  17062. rotationQuaternion: instance.rotationQuaternion,
  17063. scaling: instance.scaling
  17064. };
  17065. serializationObject.instances.push(serializationInstance);
  17066. // Animations
  17067. appendAnimations(instance, serializationInstance);
  17068. }
  17069. // Animations
  17070. appendAnimations(mesh, serializationObject);
  17071. // Layer mask
  17072. serializationObject.layerMask = mesh.layerMask;
  17073. return serializationObject;
  17074. };
  17075. var SceneSerializer = (function () {
  17076. function SceneSerializer() {
  17077. }
  17078. SceneSerializer.Serialize = function (scene) {
  17079. var serializationObject = {};
  17080. // Scene
  17081. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17082. serializationObject.autoClear = scene.autoClear;
  17083. serializationObject.clearColor = scene.clearColor.asArray();
  17084. serializationObject.ambientColor = scene.ambientColor.asArray();
  17085. serializationObject.gravity = scene.gravity.asArray();
  17086. // Fog
  17087. if (scene.fogMode && scene.fogMode !== 0) {
  17088. serializationObject.fogMode = scene.fogMode;
  17089. serializationObject.fogColor = scene.fogColor.asArray();
  17090. serializationObject.fogStart = scene.fogStart;
  17091. serializationObject.fogEnd = scene.fogEnd;
  17092. serializationObject.fogDensity = scene.fogDensity;
  17093. }
  17094. // Lights
  17095. serializationObject.lights = [];
  17096. for (var index = 0; index < scene.lights.length; index++) {
  17097. var light = scene.lights[index];
  17098. serializationObject.lights.push(serializeLight(light));
  17099. }
  17100. // Cameras
  17101. serializationObject.cameras = [];
  17102. for (index = 0; index < scene.cameras.length; index++) {
  17103. var camera = scene.cameras[index];
  17104. if (camera instanceof BABYLON.FreeCamera) {
  17105. serializationObject.cameras.push(serializeCamera(camera));
  17106. }
  17107. }
  17108. if (scene.activeCamera) {
  17109. serializationObject.activeCameraID = scene.activeCamera.id;
  17110. }
  17111. // Materials
  17112. serializationObject.materials = [];
  17113. serializationObject.multiMaterials = [];
  17114. for (index = 0; index < scene.materials.length; index++) {
  17115. var material = scene.materials[index];
  17116. if (material instanceof BABYLON.StandardMaterial) {
  17117. serializationObject.materials.push(serializeMaterial(material));
  17118. } else if (material instanceof BABYLON.MultiMaterial) {
  17119. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17120. }
  17121. }
  17122. // Skeletons
  17123. serializationObject.skeletons = [];
  17124. for (index = 0; index < scene.skeletons.length; index++) {
  17125. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17126. }
  17127. // Geometries
  17128. serializationObject.geometries = {};
  17129. serializationObject.geometries.boxes = [];
  17130. serializationObject.geometries.spheres = [];
  17131. serializationObject.geometries.cylinders = [];
  17132. serializationObject.geometries.toruses = [];
  17133. serializationObject.geometries.grounds = [];
  17134. serializationObject.geometries.planes = [];
  17135. serializationObject.geometries.torusKnots = [];
  17136. serializationObject.geometries.vertexData = [];
  17137. serializedGeometries = [];
  17138. var geometries = scene.getGeometries();
  17139. for (var index = 0; index < geometries.length; index++) {
  17140. var geometry = geometries[index];
  17141. if (geometry.isReady()) {
  17142. serializeGeometry(geometry, serializationObject.geometries);
  17143. }
  17144. }
  17145. // Meshes
  17146. serializationObject.meshes = [];
  17147. for (index = 0; index < scene.meshes.length; index++) {
  17148. var abstractMesh = scene.meshes[index];
  17149. if (abstractMesh instanceof BABYLON.Mesh) {
  17150. var mesh = abstractMesh;
  17151. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17152. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17153. }
  17154. }
  17155. }
  17156. // Particles Systems
  17157. serializationObject.particleSystems = [];
  17158. for (index = 0; index < scene.particleSystems.length; index++) {
  17159. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17160. }
  17161. // Lens flares
  17162. serializationObject.lensFlareSystems = [];
  17163. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17164. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17165. }
  17166. // Shadows
  17167. serializationObject.shadowGenerators = [];
  17168. for (index = 0; index < scene.lights.length; index++) {
  17169. light = scene.lights[index];
  17170. if (light.getShadowGenerator()) {
  17171. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17172. }
  17173. }
  17174. return serializationObject;
  17175. };
  17176. return SceneSerializer;
  17177. })();
  17178. BABYLON.SceneSerializer = SceneSerializer;
  17179. })(BABYLON || (BABYLON = {}));
  17180. //# sourceMappingURL=babylon.sceneSerializer.js.map
  17181. var BABYLON;
  17182. (function (BABYLON) {
  17183. var SceneLoader = (function () {
  17184. function SceneLoader() {
  17185. }
  17186. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17187. get: function () {
  17188. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17189. },
  17190. set: function (value) {
  17191. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17192. },
  17193. enumerable: true,
  17194. configurable: true
  17195. });
  17196. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17197. get: function () {
  17198. return SceneLoader._ShowLoadingScreen;
  17199. },
  17200. set: function (value) {
  17201. SceneLoader._ShowLoadingScreen = value;
  17202. },
  17203. enumerable: true,
  17204. configurable: true
  17205. });
  17206. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17207. var dotPosition = sceneFilename.lastIndexOf(".");
  17208. var queryStringPosition = sceneFilename.indexOf("?");
  17209. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17210. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17211. var plugin = this._registeredPlugins[index];
  17212. if (plugin.extensions.indexOf(extension) !== -1) {
  17213. return plugin;
  17214. }
  17215. }
  17216. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17217. };
  17218. // Public functions
  17219. SceneLoader.RegisterPlugin = function (plugin) {
  17220. plugin.extensions = plugin.extensions.toLowerCase();
  17221. SceneLoader._registeredPlugins.push(plugin);
  17222. };
  17223. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17224. var manifestChecked = function (success) {
  17225. scene.database = database;
  17226. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17227. var importMeshFromData = function (data) {
  17228. var meshes = [];
  17229. var particleSystems = [];
  17230. var skeletons = [];
  17231. try {
  17232. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17233. if (onerror) {
  17234. onerror(scene, 'unable to load the scene');
  17235. }
  17236. return;
  17237. }
  17238. } catch (e) {
  17239. if (onerror) {
  17240. onerror(scene, e);
  17241. }
  17242. return;
  17243. }
  17244. if (onsuccess) {
  17245. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17246. onsuccess(meshes, particleSystems, skeletons);
  17247. }
  17248. };
  17249. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17250. // Direct load
  17251. importMeshFromData(sceneFilename.substr(5));
  17252. return;
  17253. }
  17254. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17255. importMeshFromData(data);
  17256. }, progressCallBack, database);
  17257. };
  17258. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17259. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17260. };
  17261. /**
  17262. * Load a scene
  17263. * @param rootUrl a string that defines the root url for scene and resources
  17264. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17265. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17266. */
  17267. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17268. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17269. };
  17270. /**
  17271. * Append a scene
  17272. * @param rootUrl a string that defines the root url for scene and resources
  17273. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17274. * @param scene is the instance of BABYLON.Scene to append to
  17275. */
  17276. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17277. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17278. var database;
  17279. if (SceneLoader.ShowLoadingScreen) {
  17280. scene.getEngine().displayLoadingUI();
  17281. }
  17282. var loadSceneFromData = function (data) {
  17283. scene.database = database;
  17284. if (!plugin.load(scene, data, rootUrl)) {
  17285. if (onerror) {
  17286. onerror(scene);
  17287. }
  17288. scene.getEngine().hideLoadingUI();
  17289. return;
  17290. }
  17291. if (onsuccess) {
  17292. onsuccess(scene);
  17293. }
  17294. if (SceneLoader.ShowLoadingScreen) {
  17295. scene.executeWhenReady(function () {
  17296. scene.getEngine().hideLoadingUI();
  17297. });
  17298. }
  17299. };
  17300. var manifestChecked = function (success) {
  17301. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17302. };
  17303. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17304. // Direct load
  17305. loadSceneFromData(sceneFilename.substr(5));
  17306. return;
  17307. }
  17308. if (rootUrl.indexOf("file:") === -1) {
  17309. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17310. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17311. } else {
  17312. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17313. }
  17314. };
  17315. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17316. SceneLoader._ShowLoadingScreen = true;
  17317. SceneLoader._registeredPlugins = new Array();
  17318. return SceneLoader;
  17319. })();
  17320. BABYLON.SceneLoader = SceneLoader;
  17321. ;
  17322. })(BABYLON || (BABYLON = {}));
  17323. //# sourceMappingURL=babylon.sceneLoader.js.map
  17324. var BABYLON;
  17325. (function (BABYLON) {
  17326. (function (Internals) {
  17327. var checkColors4 = function (colors, count) {
  17328. // Check if color3 was used
  17329. if (colors.length === count * 3) {
  17330. var colors4 = [];
  17331. for (var index = 0; index < colors.length; index += 3) {
  17332. var newIndex = (index / 3) * 4;
  17333. colors4[newIndex] = colors[index];
  17334. colors4[newIndex + 1] = colors[index + 1];
  17335. colors4[newIndex + 2] = colors[index + 2];
  17336. colors4[newIndex + 3] = 1.0;
  17337. }
  17338. return colors4;
  17339. }
  17340. return colors;
  17341. };
  17342. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17343. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17344. texture.name = parsedTexture.name;
  17345. texture.hasAlpha = parsedTexture.hasAlpha;
  17346. texture.level = parsedTexture.level;
  17347. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17348. return texture;
  17349. };
  17350. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17351. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17352. return null;
  17353. }
  17354. if (parsedTexture.isCube) {
  17355. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17356. }
  17357. var texture;
  17358. if (parsedTexture.mirrorPlane) {
  17359. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17360. texture._waitingRenderList = parsedTexture.renderList;
  17361. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17362. } else if (parsedTexture.isRenderTarget) {
  17363. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17364. texture._waitingRenderList = parsedTexture.renderList;
  17365. } else {
  17366. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17367. }
  17368. texture.name = parsedTexture.name;
  17369. texture.hasAlpha = parsedTexture.hasAlpha;
  17370. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17371. texture.level = parsedTexture.level;
  17372. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17373. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17374. texture.uOffset = parsedTexture.uOffset;
  17375. texture.vOffset = parsedTexture.vOffset;
  17376. texture.uScale = parsedTexture.uScale;
  17377. texture.vScale = parsedTexture.vScale;
  17378. texture.uAng = parsedTexture.uAng;
  17379. texture.vAng = parsedTexture.vAng;
  17380. texture.wAng = parsedTexture.wAng;
  17381. texture.wrapU = parsedTexture.wrapU;
  17382. texture.wrapV = parsedTexture.wrapV;
  17383. // Animations
  17384. if (parsedTexture.animations) {
  17385. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17386. var parsedAnimation = parsedTexture.animations[animationIndex];
  17387. texture.animations.push(parseAnimation(parsedAnimation));
  17388. }
  17389. }
  17390. return texture;
  17391. };
  17392. var parseSkeleton = function (parsedSkeleton, scene) {
  17393. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17394. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17395. var parsedBone = parsedSkeleton.bones[index];
  17396. var parentBone = null;
  17397. if (parsedBone.parentBoneIndex > -1) {
  17398. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17399. }
  17400. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17401. if (parsedBone.animation) {
  17402. bone.animations.push(parseAnimation(parsedBone.animation));
  17403. }
  17404. }
  17405. return skeleton;
  17406. };
  17407. var parseFresnelParameters = function (parsedFresnelParameters) {
  17408. var fresnelParameters = new BABYLON.FresnelParameters();
  17409. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17410. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17411. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17412. fresnelParameters.bias = parsedFresnelParameters.bias;
  17413. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17414. return fresnelParameters;
  17415. };
  17416. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17417. var material;
  17418. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17419. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17420. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17421. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17422. material.specularPower = parsedMaterial.specularPower;
  17423. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17424. material.alpha = parsedMaterial.alpha;
  17425. material.id = parsedMaterial.id;
  17426. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17427. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17428. material.wireframe = parsedMaterial.wireframe;
  17429. if (parsedMaterial.diffuseTexture) {
  17430. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17431. }
  17432. if (parsedMaterial.diffuseFresnelParameters) {
  17433. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17434. }
  17435. if (parsedMaterial.ambientTexture) {
  17436. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17437. }
  17438. if (parsedMaterial.opacityTexture) {
  17439. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17440. }
  17441. if (parsedMaterial.opacityFresnelParameters) {
  17442. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17443. }
  17444. if (parsedMaterial.reflectionTexture) {
  17445. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17446. }
  17447. if (parsedMaterial.reflectionFresnelParameters) {
  17448. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17449. }
  17450. if (parsedMaterial.emissiveTexture) {
  17451. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17452. }
  17453. if (parsedMaterial.emissiveFresnelParameters) {
  17454. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17455. }
  17456. if (parsedMaterial.specularTexture) {
  17457. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17458. }
  17459. if (parsedMaterial.bumpTexture) {
  17460. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17461. }
  17462. return material;
  17463. };
  17464. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17465. for (var index = 0; index < parsedData.materials.length; index++) {
  17466. var parsedMaterial = parsedData.materials[index];
  17467. if (parsedMaterial.id === id) {
  17468. return parseMaterial(parsedMaterial, scene, rootUrl);
  17469. }
  17470. }
  17471. return null;
  17472. };
  17473. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17474. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17475. multiMaterial.id = parsedMultiMaterial.id;
  17476. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17477. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17478. var subMatId = parsedMultiMaterial.materials[matIndex];
  17479. if (subMatId) {
  17480. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17481. } else {
  17482. multiMaterial.subMaterials.push(null);
  17483. }
  17484. }
  17485. return multiMaterial;
  17486. };
  17487. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17488. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17489. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17490. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17491. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17492. var parsedFlare = parsedLensFlareSystem.flares[index];
  17493. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17494. }
  17495. return lensFlareSystem;
  17496. };
  17497. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17498. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17499. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17500. if (parsedParticleSystem.textureName) {
  17501. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17502. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17503. }
  17504. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17505. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17506. particleSystem.minSize = parsedParticleSystem.minSize;
  17507. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17508. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17509. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17510. particleSystem.emitter = emitter;
  17511. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17512. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17513. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17514. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17515. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17516. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17517. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17518. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17519. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17520. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17521. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17522. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17523. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17524. particleSystem.start();
  17525. return particleSystem;
  17526. };
  17527. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17528. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17529. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17530. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17531. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17532. shadowGenerator.getShadowMap().renderList.push(mesh);
  17533. }
  17534. if (parsedShadowGenerator.usePoissonSampling) {
  17535. shadowGenerator.usePoissonSampling = true;
  17536. } else {
  17537. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17538. }
  17539. return shadowGenerator;
  17540. };
  17541. var parseAnimation = function (parsedAnimation) {
  17542. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17543. var dataType = parsedAnimation.dataType;
  17544. var keys = [];
  17545. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17546. var key = parsedAnimation.keys[index];
  17547. var data;
  17548. switch (dataType) {
  17549. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17550. data = key.values[0];
  17551. break;
  17552. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17553. data = BABYLON.Quaternion.FromArray(key.values);
  17554. break;
  17555. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17556. data = BABYLON.Matrix.FromArray(key.values);
  17557. break;
  17558. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17559. default:
  17560. data = BABYLON.Vector3.FromArray(key.values);
  17561. break;
  17562. }
  17563. keys.push({
  17564. frame: key.frame,
  17565. value: data
  17566. });
  17567. }
  17568. animation.setKeys(keys);
  17569. return animation;
  17570. };
  17571. var parseLight = function (parsedLight, scene) {
  17572. var light;
  17573. switch (parsedLight.type) {
  17574. case 0:
  17575. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17576. break;
  17577. case 1:
  17578. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17579. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17580. break;
  17581. case 2:
  17582. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17583. break;
  17584. case 3:
  17585. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17586. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17587. break;
  17588. }
  17589. light.id = parsedLight.id;
  17590. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17591. if (parsedLight.intensity !== undefined) {
  17592. light.intensity = parsedLight.intensity;
  17593. }
  17594. if (parsedLight.range) {
  17595. light.range = parsedLight.range;
  17596. }
  17597. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17598. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17599. if (parsedLight.excludedMeshesIds) {
  17600. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17601. }
  17602. // Parent
  17603. if (parsedLight.parentId) {
  17604. light._waitingParentId = parsedLight.parentId;
  17605. }
  17606. if (parsedLight.includedOnlyMeshesIds) {
  17607. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17608. }
  17609. // Animations
  17610. if (parsedLight.animations) {
  17611. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17612. var parsedAnimation = parsedLight.animations[animationIndex];
  17613. light.animations.push(parseAnimation(parsedAnimation));
  17614. }
  17615. }
  17616. if (parsedLight.autoAnimate) {
  17617. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17618. }
  17619. };
  17620. var parseCamera = function (parsedCamera, scene) {
  17621. var camera;
  17622. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17623. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17624. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17625. var alpha = parsedCamera.alpha;
  17626. var beta = parsedCamera.beta;
  17627. var radius = parsedCamera.radius;
  17628. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17629. var eye_space = parsedCamera.eye_space;
  17630. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17631. } else {
  17632. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17633. }
  17634. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17635. eye_space = parsedCamera.eye_space;
  17636. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17637. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17638. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17639. } else if (parsedCamera.type === "FollowCamera") {
  17640. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17641. camera.heightOffset = parsedCamera.heightOffset;
  17642. camera.radius = parsedCamera.radius;
  17643. camera.rotationOffset = parsedCamera.rotationOffset;
  17644. if (lockedTargetMesh)
  17645. camera.target = lockedTargetMesh;
  17646. } else if (parsedCamera.type === "GamepadCamera") {
  17647. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17648. } else if (parsedCamera.type === "OculusCamera") {
  17649. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17650. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17651. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17652. } else if (parsedCamera.type === "TouchCamera") {
  17653. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17654. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17655. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17656. } else if (parsedCamera.type === "WebVRCamera") {
  17657. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17658. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17659. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17660. } else {
  17661. // Free Camera is the default value
  17662. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17663. }
  17664. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17665. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17666. camera.lockedTarget = lockedTargetMesh;
  17667. }
  17668. camera.id = parsedCamera.id;
  17669. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17670. // Parent
  17671. if (parsedCamera.parentId) {
  17672. camera._waitingParentId = parsedCamera.parentId;
  17673. }
  17674. // Target
  17675. if (parsedCamera.target) {
  17676. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17677. } else {
  17678. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17679. }
  17680. camera.fov = parsedCamera.fov;
  17681. camera.minZ = parsedCamera.minZ;
  17682. camera.maxZ = parsedCamera.maxZ;
  17683. camera.speed = parsedCamera.speed;
  17684. camera.inertia = parsedCamera.inertia;
  17685. camera.checkCollisions = parsedCamera.checkCollisions;
  17686. camera.applyGravity = parsedCamera.applyGravity;
  17687. if (parsedCamera.ellipsoid) {
  17688. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17689. }
  17690. // Animations
  17691. if (parsedCamera.animations) {
  17692. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17693. var parsedAnimation = parsedCamera.animations[animationIndex];
  17694. camera.animations.push(parseAnimation(parsedAnimation));
  17695. }
  17696. }
  17697. if (parsedCamera.autoAnimate) {
  17698. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17699. }
  17700. // Layer Mask
  17701. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17702. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17703. } else {
  17704. camera.layerMask = 0xFFFFFFFF;
  17705. }
  17706. return camera;
  17707. };
  17708. var parseGeometry = function (parsedGeometry, scene) {
  17709. var id = parsedGeometry.id;
  17710. return scene.getGeometryByID(id);
  17711. };
  17712. var parseBox = function (parsedBox, scene) {
  17713. if (parseGeometry(parsedBox, scene)) {
  17714. return null;
  17715. }
  17716. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17717. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17718. scene.pushGeometry(box, true);
  17719. return box;
  17720. };
  17721. var parseSphere = function (parsedSphere, scene) {
  17722. if (parseGeometry(parsedSphere, scene)) {
  17723. return null;
  17724. }
  17725. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17726. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17727. scene.pushGeometry(sphere, true);
  17728. return sphere;
  17729. };
  17730. var parseCylinder = function (parsedCylinder, scene) {
  17731. if (parseGeometry(parsedCylinder, scene)) {
  17732. return null;
  17733. }
  17734. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17735. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17736. scene.pushGeometry(cylinder, true);
  17737. return cylinder;
  17738. };
  17739. var parseTorus = function (parsedTorus, scene) {
  17740. if (parseGeometry(parsedTorus, scene)) {
  17741. return null;
  17742. }
  17743. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17744. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17745. scene.pushGeometry(torus, true);
  17746. return torus;
  17747. };
  17748. var parseGround = function (parsedGround, scene) {
  17749. if (parseGeometry(parsedGround, scene)) {
  17750. return null;
  17751. }
  17752. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17753. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17754. scene.pushGeometry(ground, true);
  17755. return ground;
  17756. };
  17757. var parsePlane = function (parsedPlane, scene) {
  17758. if (parseGeometry(parsedPlane, scene)) {
  17759. return null;
  17760. }
  17761. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17762. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17763. scene.pushGeometry(plane, true);
  17764. return plane;
  17765. };
  17766. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17767. if (parseGeometry(parsedTorusKnot, scene)) {
  17768. return null;
  17769. }
  17770. 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);
  17771. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17772. scene.pushGeometry(torusKnot, true);
  17773. return torusKnot;
  17774. };
  17775. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17776. if (parseGeometry(parsedVertexData, scene)) {
  17777. return null;
  17778. }
  17779. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17780. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17781. if (parsedVertexData.delayLoadingFile) {
  17782. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17783. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17784. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17785. geometry._delayInfo = [];
  17786. if (parsedVertexData.hasUVs) {
  17787. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17788. }
  17789. if (parsedVertexData.hasUVs2) {
  17790. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17791. }
  17792. if (parsedVertexData.hasColors) {
  17793. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17794. }
  17795. if (parsedVertexData.hasMatricesIndices) {
  17796. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17797. }
  17798. if (parsedVertexData.hasMatricesWeights) {
  17799. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17800. }
  17801. geometry._delayLoadingFunction = importVertexData;
  17802. } else {
  17803. importVertexData(parsedVertexData, geometry);
  17804. }
  17805. scene.pushGeometry(geometry, true);
  17806. return geometry;
  17807. };
  17808. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17809. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17810. mesh.id = parsedMesh.id;
  17811. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17812. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17813. if (parsedMesh.rotationQuaternion) {
  17814. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17815. } else if (parsedMesh.rotation) {
  17816. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17817. }
  17818. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17819. if (parsedMesh.localMatrix) {
  17820. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17821. } else if (parsedMesh.pivotMatrix) {
  17822. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17823. }
  17824. mesh.setEnabled(parsedMesh.isEnabled);
  17825. mesh.isVisible = parsedMesh.isVisible;
  17826. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17827. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17828. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17829. if (parsedMesh.applyFog !== undefined) {
  17830. mesh.applyFog = parsedMesh.applyFog;
  17831. }
  17832. if (parsedMesh.pickable !== undefined) {
  17833. mesh.isPickable = parsedMesh.pickable;
  17834. }
  17835. if (parsedMesh.alphaIndex !== undefined) {
  17836. mesh.alphaIndex = parsedMesh.alphaIndex;
  17837. }
  17838. mesh.receiveShadows = parsedMesh.receiveShadows;
  17839. mesh.billboardMode = parsedMesh.billboardMode;
  17840. if (parsedMesh.visibility !== undefined) {
  17841. mesh.visibility = parsedMesh.visibility;
  17842. }
  17843. mesh.checkCollisions = parsedMesh.checkCollisions;
  17844. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17845. // Parent
  17846. if (parsedMesh.parentId) {
  17847. mesh._waitingParentId = parsedMesh.parentId;
  17848. }
  17849. // Actions
  17850. if (parsedMesh.actions !== undefined) {
  17851. mesh._waitingActions = parsedMesh.actions;
  17852. }
  17853. // Geometry
  17854. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17855. if (parsedMesh.delayLoadingFile) {
  17856. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17857. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17858. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17859. if (parsedMesh._binaryInfo) {
  17860. mesh._binaryInfo = parsedMesh._binaryInfo;
  17861. }
  17862. mesh._delayInfo = [];
  17863. if (parsedMesh.hasUVs) {
  17864. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17865. }
  17866. if (parsedMesh.hasUVs2) {
  17867. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17868. }
  17869. if (parsedMesh.hasColors) {
  17870. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17871. }
  17872. if (parsedMesh.hasMatricesIndices) {
  17873. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17874. }
  17875. if (parsedMesh.hasMatricesWeights) {
  17876. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17877. }
  17878. mesh._delayLoadingFunction = importGeometry;
  17879. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17880. mesh._checkDelayState();
  17881. }
  17882. } else {
  17883. importGeometry(parsedMesh, mesh);
  17884. }
  17885. // Material
  17886. if (parsedMesh.materialId) {
  17887. mesh.setMaterialByID(parsedMesh.materialId);
  17888. } else {
  17889. mesh.material = null;
  17890. }
  17891. // Skeleton
  17892. if (parsedMesh.skeletonId > -1) {
  17893. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17894. }
  17895. // Physics
  17896. if (parsedMesh.physicsImpostor) {
  17897. if (!scene.isPhysicsEnabled()) {
  17898. scene.enablePhysics();
  17899. }
  17900. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17901. }
  17902. // Animations
  17903. if (parsedMesh.animations) {
  17904. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17905. var parsedAnimation = parsedMesh.animations[animationIndex];
  17906. mesh.animations.push(parseAnimation(parsedAnimation));
  17907. }
  17908. }
  17909. if (parsedMesh.autoAnimate) {
  17910. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17911. }
  17912. // Layer Mask
  17913. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17914. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17915. } else {
  17916. mesh.layerMask = 0xFFFFFFFF;
  17917. }
  17918. // Instances
  17919. if (parsedMesh.instances) {
  17920. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17921. var parsedInstance = parsedMesh.instances[index];
  17922. var instance = mesh.createInstance(parsedInstance.name);
  17923. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17924. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17925. if (parsedInstance.rotationQuaternion) {
  17926. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17927. } else if (parsedInstance.rotation) {
  17928. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17929. }
  17930. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17931. instance.checkCollisions = mesh.checkCollisions;
  17932. if (parsedMesh.animations) {
  17933. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17934. parsedAnimation = parsedMesh.animations[animationIndex];
  17935. instance.animations.push(parseAnimation(parsedAnimation));
  17936. }
  17937. }
  17938. }
  17939. }
  17940. return mesh;
  17941. };
  17942. var parseActions = function (parsedActions, object, scene) {
  17943. var Types = { TRIGGER: 0, ACTION: 1, FLOW_CONTROL: 2, OBJECT: 3, SCENE: 4 };
  17944. object.actionManager = new BABYLON.ActionManager(scene);
  17945. var instanciate = function (name, params) {
  17946. var newInstance = Object.create(BABYLON[name].prototype);
  17947. newInstance.constructor.apply(newInstance, params);
  17948. return newInstance;
  17949. };
  17950. var getObjectByName = function (name) {
  17951. var object = scene.getMeshByName(name);
  17952. if (!object)
  17953. object = scene.getLightByName(name);
  17954. if (!object)
  17955. object = scene.getCameraByName(name);
  17956. return object;
  17957. };
  17958. // traverse graph per trigger
  17959. var traverse = function (parsedAction, trigger, condition, action, actionManager) {
  17960. var parameters = new Array();
  17961. // Parameters
  17962. if (parsedAction.type == Types.FLOW_CONTROL)
  17963. parameters.push(actionManager);
  17964. else
  17965. parameters.push(trigger);
  17966. for (var i = 0; i < parsedAction.properties.length; i++) {
  17967. var value = parsedAction.properties[i].value;
  17968. if (parsedAction.properties[i].name == "target") {
  17969. value = getObjectByName(value);
  17970. } else if (parsedAction.properties[i].name != "propertyPath") {
  17971. if (value == "false" || value == "true")
  17972. value = value == "true";
  17973. else if (parsedAction.type == Types.FLOW_CONTROL && parsedAction.properties[i].name == "operator")
  17974. value = BABYLON.ValueCondition[value];
  17975. else
  17976. value = parseFloat(value);
  17977. }
  17978. parameters.push(value);
  17979. }
  17980. parameters.push(condition);
  17981. // If interpolate value action
  17982. if (parsedAction.name == "InterpolateValueAction") {
  17983. var param = parameters[parameters.length - 2];
  17984. parameters[parameters.length - 1] = param;
  17985. parameters[parameters.length - 2] = condition;
  17986. }
  17987. // Action or condition
  17988. var newAction = instanciate(parsedAction.name, parameters);
  17989. if (newAction instanceof BABYLON.Condition) {
  17990. condition = newAction;
  17991. newAction = action;
  17992. } else {
  17993. condition = null;
  17994. if (action)
  17995. action.then(newAction);
  17996. else
  17997. actionManager.registerAction(newAction);
  17998. }
  17999. for (var i = 0; i < parsedAction.children.length; i++)
  18000. traverse(parsedAction.children[i], trigger, condition, newAction, actionManager);
  18001. };
  18002. for (var i = 0; i < parsedActions.children.length; i++) {
  18003. var triggerParams;
  18004. var trigger = parsedActions.children[i];
  18005. if (trigger.properties.length > 0) {
  18006. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18007. } else
  18008. triggerParams = BABYLON.ActionManager[trigger.name];
  18009. for (var j = 0; j < trigger.children.length; j++)
  18010. traverse(trigger.children[j], triggerParams, null, null, object.actionManager);
  18011. }
  18012. };
  18013. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18014. names = (names instanceof Array) ? names : [names];
  18015. for (var i in names) {
  18016. if (mesh.name === names[i]) {
  18017. hierarchyIds.push(mesh.id);
  18018. return true;
  18019. }
  18020. }
  18021. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18022. hierarchyIds.push(mesh.id);
  18023. return true;
  18024. }
  18025. return false;
  18026. };
  18027. var importVertexData = function (parsedVertexData, geometry) {
  18028. var vertexData = new BABYLON.VertexData();
  18029. // positions
  18030. var positions = parsedVertexData.positions;
  18031. if (positions) {
  18032. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18033. }
  18034. // normals
  18035. var normals = parsedVertexData.normals;
  18036. if (normals) {
  18037. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18038. }
  18039. // uvs
  18040. var uvs = parsedVertexData.uvs;
  18041. if (uvs) {
  18042. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18043. }
  18044. // uv2s
  18045. var uv2s = parsedVertexData.uv2s;
  18046. if (uv2s) {
  18047. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18048. }
  18049. // colors
  18050. var colors = parsedVertexData.colors;
  18051. if (colors) {
  18052. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18053. }
  18054. // matricesIndices
  18055. var matricesIndices = parsedVertexData.matricesIndices;
  18056. if (matricesIndices) {
  18057. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18058. }
  18059. // matricesWeights
  18060. var matricesWeights = parsedVertexData.matricesWeights;
  18061. if (matricesWeights) {
  18062. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18063. }
  18064. // indices
  18065. var indices = parsedVertexData.indices;
  18066. if (indices) {
  18067. vertexData.indices = indices;
  18068. }
  18069. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18070. };
  18071. var importGeometry = function (parsedGeometry, mesh) {
  18072. var scene = mesh.getScene();
  18073. // Geometry
  18074. var geometryId = parsedGeometry.geometryId;
  18075. if (geometryId) {
  18076. var geometry = scene.getGeometryByID(geometryId);
  18077. if (geometry) {
  18078. geometry.applyToMesh(mesh);
  18079. }
  18080. } else if (parsedGeometry instanceof ArrayBuffer) {
  18081. var binaryInfo = mesh._binaryInfo;
  18082. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18083. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18084. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18085. }
  18086. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18087. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18088. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18089. }
  18090. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18091. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18092. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18093. }
  18094. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18095. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18096. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18097. }
  18098. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18099. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18100. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18101. }
  18102. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18103. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18105. }
  18106. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18107. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18108. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18109. }
  18110. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18111. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18112. mesh.setIndices(indicesData);
  18113. }
  18114. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18115. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18116. mesh.subMeshes = [];
  18117. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18118. var materialIndex = subMeshesData[(i * 5) + 0];
  18119. var verticesStart = subMeshesData[(i * 5) + 1];
  18120. var verticesCount = subMeshesData[(i * 5) + 2];
  18121. var indexStart = subMeshesData[(i * 5) + 3];
  18122. var indexCount = subMeshesData[(i * 5) + 4];
  18123. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18124. }
  18125. }
  18126. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18127. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18128. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18129. if (parsedGeometry.uvs) {
  18130. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18131. }
  18132. if (parsedGeometry.uvs2) {
  18133. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18134. }
  18135. if (parsedGeometry.colors) {
  18136. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18137. }
  18138. if (parsedGeometry.matricesIndices) {
  18139. if (!parsedGeometry.matricesIndices._isExpanded) {
  18140. var floatIndices = [];
  18141. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18142. var matricesIndex = parsedGeometry.matricesIndices[i];
  18143. floatIndices.push(matricesIndex & 0x000000FF);
  18144. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18145. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18146. floatIndices.push(matricesIndex >> 24);
  18147. }
  18148. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18149. } else {
  18150. delete parsedGeometry.matricesIndices._isExpanded;
  18151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18152. }
  18153. }
  18154. if (parsedGeometry.matricesWeights) {
  18155. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18156. }
  18157. mesh.setIndices(parsedGeometry.indices);
  18158. // SubMeshes
  18159. if (parsedGeometry.subMeshes) {
  18160. mesh.subMeshes = [];
  18161. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18162. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18163. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18164. }
  18165. }
  18166. }
  18167. // Flat shading
  18168. if (mesh._shouldGenerateFlatShading) {
  18169. mesh.convertToFlatShadedMesh();
  18170. delete mesh._shouldGenerateFlatShading;
  18171. }
  18172. // Update
  18173. mesh.computeWorldMatrix(true);
  18174. // Octree
  18175. if (scene._selectionOctree) {
  18176. scene._selectionOctree.addMesh(mesh);
  18177. }
  18178. };
  18179. BABYLON.SceneLoader.RegisterPlugin({
  18180. extensions: ".babylon",
  18181. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18182. var parsedData = JSON.parse(data);
  18183. var loadedSkeletonsIds = [];
  18184. var loadedMaterialsIds = [];
  18185. var hierarchyIds = [];
  18186. for (var index = 0; index < parsedData.meshes.length; index++) {
  18187. var parsedMesh = parsedData.meshes[index];
  18188. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18189. if (meshesNames instanceof Array) {
  18190. // Remove found mesh name from list.
  18191. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18192. }
  18193. // Material ?
  18194. if (parsedMesh.materialId) {
  18195. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18196. if (!materialFound) {
  18197. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18198. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18199. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18200. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18201. var subMatId = parsedMultiMaterial.materials[matIndex];
  18202. loadedMaterialsIds.push(subMatId);
  18203. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18204. }
  18205. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18206. parseMultiMaterial(parsedMultiMaterial, scene);
  18207. materialFound = true;
  18208. break;
  18209. }
  18210. }
  18211. }
  18212. if (!materialFound) {
  18213. loadedMaterialsIds.push(parsedMesh.materialId);
  18214. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18215. }
  18216. }
  18217. // Skeleton ?
  18218. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18219. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18220. if (!skeletonAlreadyLoaded) {
  18221. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18222. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18223. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18224. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18225. loadedSkeletonsIds.push(parsedSkeleton.id);
  18226. }
  18227. }
  18228. }
  18229. }
  18230. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18231. meshes.push(mesh);
  18232. }
  18233. }
  18234. for (index = 0; index < scene.meshes.length; index++) {
  18235. var currentMesh = scene.meshes[index];
  18236. if (currentMesh._waitingParentId) {
  18237. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18238. currentMesh._waitingParentId = undefined;
  18239. }
  18240. }
  18241. // Particles
  18242. if (parsedData.particleSystems) {
  18243. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18244. var parsedParticleSystem = parsedData.particleSystems[index];
  18245. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18246. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18247. }
  18248. }
  18249. }
  18250. return true;
  18251. },
  18252. load: function (scene, data, rootUrl) {
  18253. var parsedData = JSON.parse(data);
  18254. // Scene
  18255. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18256. scene.autoClear = parsedData.autoClear;
  18257. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18258. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18259. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18260. // Fog
  18261. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18262. scene.fogMode = parsedData.fogMode;
  18263. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18264. scene.fogStart = parsedData.fogStart;
  18265. scene.fogEnd = parsedData.fogEnd;
  18266. scene.fogDensity = parsedData.fogDensity;
  18267. }
  18268. for (var index = 0; index < parsedData.lights.length; index++) {
  18269. var parsedLight = parsedData.lights[index];
  18270. parseLight(parsedLight, scene);
  18271. }
  18272. // Materials
  18273. if (parsedData.materials) {
  18274. for (index = 0; index < parsedData.materials.length; index++) {
  18275. var parsedMaterial = parsedData.materials[index];
  18276. parseMaterial(parsedMaterial, scene, rootUrl);
  18277. }
  18278. }
  18279. if (parsedData.multiMaterials) {
  18280. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18281. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18282. parseMultiMaterial(parsedMultiMaterial, scene);
  18283. }
  18284. }
  18285. // Skeletons
  18286. if (parsedData.skeletons) {
  18287. for (index = 0; index < parsedData.skeletons.length; index++) {
  18288. var parsedSkeleton = parsedData.skeletons[index];
  18289. parseSkeleton(parsedSkeleton, scene);
  18290. }
  18291. }
  18292. // Geometries
  18293. var geometries = parsedData.geometries;
  18294. if (geometries) {
  18295. // Boxes
  18296. var boxes = geometries.boxes;
  18297. if (boxes) {
  18298. for (index = 0; index < boxes.length; index++) {
  18299. var parsedBox = boxes[index];
  18300. parseBox(parsedBox, scene);
  18301. }
  18302. }
  18303. // Spheres
  18304. var spheres = geometries.spheres;
  18305. if (spheres) {
  18306. for (index = 0; index < spheres.length; index++) {
  18307. var parsedSphere = spheres[index];
  18308. parseSphere(parsedSphere, scene);
  18309. }
  18310. }
  18311. // Cylinders
  18312. var cylinders = geometries.cylinders;
  18313. if (cylinders) {
  18314. for (index = 0; index < cylinders.length; index++) {
  18315. var parsedCylinder = cylinders[index];
  18316. parseCylinder(parsedCylinder, scene);
  18317. }
  18318. }
  18319. // Toruses
  18320. var toruses = geometries.toruses;
  18321. if (toruses) {
  18322. for (index = 0; index < toruses.length; index++) {
  18323. var parsedTorus = toruses[index];
  18324. parseTorus(parsedTorus, scene);
  18325. }
  18326. }
  18327. // Grounds
  18328. var grounds = geometries.grounds;
  18329. if (grounds) {
  18330. for (index = 0; index < grounds.length; index++) {
  18331. var parsedGround = grounds[index];
  18332. parseGround(parsedGround, scene);
  18333. }
  18334. }
  18335. // Planes
  18336. var planes = geometries.planes;
  18337. if (planes) {
  18338. for (index = 0; index < planes.length; index++) {
  18339. var parsedPlane = planes[index];
  18340. parsePlane(parsedPlane, scene);
  18341. }
  18342. }
  18343. // TorusKnots
  18344. var torusKnots = geometries.torusKnots;
  18345. if (torusKnots) {
  18346. for (index = 0; index < torusKnots.length; index++) {
  18347. var parsedTorusKnot = torusKnots[index];
  18348. parseTorusKnot(parsedTorusKnot, scene);
  18349. }
  18350. }
  18351. // VertexData
  18352. var vertexData = geometries.vertexData;
  18353. if (vertexData) {
  18354. for (index = 0; index < vertexData.length; index++) {
  18355. var parsedVertexData = vertexData[index];
  18356. parseVertexData(parsedVertexData, scene, rootUrl);
  18357. }
  18358. }
  18359. }
  18360. for (index = 0; index < parsedData.meshes.length; index++) {
  18361. var parsedMesh = parsedData.meshes[index];
  18362. parseMesh(parsedMesh, scene, rootUrl);
  18363. }
  18364. for (index = 0; index < parsedData.cameras.length; index++) {
  18365. var parsedCamera = parsedData.cameras[index];
  18366. parseCamera(parsedCamera, scene);
  18367. }
  18368. if (parsedData.activeCameraID) {
  18369. scene.setActiveCameraByID(parsedData.activeCameraID);
  18370. }
  18371. for (index = 0; index < scene.cameras.length; index++) {
  18372. var camera = scene.cameras[index];
  18373. if (camera._waitingParentId) {
  18374. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18375. camera._waitingParentId = undefined;
  18376. }
  18377. }
  18378. for (index = 0; index < scene.lights.length; index++) {
  18379. var light = scene.lights[index];
  18380. if (light._waitingParentId) {
  18381. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18382. light._waitingParentId = undefined;
  18383. }
  18384. }
  18385. for (index = 0; index < scene.meshes.length; index++) {
  18386. var mesh = scene.meshes[index];
  18387. if (mesh._waitingParentId) {
  18388. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18389. mesh._waitingParentId = undefined;
  18390. }
  18391. if (mesh._waitingActions) {
  18392. parseActions(mesh._waitingActions, mesh, scene);
  18393. mesh._waitingActions = undefined;
  18394. }
  18395. }
  18396. // Particles Systems
  18397. if (parsedData.particleSystems) {
  18398. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18399. var parsedParticleSystem = parsedData.particleSystems[index];
  18400. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18401. }
  18402. }
  18403. // Lens flares
  18404. if (parsedData.lensFlareSystems) {
  18405. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18406. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18407. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18408. }
  18409. }
  18410. // Shadows
  18411. if (parsedData.shadowGenerators) {
  18412. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18413. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18414. parseShadowGenerator(parsedShadowGenerator, scene);
  18415. }
  18416. }
  18417. // Actions (scene)
  18418. if (parsedData.actions) {
  18419. parseActions(parsedData.actions, scene, scene);
  18420. }
  18421. // Finish
  18422. return true;
  18423. }
  18424. });
  18425. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18426. var Internals = BABYLON.Internals;
  18427. })(BABYLON || (BABYLON = {}));
  18428. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18429. var BABYLON;
  18430. (function (BABYLON) {
  18431. // Unique ID when we import meshes from Babylon to CSG
  18432. var currentCSGMeshId = 0;
  18433. // # class Vertex
  18434. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18435. // one to provide additional features like texture coordinates and vertex
  18436. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18437. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18438. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18439. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18440. // is not used anywhere else.
  18441. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18442. var Vertex = (function () {
  18443. function Vertex(pos, normal, uv) {
  18444. this.pos = pos;
  18445. this.normal = normal;
  18446. this.uv = uv;
  18447. }
  18448. Vertex.prototype.clone = function () {
  18449. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18450. };
  18451. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18452. // orientation of a polygon is flipped.
  18453. Vertex.prototype.flip = function () {
  18454. this.normal = this.normal.scale(-1);
  18455. };
  18456. // Create a new vertex between this vertex and `other` by linearly
  18457. // interpolating all properties using a parameter of `t`. Subclasses should
  18458. // override this to interpolate additional properties.
  18459. Vertex.prototype.interpolate = function (other, t) {
  18460. 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));
  18461. };
  18462. return Vertex;
  18463. })();
  18464. // # class Plane
  18465. // Represents a plane in 3D space.
  18466. var Plane = (function () {
  18467. function Plane(normal, w) {
  18468. this.normal = normal;
  18469. this.w = w;
  18470. }
  18471. Plane.FromPoints = function (a, b, c) {
  18472. var v0 = c.subtract(a);
  18473. var v1 = b.subtract(a);
  18474. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18475. return null;
  18476. }
  18477. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18478. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18479. };
  18480. Plane.prototype.clone = function () {
  18481. return new Plane(this.normal.clone(), this.w);
  18482. };
  18483. Plane.prototype.flip = function () {
  18484. this.normal.scaleInPlace(-1);
  18485. this.w = -this.w;
  18486. };
  18487. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18488. // fragments in the appropriate lists. Coplanar polygons go into either
  18489. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18490. // respect to this plane. Polygons in front or in back of this plane go into
  18491. // either `front` or `back`.
  18492. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18493. var COPLANAR = 0;
  18494. var FRONT = 1;
  18495. var BACK = 2;
  18496. var SPANNING = 3;
  18497. // Classify each point as well as the entire polygon into one of the above
  18498. // four classes.
  18499. var polygonType = 0;
  18500. var types = [];
  18501. for (var i = 0; i < polygon.vertices.length; i++) {
  18502. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18503. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18504. polygonType |= type;
  18505. types.push(type);
  18506. }
  18507. switch (polygonType) {
  18508. case COPLANAR:
  18509. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18510. break;
  18511. case FRONT:
  18512. front.push(polygon);
  18513. break;
  18514. case BACK:
  18515. back.push(polygon);
  18516. break;
  18517. case SPANNING:
  18518. var f = [], b = [];
  18519. for (i = 0; i < polygon.vertices.length; i++) {
  18520. var j = (i + 1) % polygon.vertices.length;
  18521. var ti = types[i], tj = types[j];
  18522. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18523. if (ti != BACK)
  18524. f.push(vi);
  18525. if (ti != FRONT)
  18526. b.push(ti != BACK ? vi.clone() : vi);
  18527. if ((ti | tj) == SPANNING) {
  18528. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18529. var v = vi.interpolate(vj, t);
  18530. f.push(v);
  18531. b.push(v.clone());
  18532. }
  18533. }
  18534. if (f.length >= 3) {
  18535. var poly = new Polygon(f, polygon.shared);
  18536. if (poly.plane)
  18537. front.push(poly);
  18538. }
  18539. if (b.length >= 3) {
  18540. poly = new Polygon(b, polygon.shared);
  18541. if (poly.plane)
  18542. back.push(poly);
  18543. }
  18544. break;
  18545. }
  18546. };
  18547. Plane.EPSILON = 1e-5;
  18548. return Plane;
  18549. })();
  18550. // # class Polygon
  18551. // Represents a convex polygon. The vertices used to initialize a polygon must
  18552. // be coplanar and form a convex loop.
  18553. //
  18554. // Each convex polygon has a `shared` property, which is shared between all
  18555. // polygons that are clones of each other or were split from the same polygon.
  18556. // This can be used to define per-polygon properties (such as surface color).
  18557. var Polygon = (function () {
  18558. function Polygon(vertices, shared) {
  18559. this.vertices = vertices;
  18560. this.shared = shared;
  18561. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18562. }
  18563. Polygon.prototype.clone = function () {
  18564. var vertices = this.vertices.map(function (v) {
  18565. return v.clone();
  18566. });
  18567. return new Polygon(vertices, this.shared);
  18568. };
  18569. Polygon.prototype.flip = function () {
  18570. this.vertices.reverse().map(function (v) {
  18571. v.flip();
  18572. });
  18573. this.plane.flip();
  18574. };
  18575. return Polygon;
  18576. })();
  18577. // # class Node
  18578. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18579. // by picking a polygon to split along. That polygon (and all other coplanar
  18580. // polygons) are added directly to that node and the other polygons are added to
  18581. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18582. // no distinction between internal and leaf nodes.
  18583. var Node = (function () {
  18584. function Node(polygons) {
  18585. this.plane = null;
  18586. this.front = null;
  18587. this.back = null;
  18588. this.polygons = [];
  18589. if (polygons) {
  18590. this.build(polygons);
  18591. }
  18592. }
  18593. Node.prototype.clone = function () {
  18594. var node = new Node();
  18595. node.plane = this.plane && this.plane.clone();
  18596. node.front = this.front && this.front.clone();
  18597. node.back = this.back && this.back.clone();
  18598. node.polygons = this.polygons.map(function (p) {
  18599. return p.clone();
  18600. });
  18601. return node;
  18602. };
  18603. // Convert solid space to empty space and empty space to solid space.
  18604. Node.prototype.invert = function () {
  18605. for (var i = 0; i < this.polygons.length; i++) {
  18606. this.polygons[i].flip();
  18607. }
  18608. if (this.plane) {
  18609. this.plane.flip();
  18610. }
  18611. if (this.front) {
  18612. this.front.invert();
  18613. }
  18614. if (this.back) {
  18615. this.back.invert();
  18616. }
  18617. var temp = this.front;
  18618. this.front = this.back;
  18619. this.back = temp;
  18620. };
  18621. // Recursively remove all polygons in `polygons` that are inside this BSP
  18622. // tree.
  18623. Node.prototype.clipPolygons = function (polygons) {
  18624. if (!this.plane)
  18625. return polygons.slice();
  18626. var front = [], back = [];
  18627. for (var i = 0; i < polygons.length; i++) {
  18628. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18629. }
  18630. if (this.front) {
  18631. front = this.front.clipPolygons(front);
  18632. }
  18633. if (this.back) {
  18634. back = this.back.clipPolygons(back);
  18635. } else {
  18636. back = [];
  18637. }
  18638. return front.concat(back);
  18639. };
  18640. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18641. // `bsp`.
  18642. Node.prototype.clipTo = function (bsp) {
  18643. this.polygons = bsp.clipPolygons(this.polygons);
  18644. if (this.front)
  18645. this.front.clipTo(bsp);
  18646. if (this.back)
  18647. this.back.clipTo(bsp);
  18648. };
  18649. // Return a list of all polygons in this BSP tree.
  18650. Node.prototype.allPolygons = function () {
  18651. var polygons = this.polygons.slice();
  18652. if (this.front)
  18653. polygons = polygons.concat(this.front.allPolygons());
  18654. if (this.back)
  18655. polygons = polygons.concat(this.back.allPolygons());
  18656. return polygons;
  18657. };
  18658. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18659. // new polygons are filtered down to the bottom of the tree and become new
  18660. // nodes there. Each set of polygons is partitioned using the first polygon
  18661. // (no heuristic is used to pick a good split).
  18662. Node.prototype.build = function (polygons) {
  18663. if (!polygons.length)
  18664. return;
  18665. if (!this.plane)
  18666. this.plane = polygons[0].plane.clone();
  18667. var front = [], back = [];
  18668. for (var i = 0; i < polygons.length; i++) {
  18669. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18670. }
  18671. if (front.length) {
  18672. if (!this.front)
  18673. this.front = new Node();
  18674. this.front.build(front);
  18675. }
  18676. if (back.length) {
  18677. if (!this.back)
  18678. this.back = new Node();
  18679. this.back.build(back);
  18680. }
  18681. };
  18682. return Node;
  18683. })();
  18684. var CSG = (function () {
  18685. function CSG() {
  18686. this.polygons = new Array();
  18687. }
  18688. // Convert BABYLON.Mesh to BABYLON.CSG
  18689. CSG.FromMesh = function (mesh) {
  18690. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18691. if (mesh instanceof BABYLON.Mesh) {
  18692. mesh.computeWorldMatrix(true);
  18693. var matrix = mesh.getWorldMatrix();
  18694. var meshPosition = mesh.position.clone();
  18695. var meshRotation = mesh.rotation.clone();
  18696. var meshScaling = mesh.scaling.clone();
  18697. } else {
  18698. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18699. }
  18700. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18701. var subMeshes = mesh.subMeshes;
  18702. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18703. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18704. vertices = [];
  18705. for (var j = 0; j < 3; j++) {
  18706. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18707. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18708. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18709. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18710. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18711. vertex = new Vertex(position, normal, uv);
  18712. vertices.push(vertex);
  18713. }
  18714. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18715. // To handle the case of degenerated triangle
  18716. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18717. if (polygon.plane)
  18718. polygons.push(polygon);
  18719. }
  18720. }
  18721. var csg = CSG.FromPolygons(polygons);
  18722. csg.matrix = matrix;
  18723. csg.position = meshPosition;
  18724. csg.rotation = meshRotation;
  18725. csg.scaling = meshScaling;
  18726. currentCSGMeshId++;
  18727. return csg;
  18728. };
  18729. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18730. CSG.FromPolygons = function (polygons) {
  18731. var csg = new BABYLON.CSG();
  18732. csg.polygons = polygons;
  18733. return csg;
  18734. };
  18735. CSG.prototype.clone = function () {
  18736. var csg = new BABYLON.CSG();
  18737. csg.polygons = this.polygons.map(function (p) {
  18738. return p.clone();
  18739. });
  18740. csg.copyTransformAttributes(this);
  18741. return csg;
  18742. };
  18743. CSG.prototype.toPolygons = function () {
  18744. return this.polygons;
  18745. };
  18746. CSG.prototype.union = function (csg) {
  18747. var a = new Node(this.clone().polygons);
  18748. var b = new Node(csg.clone().polygons);
  18749. a.clipTo(b);
  18750. b.clipTo(a);
  18751. b.invert();
  18752. b.clipTo(a);
  18753. b.invert();
  18754. a.build(b.allPolygons());
  18755. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18756. };
  18757. CSG.prototype.unionInPlace = function (csg) {
  18758. var a = new Node(this.polygons);
  18759. var b = new Node(csg.polygons);
  18760. a.clipTo(b);
  18761. b.clipTo(a);
  18762. b.invert();
  18763. b.clipTo(a);
  18764. b.invert();
  18765. a.build(b.allPolygons());
  18766. this.polygons = a.allPolygons();
  18767. };
  18768. CSG.prototype.subtract = function (csg) {
  18769. var a = new Node(this.clone().polygons);
  18770. var b = new Node(csg.clone().polygons);
  18771. a.invert();
  18772. a.clipTo(b);
  18773. b.clipTo(a);
  18774. b.invert();
  18775. b.clipTo(a);
  18776. b.invert();
  18777. a.build(b.allPolygons());
  18778. a.invert();
  18779. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18780. };
  18781. CSG.prototype.subtractInPlace = function (csg) {
  18782. var a = new Node(this.polygons);
  18783. var b = new Node(csg.polygons);
  18784. a.invert();
  18785. a.clipTo(b);
  18786. b.clipTo(a);
  18787. b.invert();
  18788. b.clipTo(a);
  18789. b.invert();
  18790. a.build(b.allPolygons());
  18791. a.invert();
  18792. this.polygons = a.allPolygons();
  18793. };
  18794. CSG.prototype.intersect = function (csg) {
  18795. var a = new Node(this.clone().polygons);
  18796. var b = new Node(csg.clone().polygons);
  18797. a.invert();
  18798. b.clipTo(a);
  18799. b.invert();
  18800. a.clipTo(b);
  18801. b.clipTo(a);
  18802. a.build(b.allPolygons());
  18803. a.invert();
  18804. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18805. };
  18806. CSG.prototype.intersectInPlace = function (csg) {
  18807. var a = new Node(this.polygons);
  18808. var b = new Node(csg.polygons);
  18809. a.invert();
  18810. b.clipTo(a);
  18811. b.invert();
  18812. a.clipTo(b);
  18813. b.clipTo(a);
  18814. a.build(b.allPolygons());
  18815. a.invert();
  18816. this.polygons = a.allPolygons();
  18817. };
  18818. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18819. // not modified.
  18820. CSG.prototype.inverse = function () {
  18821. var csg = this.clone();
  18822. csg.inverseInPlace();
  18823. return csg;
  18824. };
  18825. CSG.prototype.inverseInPlace = function () {
  18826. this.polygons.map(function (p) {
  18827. p.flip();
  18828. });
  18829. };
  18830. // This is used to keep meshes transformations so they can be restored
  18831. // when we build back a Babylon Mesh
  18832. // NB : All CSG operations are performed in world coordinates
  18833. CSG.prototype.copyTransformAttributes = function (csg) {
  18834. this.matrix = csg.matrix;
  18835. this.position = csg.position;
  18836. this.rotation = csg.rotation;
  18837. this.scaling = csg.scaling;
  18838. return this;
  18839. };
  18840. // Build Raw mesh from CSG
  18841. // Coordinates here are in world space
  18842. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18843. var matrix = this.matrix.clone();
  18844. matrix.invert();
  18845. 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;
  18846. if (keepSubMeshes) {
  18847. // Sort Polygons, since subMeshes are indices range
  18848. polygons.sort(function (a, b) {
  18849. if (a.shared.meshId === b.shared.meshId) {
  18850. return a.shared.subMeshId - b.shared.subMeshId;
  18851. } else {
  18852. return a.shared.meshId - b.shared.meshId;
  18853. }
  18854. });
  18855. }
  18856. for (var i = 0, il = polygons.length; i < il; i++) {
  18857. polygon = polygons[i];
  18858. // Building SubMeshes
  18859. if (!subMesh_dict[polygon.shared.meshId]) {
  18860. subMesh_dict[polygon.shared.meshId] = {};
  18861. }
  18862. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18863. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18864. indexStart: +Infinity,
  18865. indexEnd: -Infinity,
  18866. materialIndex: polygon.shared.materialIndex
  18867. };
  18868. }
  18869. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18870. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18871. polygonIndices[0] = 0;
  18872. polygonIndices[1] = j - 1;
  18873. polygonIndices[2] = j;
  18874. for (var k = 0; k < 3; k++) {
  18875. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18876. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18877. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18878. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18879. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18880. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18881. // Check if 2 points can be merged
  18882. 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)) {
  18883. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18884. uvs.push(uv.x, uv.y);
  18885. normals.push(normal.x, normal.y, normal.z);
  18886. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18887. }
  18888. indices.push(vertex_idx);
  18889. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18890. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18891. currentIndex++;
  18892. }
  18893. }
  18894. }
  18895. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18896. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18897. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18898. mesh.setIndices(indices);
  18899. if (keepSubMeshes) {
  18900. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18901. var materialIndexOffset = 0, materialMaxIndex;
  18902. mesh.subMeshes.length = 0;
  18903. for (var m in subMesh_dict) {
  18904. materialMaxIndex = -1;
  18905. for (var sm in subMesh_dict[m]) {
  18906. subMesh_obj = subMesh_dict[m][sm];
  18907. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18908. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18909. }
  18910. materialIndexOffset += ++materialMaxIndex;
  18911. }
  18912. }
  18913. return mesh;
  18914. };
  18915. // Build Mesh from CSG taking material and transforms into account
  18916. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18917. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18918. mesh.material = material;
  18919. mesh.position.copyFrom(this.position);
  18920. mesh.rotation.copyFrom(this.rotation);
  18921. mesh.scaling.copyFrom(this.scaling);
  18922. mesh.computeWorldMatrix(true);
  18923. return mesh;
  18924. };
  18925. return CSG;
  18926. })();
  18927. BABYLON.CSG = CSG;
  18928. })(BABYLON || (BABYLON = {}));
  18929. //# sourceMappingURL=babylon.csg.js.map
  18930. var BABYLON;
  18931. (function (BABYLON) {
  18932. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18933. __extends(OculusDistortionCorrectionPostProcess, _super);
  18934. //ANY
  18935. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18936. var _this = this;
  18937. _super.call(this, name, "oculusDistortionCorrection", [
  18938. 'LensCenter',
  18939. 'Scale',
  18940. 'ScaleIn',
  18941. 'HmdWarpParam'
  18942. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18943. this._isRightEye = isRightEye;
  18944. this._distortionFactors = cameraSettings.DistortionK;
  18945. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18946. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18947. this.onSizeChanged = function () {
  18948. _this.aspectRatio = _this.width * .5 / _this.height;
  18949. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18950. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18951. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18952. };
  18953. this.onApply = function (effect) {
  18954. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18955. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18956. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18957. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18958. };
  18959. }
  18960. return OculusDistortionCorrectionPostProcess;
  18961. })(BABYLON.PostProcess);
  18962. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18963. })(BABYLON || (BABYLON = {}));
  18964. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18965. // Mainly based on these 2 articles :
  18966. // 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
  18967. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18968. var BABYLON;
  18969. (function (BABYLON) {
  18970. (function (JoystickAxis) {
  18971. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18972. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18973. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18974. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18975. var JoystickAxis = BABYLON.JoystickAxis;
  18976. var VirtualJoystick = (function () {
  18977. function VirtualJoystick(leftJoystick) {
  18978. var _this = this;
  18979. if (leftJoystick) {
  18980. this._leftJoystick = true;
  18981. } else {
  18982. this._leftJoystick = false;
  18983. }
  18984. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18985. VirtualJoystick._globalJoystickIndex++;
  18986. // By default left & right arrow keys are moving the X
  18987. // and up & down keys are moving the Y
  18988. this._axisTargetedByLeftAndRight = 0 /* X */;
  18989. this._axisTargetedByUpAndDown = 1 /* Y */;
  18990. this.reverseLeftRight = false;
  18991. this.reverseUpDown = false;
  18992. // collections of pointers
  18993. this._touches = new BABYLON.VirtualJoystick.Collection();
  18994. this.deltaPosition = BABYLON.Vector3.Zero();
  18995. this._joystickSensibility = 25;
  18996. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18997. this._rotationSpeed = 25;
  18998. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18999. this._rotateOnAxisRelativeToMesh = false;
  19000. // injecting a canvas element on top of the canvas 3D game
  19001. if (!VirtualJoystick.vjCanvas) {
  19002. window.addEventListener("resize", function () {
  19003. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19004. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19005. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19006. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19007. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19008. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19009. }, false);
  19010. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19011. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19012. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19013. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19014. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19015. VirtualJoystick.vjCanvas.style.width = "100%";
  19016. VirtualJoystick.vjCanvas.style.height = "100%";
  19017. VirtualJoystick.vjCanvas.style.position = "absolute";
  19018. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19019. VirtualJoystick.vjCanvas.style.top = "0px";
  19020. VirtualJoystick.vjCanvas.style.left = "0px";
  19021. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19022. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19023. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19024. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19025. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19026. document.body.appendChild(VirtualJoystick.vjCanvas);
  19027. }
  19028. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19029. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19030. this.pressed = false;
  19031. // default joystick color
  19032. this._joystickColor = "cyan";
  19033. this._joystickPointerID = -1;
  19034. // current joystick position
  19035. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19036. // origin joystick position
  19037. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19038. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19039. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19040. _this._onPointerDown(evt);
  19041. }, false);
  19042. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19043. _this._onPointerMove(evt);
  19044. }, false);
  19045. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19046. _this._onPointerUp(evt);
  19047. }, false);
  19048. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19049. _this._onPointerUp(evt);
  19050. }, false);
  19051. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19052. evt.preventDefault(); // Disables system menu
  19053. }, false);
  19054. requestAnimationFrame(function () {
  19055. _this._drawVirtualJoystick();
  19056. });
  19057. }
  19058. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19059. this._joystickSensibility = newJoystickSensibility;
  19060. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19061. };
  19062. VirtualJoystick.prototype._onPointerDown = function (e) {
  19063. var positionOnScreenCondition;
  19064. e.preventDefault();
  19065. if (this._leftJoystick === true) {
  19066. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19067. } else {
  19068. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19069. }
  19070. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19071. // First contact will be dedicated to the virtual joystick
  19072. this._joystickPointerID = e.pointerId;
  19073. this._joystickPointerStartPos.x = e.clientX;
  19074. this._joystickPointerStartPos.y = e.clientY;
  19075. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19076. this._deltaJoystickVector.x = 0;
  19077. this._deltaJoystickVector.y = 0;
  19078. this.pressed = true;
  19079. this._touches.add(e.pointerId.toString(), e);
  19080. } else {
  19081. // You can only trigger the action buttons with a joystick declared
  19082. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19083. this._action();
  19084. this._touches.add(e.pointerId.toString(), e);
  19085. }
  19086. }
  19087. };
  19088. VirtualJoystick.prototype._onPointerMove = function (e) {
  19089. // If the current pointer is the one associated to the joystick (first touch contact)
  19090. if (this._joystickPointerID == e.pointerId) {
  19091. this._joystickPointerPos.x = e.clientX;
  19092. this._joystickPointerPos.y = e.clientY;
  19093. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19094. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19095. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19096. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19097. switch (this._axisTargetedByLeftAndRight) {
  19098. case 0 /* X */:
  19099. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19100. break;
  19101. case 1 /* Y */:
  19102. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19103. break;
  19104. case 2 /* Z */:
  19105. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19106. break;
  19107. }
  19108. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19109. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19110. switch (this._axisTargetedByUpAndDown) {
  19111. case 0 /* X */:
  19112. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19113. break;
  19114. case 1 /* Y */:
  19115. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19116. break;
  19117. case 2 /* Z */:
  19118. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19119. break;
  19120. }
  19121. } else {
  19122. if (this._touches.item(e.pointerId.toString())) {
  19123. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19124. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19125. }
  19126. }
  19127. };
  19128. VirtualJoystick.prototype._onPointerUp = function (e) {
  19129. this._clearCanvas();
  19130. if (this._joystickPointerID == e.pointerId) {
  19131. this._joystickPointerID = -1;
  19132. this.pressed = false;
  19133. }
  19134. this._deltaJoystickVector.x = 0;
  19135. this._deltaJoystickVector.y = 0;
  19136. this._touches.remove(e.pointerId.toString());
  19137. };
  19138. /**
  19139. * Change the color of the virtual joystick
  19140. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19141. */
  19142. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19143. this._joystickColor = newColor;
  19144. };
  19145. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19146. this._action = action;
  19147. };
  19148. // Define which axis you'd like to control for left & right
  19149. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19150. switch (axis) {
  19151. case 0 /* X */:
  19152. case 1 /* Y */:
  19153. case 2 /* Z */:
  19154. this._axisTargetedByLeftAndRight = axis;
  19155. break;
  19156. default:
  19157. this._axisTargetedByLeftAndRight = 0 /* X */;
  19158. break;
  19159. }
  19160. };
  19161. // Define which axis you'd like to control for up & down
  19162. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19163. switch (axis) {
  19164. case 0 /* X */:
  19165. case 1 /* Y */:
  19166. case 2 /* Z */:
  19167. this._axisTargetedByUpAndDown = axis;
  19168. break;
  19169. default:
  19170. this._axisTargetedByUpAndDown = 1 /* Y */;
  19171. break;
  19172. }
  19173. };
  19174. VirtualJoystick.prototype._clearCanvas = function () {
  19175. if (this._leftJoystick) {
  19176. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19177. } else {
  19178. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19179. }
  19180. };
  19181. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19182. var _this = this;
  19183. if (this.pressed) {
  19184. this._clearCanvas();
  19185. this._touches.forEach(function (touch) {
  19186. if (touch.pointerId === _this._joystickPointerID) {
  19187. VirtualJoystick.vjCanvasContext.beginPath();
  19188. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19189. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19190. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19191. VirtualJoystick.vjCanvasContext.stroke();
  19192. VirtualJoystick.vjCanvasContext.beginPath();
  19193. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19194. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19195. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19196. VirtualJoystick.vjCanvasContext.stroke();
  19197. VirtualJoystick.vjCanvasContext.beginPath();
  19198. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19199. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19200. VirtualJoystick.vjCanvasContext.stroke();
  19201. } else {
  19202. VirtualJoystick.vjCanvasContext.beginPath();
  19203. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19204. VirtualJoystick.vjCanvasContext.beginPath();
  19205. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19206. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19207. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19208. VirtualJoystick.vjCanvasContext.stroke();
  19209. }
  19210. ;
  19211. });
  19212. }
  19213. requestAnimationFrame(function () {
  19214. _this._drawVirtualJoystick();
  19215. });
  19216. };
  19217. VirtualJoystick.prototype.releaseCanvas = function () {
  19218. if (VirtualJoystick.vjCanvas) {
  19219. document.body.removeChild(VirtualJoystick.vjCanvas);
  19220. VirtualJoystick.vjCanvas = null;
  19221. }
  19222. };
  19223. VirtualJoystick._globalJoystickIndex = 0;
  19224. return VirtualJoystick;
  19225. })();
  19226. BABYLON.VirtualJoystick = VirtualJoystick;
  19227. })(BABYLON || (BABYLON = {}));
  19228. var BABYLON;
  19229. (function (BABYLON) {
  19230. (function (VirtualJoystick) {
  19231. var Collection = (function () {
  19232. function Collection() {
  19233. this._count = 0;
  19234. this._collection = new Array();
  19235. }
  19236. Collection.prototype.Count = function () {
  19237. return this._count;
  19238. };
  19239. Collection.prototype.add = function (key, item) {
  19240. if (this._collection[key] != undefined) {
  19241. return undefined;
  19242. }
  19243. this._collection[key] = item;
  19244. return ++this._count;
  19245. };
  19246. Collection.prototype.remove = function (key) {
  19247. if (this._collection[key] == undefined) {
  19248. return undefined;
  19249. }
  19250. delete this._collection[key];
  19251. return --this._count;
  19252. };
  19253. Collection.prototype.item = function (key) {
  19254. return this._collection[key];
  19255. };
  19256. Collection.prototype.forEach = function (block) {
  19257. var key;
  19258. for (key in this._collection) {
  19259. if (this._collection.hasOwnProperty(key)) {
  19260. block(this._collection[key]);
  19261. }
  19262. }
  19263. };
  19264. return Collection;
  19265. })();
  19266. VirtualJoystick.Collection = Collection;
  19267. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19268. var VirtualJoystick = BABYLON.VirtualJoystick;
  19269. })(BABYLON || (BABYLON = {}));
  19270. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19271. var BABYLON;
  19272. (function (BABYLON) {
  19273. var OculusRiftDevKit2013_Metric = {
  19274. HResolution: 1280,
  19275. VResolution: 800,
  19276. HScreenSize: 0.149759993,
  19277. VScreenSize: 0.0935999975,
  19278. VScreenCenter: 0.0467999987,
  19279. EyeToScreenDistance: 0.0410000011,
  19280. LensSeparationDistance: 0.0635000020,
  19281. InterpupillaryDistance: 0.0640000030,
  19282. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19283. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19284. PostProcessScaleFactor: 1.714605507808412,
  19285. LensCenterOffset: 0.151976421
  19286. };
  19287. var _OculusInnerCamera = (function (_super) {
  19288. __extends(_OculusInnerCamera, _super);
  19289. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19290. _super.call(this, name, position, scene);
  19291. this._workMatrix = new BABYLON.Matrix();
  19292. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19293. // Constants
  19294. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19295. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19296. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19297. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19298. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19299. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19300. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19301. // Postprocess
  19302. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19303. }
  19304. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19305. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19306. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19307. return this._projectionMatrix;
  19308. };
  19309. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19310. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19311. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19312. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19313. // Computing target and final matrix
  19314. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19315. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19316. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19317. return this._viewMatrix;
  19318. };
  19319. return _OculusInnerCamera;
  19320. })(BABYLON.FreeCamera);
  19321. var OculusCamera = (function (_super) {
  19322. __extends(OculusCamera, _super);
  19323. function OculusCamera(name, position, scene) {
  19324. _super.call(this, name, position, scene);
  19325. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19326. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19327. this.subCameras.push(this._leftCamera);
  19328. this.subCameras.push(this._rightCamera);
  19329. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19330. }
  19331. OculusCamera.prototype._update = function () {
  19332. this._leftCamera.position.copyFrom(this.position);
  19333. this._rightCamera.position.copyFrom(this.position);
  19334. this._updateCamera(this._leftCamera);
  19335. this._updateCamera(this._rightCamera);
  19336. _super.prototype._update.call(this);
  19337. };
  19338. OculusCamera.prototype._updateCamera = function (camera) {
  19339. camera.minZ = this.minZ;
  19340. camera.maxZ = this.maxZ;
  19341. camera.rotation.x = this.rotation.x;
  19342. camera.rotation.y = this.rotation.y;
  19343. camera.rotation.z = this.rotation.z;
  19344. };
  19345. // Oculus events
  19346. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19347. var yaw = evt.alpha / 180 * Math.PI;
  19348. var pitch = evt.beta / 180 * Math.PI;
  19349. var roll = evt.gamma / 180 * Math.PI;
  19350. if (!this._offsetOrientation) {
  19351. this._offsetOrientation = {
  19352. yaw: yaw,
  19353. pitch: pitch,
  19354. roll: roll
  19355. };
  19356. return;
  19357. } else {
  19358. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19359. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19360. this.rotation.z += this._offsetOrientation.roll - roll;
  19361. this._offsetOrientation.yaw = yaw;
  19362. this._offsetOrientation.pitch = pitch;
  19363. this._offsetOrientation.roll = roll;
  19364. }
  19365. };
  19366. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19367. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19368. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19369. };
  19370. OculusCamera.prototype.detachControl = function (element) {
  19371. _super.prototype.detachControl.call(this, element);
  19372. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19373. };
  19374. return OculusCamera;
  19375. })(BABYLON.FreeCamera);
  19376. BABYLON.OculusCamera = OculusCamera;
  19377. })(BABYLON || (BABYLON = {}));
  19378. //# sourceMappingURL=babylon.oculusCamera.js.map
  19379. var BABYLON;
  19380. (function (BABYLON) {
  19381. var OculusRiftDevKit2013_Metric = {
  19382. HResolution: 1280,
  19383. VResolution: 800,
  19384. HScreenSize: 0.149759993,
  19385. VScreenSize: 0.0935999975,
  19386. VScreenCenter: 0.0467999987,
  19387. EyeToScreenDistance: 0.0410000011,
  19388. LensSeparationDistance: 0.0635000020,
  19389. InterpupillaryDistance: 0.0640000030,
  19390. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19391. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19392. PostProcessScaleFactor: 1.714605507808412,
  19393. LensCenterOffset: 0.151976421
  19394. };
  19395. var _OculusInnerGamepadCamera = (function (_super) {
  19396. __extends(_OculusInnerGamepadCamera, _super);
  19397. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19398. _super.call(this, name, position, scene);
  19399. this._workMatrix = new BABYLON.Matrix();
  19400. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19401. // Constants
  19402. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19403. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19404. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19405. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19406. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19407. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19408. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19409. // Postprocess
  19410. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19411. }
  19412. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19413. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19414. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19415. return this._projectionMatrix;
  19416. };
  19417. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19418. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19419. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19420. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19421. // Computing target and final matrix
  19422. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19423. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19424. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19425. return this._viewMatrix;
  19426. };
  19427. return _OculusInnerGamepadCamera;
  19428. })(BABYLON.FreeCamera);
  19429. var OculusGamepadCamera = (function (_super) {
  19430. __extends(OculusGamepadCamera, _super);
  19431. function OculusGamepadCamera(name, position, scene) {
  19432. var _this = this;
  19433. _super.call(this, name, position, scene);
  19434. this.angularSensibility = 200;
  19435. this.moveSensibility = 75;
  19436. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19437. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19438. this.subCameras.push(this._leftCamera);
  19439. this.subCameras.push(this._rightCamera);
  19440. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19441. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19442. _this._onNewGameConnected(gamepad);
  19443. });
  19444. }
  19445. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19446. // Only the first gamepad can control the camera
  19447. if (gamepad.index === 0) {
  19448. this._gamepad = gamepad;
  19449. }
  19450. };
  19451. OculusGamepadCamera.prototype._update = function () {
  19452. this._leftCamera.position.copyFrom(this.position);
  19453. this._rightCamera.position.copyFrom(this.position);
  19454. this._updateCamera(this._leftCamera);
  19455. this._updateCamera(this._rightCamera);
  19456. _super.prototype._update.call(this);
  19457. };
  19458. OculusGamepadCamera.prototype._checkInputs = function () {
  19459. if (!this._gamepad) {
  19460. return;
  19461. }
  19462. var LSValues = this._gamepad.leftStick;
  19463. var normalizedLX = LSValues.x / this.moveSensibility;
  19464. var normalizedLY = LSValues.y / this.moveSensibility;
  19465. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19466. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19467. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19468. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19469. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19470. };
  19471. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19472. camera.minZ = this.minZ;
  19473. camera.maxZ = this.maxZ;
  19474. camera.rotation.x = this.rotation.x;
  19475. camera.rotation.y = this.rotation.y;
  19476. camera.rotation.z = this.rotation.z;
  19477. };
  19478. // Oculus events
  19479. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19480. var yaw = evt.alpha / 180 * Math.PI;
  19481. var pitch = evt.beta / 180 * Math.PI;
  19482. var roll = evt.gamma / 180 * Math.PI;
  19483. if (!this._offsetOrientation) {
  19484. this._offsetOrientation = {
  19485. yaw: yaw,
  19486. pitch: pitch,
  19487. roll: roll
  19488. };
  19489. return;
  19490. } else {
  19491. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19492. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19493. this.rotation.z += this._offsetOrientation.roll - roll;
  19494. this._offsetOrientation.yaw = yaw;
  19495. this._offsetOrientation.pitch = pitch;
  19496. this._offsetOrientation.roll = roll;
  19497. }
  19498. };
  19499. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19500. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19501. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19502. };
  19503. OculusGamepadCamera.prototype.detachControl = function (element) {
  19504. _super.prototype.detachControl.call(this, element);
  19505. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19506. };
  19507. OculusGamepadCamera.prototype.dispose = function () {
  19508. this._gamepads.dispose();
  19509. _super.prototype.dispose.call(this);
  19510. };
  19511. return OculusGamepadCamera;
  19512. })(BABYLON.FreeCamera);
  19513. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19514. })(BABYLON || (BABYLON = {}));
  19515. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19516. var BABYLON;
  19517. (function (BABYLON) {
  19518. // We're mainly based on the logic defined into the FreeCamera code
  19519. var VirtualJoysticksCamera = (function (_super) {
  19520. __extends(VirtualJoysticksCamera, _super);
  19521. function VirtualJoysticksCamera(name, position, scene) {
  19522. _super.call(this, name, position, scene);
  19523. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19524. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19525. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19526. this._leftjoystick.setJoystickSensibility(0.15);
  19527. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19528. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19529. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19530. this._rightjoystick.reverseUpDown = true;
  19531. this._rightjoystick.setJoystickSensibility(0.05);
  19532. this._rightjoystick.setJoystickColor("yellow");
  19533. }
  19534. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19535. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19536. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19537. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19538. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19539. if (!this._leftjoystick.pressed) {
  19540. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19541. }
  19542. if (!this._rightjoystick.pressed) {
  19543. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19544. }
  19545. };
  19546. VirtualJoysticksCamera.prototype.dispose = function () {
  19547. this._leftjoystick.releaseCanvas();
  19548. _super.prototype.dispose.call(this);
  19549. };
  19550. return VirtualJoysticksCamera;
  19551. })(BABYLON.FreeCamera);
  19552. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19553. })(BABYLON || (BABYLON = {}));
  19554. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19555. var BABYLON;
  19556. (function (BABYLON) {
  19557. var ShaderMaterial = (function (_super) {
  19558. __extends(ShaderMaterial, _super);
  19559. function ShaderMaterial(name, scene, shaderPath, options) {
  19560. _super.call(this, name, scene);
  19561. this._textures = new Array();
  19562. this._floats = new Array();
  19563. this._floatsArrays = {};
  19564. this._colors3 = new Array();
  19565. this._colors4 = new Array();
  19566. this._vectors2 = new Array();
  19567. this._vectors3 = new Array();
  19568. this._matrices = new Array();
  19569. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19570. this._shaderPath = shaderPath;
  19571. options.needAlphaBlending = options.needAlphaBlending || false;
  19572. options.needAlphaTesting = options.needAlphaTesting || false;
  19573. options.attributes = options.attributes || ["position", "normal", "uv"];
  19574. options.uniforms = options.uniforms || ["worldViewProjection"];
  19575. options.samplers = options.samplers || [];
  19576. this._options = options;
  19577. }
  19578. ShaderMaterial.prototype.needAlphaBlending = function () {
  19579. return this._options.needAlphaBlending;
  19580. };
  19581. ShaderMaterial.prototype.needAlphaTesting = function () {
  19582. return this._options.needAlphaTesting;
  19583. };
  19584. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19585. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19586. this._options.uniforms.push(uniformName);
  19587. }
  19588. };
  19589. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19590. if (this._options.samplers.indexOf(name) === -1) {
  19591. this._options.samplers.push(name);
  19592. }
  19593. this._textures[name] = texture;
  19594. return this;
  19595. };
  19596. ShaderMaterial.prototype.setFloat = function (name, value) {
  19597. this._checkUniform(name);
  19598. this._floats[name] = value;
  19599. return this;
  19600. };
  19601. ShaderMaterial.prototype.setFloats = function (name, value) {
  19602. this._checkUniform(name);
  19603. this._floatsArrays[name] = value;
  19604. return this;
  19605. };
  19606. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19607. this._checkUniform(name);
  19608. this._colors3[name] = value;
  19609. return this;
  19610. };
  19611. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19612. this._checkUniform(name);
  19613. this._colors4[name] = value;
  19614. return this;
  19615. };
  19616. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19617. this._checkUniform(name);
  19618. this._vectors2[name] = value;
  19619. return this;
  19620. };
  19621. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19622. this._checkUniform(name);
  19623. this._vectors3[name] = value;
  19624. return this;
  19625. };
  19626. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19627. this._checkUniform(name);
  19628. this._matrices[name] = value;
  19629. return this;
  19630. };
  19631. ShaderMaterial.prototype.isReady = function () {
  19632. var scene = this.getScene();
  19633. var engine = scene.getEngine();
  19634. if (!this.checkReadyOnEveryCall) {
  19635. if (this._renderId === scene.getRenderId()) {
  19636. return true;
  19637. }
  19638. }
  19639. var previousEffect = this._effect;
  19640. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19641. if (!this._effect.isReady()) {
  19642. return false;
  19643. }
  19644. if (previousEffect !== this._effect) {
  19645. scene.resetCachedMaterial();
  19646. }
  19647. this._renderId = scene.getRenderId();
  19648. return true;
  19649. };
  19650. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19651. var scene = this.getScene();
  19652. if (this._options.uniforms.indexOf("world") !== -1) {
  19653. this._effect.setMatrix("world", world);
  19654. }
  19655. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19656. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19657. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19658. }
  19659. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19660. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19661. }
  19662. };
  19663. ShaderMaterial.prototype.bind = function (world) {
  19664. // Std values
  19665. this.bindOnlyWorldMatrix(world);
  19666. if (this.getScene().getCachedMaterial() !== this) {
  19667. if (this._options.uniforms.indexOf("view") !== -1) {
  19668. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19669. }
  19670. if (this._options.uniforms.indexOf("projection") !== -1) {
  19671. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19672. }
  19673. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19674. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19675. }
  19676. for (var name in this._textures) {
  19677. this._effect.setTexture(name, this._textures[name]);
  19678. }
  19679. for (name in this._floats) {
  19680. this._effect.setFloat(name, this._floats[name]);
  19681. }
  19682. for (name in this._floatsArrays) {
  19683. this._effect.setArray(name, this._floatsArrays[name]);
  19684. }
  19685. for (name in this._colors3) {
  19686. this._effect.setColor3(name, this._colors3[name]);
  19687. }
  19688. for (name in this._colors4) {
  19689. var color = this._colors4[name];
  19690. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19691. }
  19692. for (name in this._vectors2) {
  19693. this._effect.setVector2(name, this._vectors2[name]);
  19694. }
  19695. for (name in this._vectors3) {
  19696. this._effect.setVector3(name, this._vectors3[name]);
  19697. }
  19698. for (name in this._matrices) {
  19699. this._effect.setMatrix(name, this._matrices[name]);
  19700. }
  19701. }
  19702. _super.prototype.bind.call(this, world, null);
  19703. };
  19704. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19705. for (var name in this._textures) {
  19706. this._textures[name].dispose();
  19707. }
  19708. this._textures = [];
  19709. _super.prototype.dispose.call(this, forceDisposeEffect);
  19710. };
  19711. return ShaderMaterial;
  19712. })(BABYLON.Material);
  19713. BABYLON.ShaderMaterial = ShaderMaterial;
  19714. })(BABYLON || (BABYLON = {}));
  19715. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19716. var BABYLON;
  19717. (function (BABYLON) {
  19718. var VertexData = (function () {
  19719. function VertexData() {
  19720. }
  19721. VertexData.prototype.set = function (data, kind) {
  19722. switch (kind) {
  19723. case BABYLON.VertexBuffer.PositionKind:
  19724. this.positions = data;
  19725. break;
  19726. case BABYLON.VertexBuffer.NormalKind:
  19727. this.normals = data;
  19728. break;
  19729. case BABYLON.VertexBuffer.UVKind:
  19730. this.uvs = data;
  19731. break;
  19732. case BABYLON.VertexBuffer.UV2Kind:
  19733. this.uv2s = data;
  19734. break;
  19735. case BABYLON.VertexBuffer.ColorKind:
  19736. this.colors = data;
  19737. break;
  19738. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19739. this.matricesIndices = data;
  19740. break;
  19741. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19742. this.matricesWeights = data;
  19743. break;
  19744. }
  19745. };
  19746. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19747. this._applyTo(mesh, updatable);
  19748. };
  19749. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19750. this._applyTo(geometry, updatable);
  19751. };
  19752. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19753. this._update(mesh);
  19754. };
  19755. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19756. this._update(geometry);
  19757. };
  19758. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19759. if (this.positions) {
  19760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19761. }
  19762. if (this.normals) {
  19763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19764. }
  19765. if (this.uvs) {
  19766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19767. }
  19768. if (this.uv2s) {
  19769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19770. }
  19771. if (this.colors) {
  19772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19773. }
  19774. if (this.matricesIndices) {
  19775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19776. }
  19777. if (this.matricesWeights) {
  19778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19779. }
  19780. if (this.indices) {
  19781. meshOrGeometry.setIndices(this.indices);
  19782. }
  19783. };
  19784. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19785. if (this.positions) {
  19786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19787. }
  19788. if (this.normals) {
  19789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19790. }
  19791. if (this.uvs) {
  19792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19793. }
  19794. if (this.uv2s) {
  19795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19796. }
  19797. if (this.colors) {
  19798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19799. }
  19800. if (this.matricesIndices) {
  19801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19802. }
  19803. if (this.matricesWeights) {
  19804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19805. }
  19806. if (this.indices) {
  19807. meshOrGeometry.setIndices(this.indices);
  19808. }
  19809. };
  19810. VertexData.prototype.transform = function (matrix) {
  19811. var transformed = BABYLON.Vector3.Zero();
  19812. if (this.positions) {
  19813. var position = BABYLON.Vector3.Zero();
  19814. for (var index = 0; index < this.positions.length; index += 3) {
  19815. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19816. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19817. this.positions[index] = transformed.x;
  19818. this.positions[index + 1] = transformed.y;
  19819. this.positions[index + 2] = transformed.z;
  19820. }
  19821. }
  19822. if (this.normals) {
  19823. var normal = BABYLON.Vector3.Zero();
  19824. for (index = 0; index < this.normals.length; index += 3) {
  19825. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19826. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19827. this.normals[index] = transformed.x;
  19828. this.normals[index + 1] = transformed.y;
  19829. this.normals[index + 2] = transformed.z;
  19830. }
  19831. }
  19832. };
  19833. VertexData.prototype.merge = function (other) {
  19834. if (other.indices) {
  19835. if (!this.indices) {
  19836. this.indices = [];
  19837. }
  19838. var offset = this.positions ? this.positions.length / 3 : 0;
  19839. for (var index = 0; index < other.indices.length; index++) {
  19840. this.indices.push(other.indices[index] + offset);
  19841. }
  19842. }
  19843. if (other.positions) {
  19844. if (!this.positions) {
  19845. this.positions = [];
  19846. }
  19847. for (index = 0; index < other.positions.length; index++) {
  19848. this.positions.push(other.positions[index]);
  19849. }
  19850. }
  19851. if (other.normals) {
  19852. if (!this.normals) {
  19853. this.normals = [];
  19854. }
  19855. for (index = 0; index < other.normals.length; index++) {
  19856. this.normals.push(other.normals[index]);
  19857. }
  19858. }
  19859. if (other.uvs) {
  19860. if (!this.uvs) {
  19861. this.uvs = [];
  19862. }
  19863. for (index = 0; index < other.uvs.length; index++) {
  19864. this.uvs.push(other.uvs[index]);
  19865. }
  19866. }
  19867. if (other.uv2s) {
  19868. if (!this.uv2s) {
  19869. this.uv2s = [];
  19870. }
  19871. for (index = 0; index < other.uv2s.length; index++) {
  19872. this.uv2s.push(other.uv2s[index]);
  19873. }
  19874. }
  19875. if (other.matricesIndices) {
  19876. if (!this.matricesIndices) {
  19877. this.matricesIndices = [];
  19878. }
  19879. for (index = 0; index < other.matricesIndices.length; index++) {
  19880. this.matricesIndices.push(other.matricesIndices[index]);
  19881. }
  19882. }
  19883. if (other.matricesWeights) {
  19884. if (!this.matricesWeights) {
  19885. this.matricesWeights = [];
  19886. }
  19887. for (index = 0; index < other.matricesWeights.length; index++) {
  19888. this.matricesWeights.push(other.matricesWeights[index]);
  19889. }
  19890. }
  19891. if (other.colors) {
  19892. if (!this.colors) {
  19893. this.colors = [];
  19894. }
  19895. for (index = 0; index < other.colors.length; index++) {
  19896. this.colors.push(other.colors[index]);
  19897. }
  19898. }
  19899. };
  19900. // Statics
  19901. VertexData.ExtractFromMesh = function (mesh) {
  19902. return VertexData._ExtractFrom(mesh);
  19903. };
  19904. VertexData.ExtractFromGeometry = function (geometry) {
  19905. return VertexData._ExtractFrom(geometry);
  19906. };
  19907. VertexData._ExtractFrom = function (meshOrGeometry) {
  19908. var result = new BABYLON.VertexData();
  19909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19910. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19911. }
  19912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19913. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19914. }
  19915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19916. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19917. }
  19918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19919. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19920. }
  19921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19922. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19923. }
  19924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19925. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19926. }
  19927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19928. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19929. }
  19930. result.indices = meshOrGeometry.getIndices();
  19931. return result;
  19932. };
  19933. VertexData.CreateBox = function (size) {
  19934. var normalsSource = [
  19935. new BABYLON.Vector3(0, 0, 1),
  19936. new BABYLON.Vector3(0, 0, -1),
  19937. new BABYLON.Vector3(1, 0, 0),
  19938. new BABYLON.Vector3(-1, 0, 0),
  19939. new BABYLON.Vector3(0, 1, 0),
  19940. new BABYLON.Vector3(0, -1, 0)
  19941. ];
  19942. var indices = [];
  19943. var positions = [];
  19944. var normals = [];
  19945. var uvs = [];
  19946. size = size || 1;
  19947. for (var index = 0; index < normalsSource.length; index++) {
  19948. var normal = normalsSource[index];
  19949. // Get two vectors perpendicular to the face normal and to each other.
  19950. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19951. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19952. // Six indices (two triangles) per face.
  19953. var verticesLength = positions.length / 3;
  19954. indices.push(verticesLength);
  19955. indices.push(verticesLength + 1);
  19956. indices.push(verticesLength + 2);
  19957. indices.push(verticesLength);
  19958. indices.push(verticesLength + 2);
  19959. indices.push(verticesLength + 3);
  19960. // Four vertices per face.
  19961. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19962. positions.push(vertex.x, vertex.y, vertex.z);
  19963. normals.push(normal.x, normal.y, normal.z);
  19964. uvs.push(1.0, 1.0);
  19965. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19966. positions.push(vertex.x, vertex.y, vertex.z);
  19967. normals.push(normal.x, normal.y, normal.z);
  19968. uvs.push(0.0, 1.0);
  19969. vertex = normal.add(side1).add(side2).scale(size / 2);
  19970. positions.push(vertex.x, vertex.y, vertex.z);
  19971. normals.push(normal.x, normal.y, normal.z);
  19972. uvs.push(0.0, 0.0);
  19973. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19974. positions.push(vertex.x, vertex.y, vertex.z);
  19975. normals.push(normal.x, normal.y, normal.z);
  19976. uvs.push(1.0, 0.0);
  19977. }
  19978. // Result
  19979. var vertexData = new BABYLON.VertexData();
  19980. vertexData.indices = indices;
  19981. vertexData.positions = positions;
  19982. vertexData.normals = normals;
  19983. vertexData.uvs = uvs;
  19984. return vertexData;
  19985. };
  19986. VertexData.CreateSphere = function (segments, diameter) {
  19987. segments = segments || 32;
  19988. diameter = diameter || 1;
  19989. var radius = diameter / 2;
  19990. var totalZRotationSteps = 2 + segments;
  19991. var totalYRotationSteps = 2 * totalZRotationSteps;
  19992. var indices = [];
  19993. var positions = [];
  19994. var normals = [];
  19995. var uvs = [];
  19996. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19997. var normalizedZ = zRotationStep / totalZRotationSteps;
  19998. var angleZ = (normalizedZ * Math.PI);
  19999. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20000. var normalizedY = yRotationStep / totalYRotationSteps;
  20001. var angleY = normalizedY * Math.PI * 2;
  20002. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20003. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20004. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20005. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20006. var vertex = complete.scale(radius);
  20007. var normal = BABYLON.Vector3.Normalize(vertex);
  20008. positions.push(vertex.x, vertex.y, vertex.z);
  20009. normals.push(normal.x, normal.y, normal.z);
  20010. uvs.push(normalizedZ, normalizedY);
  20011. }
  20012. if (zRotationStep > 0) {
  20013. var verticesCount = positions.length / 3;
  20014. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20015. indices.push((firstIndex));
  20016. indices.push((firstIndex + 1));
  20017. indices.push(firstIndex + totalYRotationSteps + 1);
  20018. indices.push((firstIndex + totalYRotationSteps + 1));
  20019. indices.push((firstIndex + 1));
  20020. indices.push((firstIndex + totalYRotationSteps + 2));
  20021. }
  20022. }
  20023. }
  20024. // Result
  20025. var vertexData = new BABYLON.VertexData();
  20026. vertexData.indices = indices;
  20027. vertexData.positions = positions;
  20028. vertexData.normals = normals;
  20029. vertexData.uvs = uvs;
  20030. return vertexData;
  20031. };
  20032. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20033. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20034. var radiusTop = diameterTop / 2;
  20035. var radiusBottom = diameterBottom / 2;
  20036. var indices = [];
  20037. var positions = [];
  20038. var normals = [];
  20039. var uvs = [];
  20040. height = height || 1;
  20041. diameterTop = diameterTop || 0.5;
  20042. diameterBottom = diameterBottom || 1;
  20043. tessellation = tessellation || 16;
  20044. subdivisions = subdivisions || 1;
  20045. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20046. var getCircleVector = function (i) {
  20047. var angle = (i * 2.0 * Math.PI / tessellation);
  20048. var dx = Math.cos(angle);
  20049. var dz = Math.sin(angle);
  20050. return new BABYLON.Vector3(dx, 0, dz);
  20051. };
  20052. var createCylinderCap = function (isTop) {
  20053. var radius = isTop ? radiusTop : radiusBottom;
  20054. if (radius == 0) {
  20055. return;
  20056. }
  20057. var vbase = positions.length / 3;
  20058. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20059. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20060. if (!isTop) {
  20061. offset.scaleInPlace(-1);
  20062. textureScale.x = -textureScale.x;
  20063. }
  20064. for (i = 0; i < tessellation; i++) {
  20065. var circleVector = getCircleVector(i);
  20066. var position = circleVector.scale(radius).add(offset);
  20067. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20068. positions.push(position.x, position.y, position.z);
  20069. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20070. }
  20071. for (var i = 0; i < tessellation - 2; i++) {
  20072. if (!isTop) {
  20073. indices.push(vbase);
  20074. indices.push(vbase + (i + 2) % tessellation);
  20075. indices.push(vbase + (i + 1) % tessellation);
  20076. } else {
  20077. indices.push(vbase);
  20078. indices.push(vbase + (i + 1) % tessellation);
  20079. indices.push(vbase + (i + 2) % tessellation);
  20080. }
  20081. }
  20082. };
  20083. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20084. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20085. var stride = tessellation + 1;
  20086. for (var i = 0; i <= tessellation; i++) {
  20087. var circleVector = getCircleVector(i);
  20088. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20089. var position, radius = radiusBottom;
  20090. for (var s = 0; s <= subdivisions; s++) {
  20091. // Update variables
  20092. position = circleVector.scale(radius);
  20093. position.addInPlace(base.add(offset.scale(s)));
  20094. textureCoordinate.y += 1 / subdivisions;
  20095. radius += (radiusTop - radiusBottom) / subdivisions;
  20096. // Push in arrays
  20097. positions.push(position.x, position.y, position.z);
  20098. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20099. }
  20100. }
  20101. subdivisions += 1;
  20102. for (var s = 0; s < subdivisions - 1; s++) {
  20103. for (var i = 0; i <= tessellation; i++) {
  20104. indices.push(i * subdivisions + s);
  20105. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20106. indices.push(i * subdivisions + (s + 1));
  20107. indices.push(i * subdivisions + (s + 1));
  20108. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20109. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20110. }
  20111. }
  20112. // Create flat triangle fan caps to seal the top and bottom.
  20113. createCylinderCap(true);
  20114. createCylinderCap(false);
  20115. // Normals
  20116. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20117. // Result
  20118. var vertexData = new BABYLON.VertexData();
  20119. vertexData.indices = indices;
  20120. vertexData.positions = positions;
  20121. vertexData.normals = normals;
  20122. vertexData.uvs = uvs;
  20123. return vertexData;
  20124. };
  20125. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20126. var indices = [];
  20127. var positions = [];
  20128. var normals = [];
  20129. var uvs = [];
  20130. diameter = diameter || 1;
  20131. thickness = thickness || 0.5;
  20132. tessellation = tessellation || 16;
  20133. var stride = tessellation + 1;
  20134. for (var i = 0; i <= tessellation; i++) {
  20135. var u = i / tessellation;
  20136. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20137. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20138. for (var j = 0; j <= tessellation; j++) {
  20139. var v = 1 - j / tessellation;
  20140. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20141. var dx = Math.cos(innerAngle);
  20142. var dy = Math.sin(innerAngle);
  20143. // Create a vertex.
  20144. var normal = new BABYLON.Vector3(dx, dy, 0);
  20145. var position = normal.scale(thickness / 2);
  20146. var textureCoordinate = new BABYLON.Vector2(u, v);
  20147. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20148. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20149. positions.push(position.x, position.y, position.z);
  20150. normals.push(normal.x, normal.y, normal.z);
  20151. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20152. // And create indices for two triangles.
  20153. var nextI = (i + 1) % stride;
  20154. var nextJ = (j + 1) % stride;
  20155. indices.push(i * stride + j);
  20156. indices.push(i * stride + nextJ);
  20157. indices.push(nextI * stride + j);
  20158. indices.push(i * stride + nextJ);
  20159. indices.push(nextI * stride + nextJ);
  20160. indices.push(nextI * stride + j);
  20161. }
  20162. }
  20163. // Result
  20164. var vertexData = new BABYLON.VertexData();
  20165. vertexData.indices = indices;
  20166. vertexData.positions = positions;
  20167. vertexData.normals = normals;
  20168. vertexData.uvs = uvs;
  20169. return vertexData;
  20170. };
  20171. VertexData.CreateLines = function (points) {
  20172. var indices = [];
  20173. var positions = [];
  20174. for (var index = 0; index < points.length; index++) {
  20175. positions.push(points[index].x, points[index].y, points[index].z);
  20176. if (index > 0) {
  20177. indices.push(index - 1);
  20178. indices.push(index);
  20179. }
  20180. }
  20181. // Result
  20182. var vertexData = new BABYLON.VertexData();
  20183. vertexData.indices = indices;
  20184. vertexData.positions = positions;
  20185. return vertexData;
  20186. };
  20187. VertexData.CreateGround = function (width, height, subdivisions) {
  20188. var indices = [];
  20189. var positions = [];
  20190. var normals = [];
  20191. var uvs = [];
  20192. var row, col;
  20193. width = width || 1;
  20194. height = height || 1;
  20195. subdivisions = subdivisions || 1;
  20196. for (row = 0; row <= subdivisions; row++) {
  20197. for (col = 0; col <= subdivisions; col++) {
  20198. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20199. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20200. positions.push(position.x, position.y, position.z);
  20201. normals.push(normal.x, normal.y, normal.z);
  20202. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20203. }
  20204. }
  20205. for (row = 0; row < subdivisions; row++) {
  20206. for (col = 0; col < subdivisions; col++) {
  20207. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20208. indices.push(col + 1 + row * (subdivisions + 1));
  20209. indices.push(col + row * (subdivisions + 1));
  20210. indices.push(col + (row + 1) * (subdivisions + 1));
  20211. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20212. indices.push(col + row * (subdivisions + 1));
  20213. }
  20214. }
  20215. // Result
  20216. var vertexData = new BABYLON.VertexData();
  20217. vertexData.indices = indices;
  20218. vertexData.positions = positions;
  20219. vertexData.normals = normals;
  20220. vertexData.uvs = uvs;
  20221. return vertexData;
  20222. };
  20223. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20224. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  20225. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  20226. var indices = [];
  20227. var positions = [];
  20228. var normals = [];
  20229. var uvs = [];
  20230. var row, col, tileRow, tileCol;
  20231. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20232. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20233. precision.w = (precision.w < 1) ? 1 : precision.w;
  20234. precision.h = (precision.h < 1) ? 1 : precision.h;
  20235. var tileSize = {
  20236. 'w': (xmax - xmin) / subdivisions.w,
  20237. 'h': (zmax - zmin) / subdivisions.h
  20238. };
  20239. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20240. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20241. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20242. }
  20243. }
  20244. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20245. // Indices
  20246. var base = positions.length / 3;
  20247. var rowLength = precision.w + 1;
  20248. for (row = 0; row < precision.h; row++) {
  20249. for (col = 0; col < precision.w; col++) {
  20250. var square = [
  20251. base + col + row * rowLength,
  20252. base + (col + 1) + row * rowLength,
  20253. base + (col + 1) + (row + 1) * rowLength,
  20254. base + col + (row + 1) * rowLength
  20255. ];
  20256. indices.push(square[1]);
  20257. indices.push(square[2]);
  20258. indices.push(square[3]);
  20259. indices.push(square[0]);
  20260. indices.push(square[1]);
  20261. indices.push(square[3]);
  20262. }
  20263. }
  20264. // Position, normals and uvs
  20265. var position = BABYLON.Vector3.Zero();
  20266. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20267. for (row = 0; row <= precision.h; row++) {
  20268. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20269. for (col = 0; col <= precision.w; col++) {
  20270. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20271. position.y = 0;
  20272. positions.push(position.x, position.y, position.z);
  20273. normals.push(normal.x, normal.y, normal.z);
  20274. uvs.push(col / precision.w, row / precision.h);
  20275. }
  20276. }
  20277. }
  20278. // Result
  20279. var vertexData = new BABYLON.VertexData();
  20280. vertexData.indices = indices;
  20281. vertexData.positions = positions;
  20282. vertexData.normals = normals;
  20283. vertexData.uvs = uvs;
  20284. return vertexData;
  20285. };
  20286. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20287. var indices = [];
  20288. var positions = [];
  20289. var normals = [];
  20290. var uvs = [];
  20291. var row, col;
  20292. for (row = 0; row <= subdivisions; row++) {
  20293. for (col = 0; col <= subdivisions; col++) {
  20294. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20295. // Compute height
  20296. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20297. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20298. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20299. var r = buffer[pos] / 255.0;
  20300. var g = buffer[pos + 1] / 255.0;
  20301. var b = buffer[pos + 2] / 255.0;
  20302. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20303. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20304. // Add vertex
  20305. positions.push(position.x, position.y, position.z);
  20306. normals.push(0, 0, 0);
  20307. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20308. }
  20309. }
  20310. for (row = 0; row < subdivisions; row++) {
  20311. for (col = 0; col < subdivisions; col++) {
  20312. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20313. indices.push(col + 1 + row * (subdivisions + 1));
  20314. indices.push(col + row * (subdivisions + 1));
  20315. indices.push(col + (row + 1) * (subdivisions + 1));
  20316. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20317. indices.push(col + row * (subdivisions + 1));
  20318. }
  20319. }
  20320. // Normals
  20321. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20322. // Result
  20323. var vertexData = new BABYLON.VertexData();
  20324. vertexData.indices = indices;
  20325. vertexData.positions = positions;
  20326. vertexData.normals = normals;
  20327. vertexData.uvs = uvs;
  20328. return vertexData;
  20329. };
  20330. VertexData.CreatePlane = function (size) {
  20331. var indices = [];
  20332. var positions = [];
  20333. var normals = [];
  20334. var uvs = [];
  20335. size = size || 1;
  20336. // Vertices
  20337. var halfSize = size / 2.0;
  20338. positions.push(-halfSize, -halfSize, 0);
  20339. normals.push(0, 0, -1.0);
  20340. uvs.push(0.0, 0.0);
  20341. positions.push(halfSize, -halfSize, 0);
  20342. normals.push(0, 0, -1.0);
  20343. uvs.push(1.0, 0.0);
  20344. positions.push(halfSize, halfSize, 0);
  20345. normals.push(0, 0, -1.0);
  20346. uvs.push(1.0, 1.0);
  20347. positions.push(-halfSize, halfSize, 0);
  20348. normals.push(0, 0, -1.0);
  20349. uvs.push(0.0, 1.0);
  20350. // Indices
  20351. indices.push(0);
  20352. indices.push(1);
  20353. indices.push(2);
  20354. indices.push(0);
  20355. indices.push(2);
  20356. indices.push(3);
  20357. // Result
  20358. var vertexData = new BABYLON.VertexData();
  20359. vertexData.indices = indices;
  20360. vertexData.positions = positions;
  20361. vertexData.normals = normals;
  20362. vertexData.uvs = uvs;
  20363. return vertexData;
  20364. };
  20365. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20366. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20367. var indices = [];
  20368. var positions = [];
  20369. var normals = [];
  20370. var uvs = [];
  20371. radius = radius || 2;
  20372. tube = tube || 0.5;
  20373. radialSegments = radialSegments || 32;
  20374. tubularSegments = tubularSegments || 32;
  20375. p = p || 2;
  20376. q = q || 3;
  20377. // Helper
  20378. var getPos = function (angle) {
  20379. var cu = Math.cos(angle);
  20380. var su = Math.sin(angle);
  20381. var quOverP = q / p * angle;
  20382. var cs = Math.cos(quOverP);
  20383. var tx = radius * (2 + cs) * 0.5 * cu;
  20384. var ty = radius * (2 + cs) * su * 0.5;
  20385. var tz = radius * Math.sin(quOverP) * 0.5;
  20386. return new BABYLON.Vector3(tx, ty, tz);
  20387. };
  20388. for (var i = 0; i <= radialSegments; i++) {
  20389. var modI = i % radialSegments;
  20390. var u = modI / radialSegments * 2 * p * Math.PI;
  20391. var p1 = getPos(u);
  20392. var p2 = getPos(u + 0.01);
  20393. var tang = p2.subtract(p1);
  20394. var n = p2.add(p1);
  20395. var bitan = BABYLON.Vector3.Cross(tang, n);
  20396. n = BABYLON.Vector3.Cross(bitan, tang);
  20397. bitan.normalize();
  20398. n.normalize();
  20399. for (var j = 0; j < tubularSegments; j++) {
  20400. var modJ = j % tubularSegments;
  20401. var v = modJ / tubularSegments * 2 * Math.PI;
  20402. var cx = -tube * Math.cos(v);
  20403. var cy = tube * Math.sin(v);
  20404. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20405. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20406. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20407. uvs.push(i / radialSegments);
  20408. uvs.push(j / tubularSegments);
  20409. }
  20410. }
  20411. for (i = 0; i < radialSegments; i++) {
  20412. for (j = 0; j < tubularSegments; j++) {
  20413. var jNext = (j + 1) % tubularSegments;
  20414. var a = i * tubularSegments + j;
  20415. var b = (i + 1) * tubularSegments + j;
  20416. var c = (i + 1) * tubularSegments + jNext;
  20417. var d = i * tubularSegments + jNext;
  20418. indices.push(d);
  20419. indices.push(b);
  20420. indices.push(a);
  20421. indices.push(d);
  20422. indices.push(c);
  20423. indices.push(b);
  20424. }
  20425. }
  20426. // Normals
  20427. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20428. // Result
  20429. var vertexData = new BABYLON.VertexData();
  20430. vertexData.indices = indices;
  20431. vertexData.positions = positions;
  20432. vertexData.normals = normals;
  20433. vertexData.uvs = uvs;
  20434. return vertexData;
  20435. };
  20436. // Tools
  20437. VertexData.ComputeNormals = function (positions, indices, normals) {
  20438. var positionVectors = [];
  20439. var facesOfVertices = [];
  20440. var index;
  20441. for (index = 0; index < positions.length; index += 3) {
  20442. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20443. positionVectors.push(vector3);
  20444. facesOfVertices.push([]);
  20445. }
  20446. // Compute normals
  20447. var facesNormals = [];
  20448. for (index = 0; index < indices.length / 3; index++) {
  20449. var i1 = indices[index * 3];
  20450. var i2 = indices[index * 3 + 1];
  20451. var i3 = indices[index * 3 + 2];
  20452. var p1 = positionVectors[i1];
  20453. var p2 = positionVectors[i2];
  20454. var p3 = positionVectors[i3];
  20455. var p1p2 = p1.subtract(p2);
  20456. var p3p2 = p3.subtract(p2);
  20457. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20458. facesOfVertices[i1].push(index);
  20459. facesOfVertices[i2].push(index);
  20460. facesOfVertices[i3].push(index);
  20461. }
  20462. for (index = 0; index < positionVectors.length; index++) {
  20463. var faces = facesOfVertices[index];
  20464. var normal = BABYLON.Vector3.Zero();
  20465. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20466. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20467. }
  20468. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20469. normals[index * 3] = normal.x;
  20470. normals[index * 3 + 1] = normal.y;
  20471. normals[index * 3 + 2] = normal.z;
  20472. }
  20473. };
  20474. return VertexData;
  20475. })();
  20476. BABYLON.VertexData = VertexData;
  20477. })(BABYLON || (BABYLON = {}));
  20478. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20479. var BABYLON;
  20480. (function (BABYLON) {
  20481. var buildCamera = function (that, name) {
  20482. that._leftCamera.isIntermediate = true;
  20483. that.subCameras.push(that._leftCamera);
  20484. that.subCameras.push(that._rightCamera);
  20485. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20486. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20487. that._anaglyphPostProcess.onApply = function (effect) {
  20488. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20489. };
  20490. that._update();
  20491. };
  20492. var AnaglyphArcRotateCamera = (function (_super) {
  20493. __extends(AnaglyphArcRotateCamera, _super);
  20494. // ANY
  20495. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20496. _super.call(this, name, alpha, beta, radius, target, scene);
  20497. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20498. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20499. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20500. buildCamera(this, name);
  20501. }
  20502. AnaglyphArcRotateCamera.prototype._update = function () {
  20503. this._updateCamera(this._leftCamera);
  20504. this._updateCamera(this._rightCamera);
  20505. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20506. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20507. _super.prototype._update.call(this);
  20508. };
  20509. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20510. camera.beta = this.beta;
  20511. camera.radius = this.radius;
  20512. camera.minZ = this.minZ;
  20513. camera.maxZ = this.maxZ;
  20514. camera.fov = this.fov;
  20515. camera.target = this.target;
  20516. };
  20517. return AnaglyphArcRotateCamera;
  20518. })(BABYLON.ArcRotateCamera);
  20519. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20520. var AnaglyphFreeCamera = (function (_super) {
  20521. __extends(AnaglyphFreeCamera, _super);
  20522. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20523. _super.call(this, name, position, scene);
  20524. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20525. this._transformMatrix = new BABYLON.Matrix();
  20526. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20527. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20528. buildCamera(this, name);
  20529. }
  20530. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20531. var target = this.getTarget();
  20532. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20533. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20534. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20535. };
  20536. AnaglyphFreeCamera.prototype._update = function () {
  20537. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20538. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20539. this._updateCamera(this._leftCamera);
  20540. this._updateCamera(this._rightCamera);
  20541. _super.prototype._update.call(this);
  20542. };
  20543. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20544. camera.minZ = this.minZ;
  20545. camera.maxZ = this.maxZ;
  20546. camera.fov = this.fov;
  20547. camera.viewport = this.viewport;
  20548. camera.setTarget(this.getTarget());
  20549. };
  20550. return AnaglyphFreeCamera;
  20551. })(BABYLON.FreeCamera);
  20552. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20553. })(BABYLON || (BABYLON = {}));
  20554. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20555. var BABYLON;
  20556. (function (BABYLON) {
  20557. var AnaglyphPostProcess = (function (_super) {
  20558. __extends(AnaglyphPostProcess, _super);
  20559. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20560. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20561. }
  20562. return AnaglyphPostProcess;
  20563. })(BABYLON.PostProcess);
  20564. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20565. })(BABYLON || (BABYLON = {}));
  20566. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20567. var BABYLON;
  20568. (function (BABYLON) {
  20569. var Tags = (function () {
  20570. function Tags() {
  20571. }
  20572. Tags.EnableFor = function (obj) {
  20573. obj._tags = obj._tags || {};
  20574. obj.hasTags = function () {
  20575. return Tags.HasTags(obj);
  20576. };
  20577. obj.addTags = function (tagsString) {
  20578. return Tags.AddTagsTo(obj, tagsString);
  20579. };
  20580. obj.removeTags = function (tagsString) {
  20581. return Tags.RemoveTagsFrom(obj, tagsString);
  20582. };
  20583. obj.matchesTagsQuery = function (tagsQuery) {
  20584. return Tags.MatchesQuery(obj, tagsQuery);
  20585. };
  20586. };
  20587. Tags.DisableFor = function (obj) {
  20588. delete obj._tags;
  20589. delete obj.hasTags;
  20590. delete obj.addTags;
  20591. delete obj.removeTags;
  20592. delete obj.matchesTagsQuery;
  20593. };
  20594. Tags.HasTags = function (obj) {
  20595. if (!obj._tags) {
  20596. return false;
  20597. }
  20598. return !BABYLON.Tools.IsEmpty(obj._tags);
  20599. };
  20600. Tags.GetTags = function (obj) {
  20601. if (!obj._tags) {
  20602. return null;
  20603. }
  20604. return obj._tags;
  20605. };
  20606. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20607. // a tag cannot start with '||', '&&', and '!'
  20608. // it cannot contain whitespaces
  20609. Tags.AddTagsTo = function (obj, tagsString) {
  20610. if (!tagsString) {
  20611. return;
  20612. }
  20613. var tags = tagsString.split(" ");
  20614. for (var t in tags) {
  20615. Tags._AddTagTo(obj, tags[t]);
  20616. }
  20617. };
  20618. Tags._AddTagTo = function (obj, tag) {
  20619. tag = tag.trim();
  20620. if (tag === "" || tag === "true" || tag === "false") {
  20621. return;
  20622. }
  20623. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20624. return;
  20625. }
  20626. Tags.EnableFor(obj);
  20627. obj._tags[tag] = true;
  20628. };
  20629. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20630. if (!Tags.HasTags(obj)) {
  20631. return;
  20632. }
  20633. var tags = tagsString.split(" ");
  20634. for (var t in tags) {
  20635. Tags._RemoveTagFrom(obj, tags[t]);
  20636. }
  20637. };
  20638. Tags._RemoveTagFrom = function (obj, tag) {
  20639. delete obj._tags[tag];
  20640. };
  20641. Tags.MatchesQuery = function (obj, tagsQuery) {
  20642. if (tagsQuery === undefined) {
  20643. return true;
  20644. }
  20645. if (tagsQuery === "") {
  20646. return Tags.HasTags(obj);
  20647. }
  20648. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20649. return Tags.HasTags(obj) && obj._tags[r];
  20650. });
  20651. };
  20652. return Tags;
  20653. })();
  20654. BABYLON.Tags = Tags;
  20655. })(BABYLON || (BABYLON = {}));
  20656. //# sourceMappingURL=babylon.tags.js.map
  20657. var BABYLON;
  20658. (function (BABYLON) {
  20659. (function (Internals) {
  20660. var AndOrNotEvaluator = (function () {
  20661. function AndOrNotEvaluator() {
  20662. }
  20663. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20664. if (!query.match(/\([^\(\)]*\)/g)) {
  20665. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20666. } else {
  20667. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20668. // remove parenthesis
  20669. r = r.slice(1, r.length - 1);
  20670. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20671. });
  20672. }
  20673. if (query === "true") {
  20674. return true;
  20675. }
  20676. if (query === "false") {
  20677. return false;
  20678. }
  20679. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20680. };
  20681. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20682. evaluateCallback = evaluateCallback || (function (r) {
  20683. return r === "true" ? true : false;
  20684. });
  20685. var result;
  20686. var or = parenthesisContent.split("||");
  20687. for (var i in or) {
  20688. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20689. var and = ori.split("&&");
  20690. if (and.length > 1) {
  20691. for (var j = 0; j < and.length; ++j) {
  20692. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20693. if (andj !== "true" && andj !== "false") {
  20694. if (andj[0] === "!") {
  20695. result = !evaluateCallback(andj.substring(1));
  20696. } else {
  20697. result = evaluateCallback(andj);
  20698. }
  20699. } else {
  20700. result = andj === "true" ? true : false;
  20701. }
  20702. if (!result) {
  20703. ori = "false";
  20704. break;
  20705. }
  20706. }
  20707. }
  20708. if (result || ori === "true") {
  20709. result = true;
  20710. break;
  20711. }
  20712. // result equals false (or undefined)
  20713. if (ori !== "true" && ori !== "false") {
  20714. if (ori[0] === "!") {
  20715. result = !evaluateCallback(ori.substring(1));
  20716. } else {
  20717. result = evaluateCallback(ori);
  20718. }
  20719. } else {
  20720. result = ori === "true" ? true : false;
  20721. }
  20722. }
  20723. // the whole parenthesis scope is replaced by 'true' or 'false'
  20724. return result ? "true" : "false";
  20725. };
  20726. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20727. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20728. // remove whitespaces
  20729. r = r.replace(/[\s]/g, function () {
  20730. return "";
  20731. });
  20732. return r.length % 2 ? "!" : "";
  20733. });
  20734. booleanString = booleanString.trim();
  20735. if (booleanString === "!true") {
  20736. booleanString = "false";
  20737. } else if (booleanString === "!false") {
  20738. booleanString = "true";
  20739. }
  20740. return booleanString;
  20741. };
  20742. return AndOrNotEvaluator;
  20743. })();
  20744. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20745. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20746. var Internals = BABYLON.Internals;
  20747. })(BABYLON || (BABYLON = {}));
  20748. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20749. var BABYLON;
  20750. (function (BABYLON) {
  20751. var PostProcessRenderPass = (function () {
  20752. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20753. this._enabled = true;
  20754. this._refCount = 0;
  20755. this._name = name;
  20756. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20757. this.setRenderList(renderList);
  20758. this._renderTexture.onBeforeRender = beforeRender;
  20759. this._renderTexture.onAfterRender = afterRender;
  20760. this._scene = scene;
  20761. this._renderList = renderList;
  20762. }
  20763. // private
  20764. PostProcessRenderPass.prototype._incRefCount = function () {
  20765. if (this._refCount === 0) {
  20766. this._scene.customRenderTargets.push(this._renderTexture);
  20767. }
  20768. return ++this._refCount;
  20769. };
  20770. PostProcessRenderPass.prototype._decRefCount = function () {
  20771. this._refCount--;
  20772. if (this._refCount <= 0) {
  20773. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20774. }
  20775. return this._refCount;
  20776. };
  20777. PostProcessRenderPass.prototype._update = function () {
  20778. this.setRenderList(this._renderList);
  20779. };
  20780. // public
  20781. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20782. this._renderTexture.renderList = renderList;
  20783. };
  20784. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20785. return this._renderTexture;
  20786. };
  20787. return PostProcessRenderPass;
  20788. })();
  20789. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20790. })(BABYLON || (BABYLON = {}));
  20791. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20792. var BABYLON;
  20793. (function (BABYLON) {
  20794. var PostProcessRenderEffect = (function () {
  20795. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20796. this._engine = engine;
  20797. this._name = name;
  20798. this._singleInstance = singleInstance || true;
  20799. this._getPostProcess = getPostProcess;
  20800. this._cameras = [];
  20801. this._indicesForCamera = [];
  20802. this._postProcesses = {};
  20803. this._renderPasses = {};
  20804. this._renderEffectAsPasses = {};
  20805. }
  20806. PostProcessRenderEffect.prototype._update = function () {
  20807. for (var renderPassName in this._renderPasses) {
  20808. this._renderPasses[renderPassName]._update();
  20809. }
  20810. };
  20811. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20812. this._renderPasses[renderPass._name] = renderPass;
  20813. this._linkParameters();
  20814. };
  20815. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20816. delete this._renderPasses[renderPass._name];
  20817. this._linkParameters();
  20818. };
  20819. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20820. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20821. this._linkParameters();
  20822. };
  20823. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20824. for (var renderPassName in this._renderPasses) {
  20825. if (renderPassName === passName) {
  20826. return this._renderPasses[passName];
  20827. }
  20828. }
  20829. };
  20830. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20831. this._renderPasses = {};
  20832. this._linkParameters();
  20833. };
  20834. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20835. var cameraKey;
  20836. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20837. for (var i = 0; i < _cam.length; i++) {
  20838. var camera = _cam[i];
  20839. var cameraName = camera.name;
  20840. if (this._singleInstance) {
  20841. cameraKey = 0;
  20842. } else {
  20843. cameraKey = cameraName;
  20844. }
  20845. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20846. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20847. if (!this._indicesForCamera[cameraName]) {
  20848. this._indicesForCamera[cameraName] = [];
  20849. }
  20850. this._indicesForCamera[cameraName].push(index);
  20851. if (this._cameras.indexOf(camera) === -1) {
  20852. this._cameras[cameraName] = camera;
  20853. }
  20854. for (var passName in this._renderPasses) {
  20855. this._renderPasses[passName]._incRefCount();
  20856. }
  20857. }
  20858. this._linkParameters();
  20859. };
  20860. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20861. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20862. for (var i = 0; i < _cam.length; i++) {
  20863. var camera = _cam[i];
  20864. var cameraName = camera.name;
  20865. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20866. var index = this._cameras.indexOf(cameraName);
  20867. this._indicesForCamera.splice(index, 1);
  20868. this._cameras.splice(index, 1);
  20869. for (var passName in this._renderPasses) {
  20870. this._renderPasses[passName]._decRefCount();
  20871. }
  20872. }
  20873. };
  20874. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20875. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20876. for (var i = 0; i < _cam.length; i++) {
  20877. var camera = _cam[i];
  20878. var cameraName = camera.name;
  20879. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20880. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20881. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20882. }
  20883. }
  20884. for (var passName in this._renderPasses) {
  20885. this._renderPasses[passName]._incRefCount();
  20886. }
  20887. }
  20888. };
  20889. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20890. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20891. for (var i = 0; i < _cam.length; i++) {
  20892. var camera = _cam[i];
  20893. var cameraName = camera.Name;
  20894. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20895. for (var passName in this._renderPasses) {
  20896. this._renderPasses[passName]._decRefCount();
  20897. }
  20898. }
  20899. };
  20900. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20901. if (this._singleInstance) {
  20902. return this._postProcesses[0];
  20903. } else {
  20904. return this._postProcesses[camera.name];
  20905. }
  20906. };
  20907. PostProcessRenderEffect.prototype._linkParameters = function () {
  20908. var _this = this;
  20909. for (var index in this._postProcesses) {
  20910. if (this.applyParameters) {
  20911. this.applyParameters(this._postProcesses[index]);
  20912. }
  20913. this._postProcesses[index].onBeforeRender = function (effect) {
  20914. _this._linkTextures(effect);
  20915. };
  20916. }
  20917. };
  20918. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20919. for (var renderPassName in this._renderPasses) {
  20920. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20921. }
  20922. for (var renderEffectName in this._renderEffectAsPasses) {
  20923. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20924. }
  20925. };
  20926. return PostProcessRenderEffect;
  20927. })();
  20928. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20929. })(BABYLON || (BABYLON = {}));
  20930. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20931. var BABYLON;
  20932. (function (BABYLON) {
  20933. var PostProcessRenderPipeline = (function () {
  20934. function PostProcessRenderPipeline(engine, name) {
  20935. this._engine = engine;
  20936. this._name = name;
  20937. this._renderEffects = {};
  20938. this._renderEffectsForIsolatedPass = {};
  20939. this._cameras = [];
  20940. }
  20941. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20942. this._renderEffects[renderEffect._name] = renderEffect;
  20943. };
  20944. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20945. var renderEffects = this._renderEffects[renderEffectName];
  20946. if (!renderEffects) {
  20947. return;
  20948. }
  20949. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20950. };
  20951. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20952. var renderEffects = this._renderEffects[renderEffectName];
  20953. if (!renderEffects) {
  20954. return;
  20955. }
  20956. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20957. };
  20958. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20959. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20960. var indicesToDelete = [];
  20961. for (var i = 0; i < _cam.length; i++) {
  20962. var camera = _cam[i];
  20963. var cameraName = camera.name;
  20964. if (this._cameras.indexOf(camera) === -1) {
  20965. this._cameras[cameraName] = camera;
  20966. } else if (unique) {
  20967. indicesToDelete.push(i);
  20968. }
  20969. }
  20970. for (var i = 0; i < indicesToDelete.length; i++) {
  20971. cameras.splice(indicesToDelete[i], 1);
  20972. }
  20973. for (var renderEffectName in this._renderEffects) {
  20974. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20975. }
  20976. };
  20977. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20978. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20979. for (var renderEffectName in this._renderEffects) {
  20980. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20981. }
  20982. for (var i = 0; i < _cam.length; i++) {
  20983. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20984. }
  20985. };
  20986. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20987. var _this = this;
  20988. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20989. var pass = null;
  20990. for (var renderEffectName in this._renderEffects) {
  20991. pass = this._renderEffects[renderEffectName].getPass(passName);
  20992. if (pass != null) {
  20993. break;
  20994. }
  20995. }
  20996. if (pass === null) {
  20997. return;
  20998. }
  20999. for (var renderEffectName in this._renderEffects) {
  21000. this._renderEffects[renderEffectName]._disable(_cam);
  21001. }
  21002. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21003. for (var i = 0; i < _cam.length; i++) {
  21004. var camera = _cam[i];
  21005. var cameraName = camera.name;
  21006. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21007. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21008. });
  21009. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21010. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21011. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21012. }
  21013. };
  21014. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21015. var _this = this;
  21016. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21017. for (var i = 0; i < _cam.length; i++) {
  21018. var camera = _cam[i];
  21019. var cameraName = camera.name;
  21020. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21021. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21022. });
  21023. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21024. }
  21025. for (var renderEffectName in this._renderEffects) {
  21026. this._renderEffects[renderEffectName]._enable(_cam);
  21027. }
  21028. };
  21029. PostProcessRenderPipeline.prototype._update = function () {
  21030. for (var renderEffectName in this._renderEffects) {
  21031. this._renderEffects[renderEffectName]._update();
  21032. }
  21033. for (var i = 0; i < this._cameras.length; i++) {
  21034. var cameraName = this._cameras[i].name;
  21035. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21036. this._renderEffectsForIsolatedPass[cameraName]._update();
  21037. }
  21038. }
  21039. };
  21040. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21041. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21042. return PostProcessRenderPipeline;
  21043. })();
  21044. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21045. })(BABYLON || (BABYLON = {}));
  21046. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  21047. var BABYLON;
  21048. (function (BABYLON) {
  21049. var PostProcessRenderPipelineManager = (function () {
  21050. function PostProcessRenderPipelineManager() {
  21051. this._renderPipelines = {};
  21052. }
  21053. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21054. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21055. };
  21056. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21057. var renderPipeline = this._renderPipelines[renderPipelineName];
  21058. if (!renderPipeline) {
  21059. return;
  21060. }
  21061. renderPipeline._attachCameras(cameras, unique);
  21062. };
  21063. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21064. var renderPipeline = this._renderPipelines[renderPipelineName];
  21065. if (!renderPipeline) {
  21066. return;
  21067. }
  21068. renderPipeline._detachCameras(cameras);
  21069. };
  21070. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21071. var renderPipeline = this._renderPipelines[renderPipelineName];
  21072. if (!renderPipeline) {
  21073. return;
  21074. }
  21075. renderPipeline._enableEffect(renderEffectName, cameras);
  21076. };
  21077. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21078. var renderPipeline = this._renderPipelines[renderPipelineName];
  21079. if (!renderPipeline) {
  21080. return;
  21081. }
  21082. renderPipeline._disableEffect(renderEffectName, cameras);
  21083. };
  21084. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21085. var renderPipeline = this._renderPipelines[renderPipelineName];
  21086. if (!renderPipeline) {
  21087. return;
  21088. }
  21089. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21090. };
  21091. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21092. var renderPipeline = this._renderPipelines[renderPipelineName];
  21093. if (!renderPipeline) {
  21094. return;
  21095. }
  21096. renderPipeline._disableDisplayOnlyPass(cameras);
  21097. };
  21098. PostProcessRenderPipelineManager.prototype.update = function () {
  21099. for (var renderPipelineName in this._renderPipelines) {
  21100. this._renderPipelines[renderPipelineName]._update();
  21101. }
  21102. };
  21103. return PostProcessRenderPipelineManager;
  21104. })();
  21105. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21106. })(BABYLON || (BABYLON = {}));
  21107. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21108. var BABYLON;
  21109. (function (BABYLON) {
  21110. var DisplayPassPostProcess = (function (_super) {
  21111. __extends(DisplayPassPostProcess, _super);
  21112. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21113. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21114. }
  21115. return DisplayPassPostProcess;
  21116. })(BABYLON.PostProcess);
  21117. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21118. })(BABYLON || (BABYLON = {}));
  21119. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  21120. var BABYLON;
  21121. (function (BABYLON) {
  21122. var BoundingBoxRenderer = (function () {
  21123. function BoundingBoxRenderer(scene) {
  21124. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21125. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21126. this.showBackLines = true;
  21127. this.renderList = new BABYLON.SmartArray(32);
  21128. this._scene = scene;
  21129. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21130. attributes: ["position"],
  21131. uniforms: ["worldViewProjection", "color"]
  21132. });
  21133. var engine = this._scene.getEngine();
  21134. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21135. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21136. 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]);
  21137. }
  21138. BoundingBoxRenderer.prototype.reset = function () {
  21139. this.renderList.reset();
  21140. };
  21141. BoundingBoxRenderer.prototype.render = function () {
  21142. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21143. return;
  21144. }
  21145. var engine = this._scene.getEngine();
  21146. engine.setDepthWrite(false);
  21147. this._colorShader._preBind();
  21148. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21149. var boundingBox = this.renderList.data[boundingBoxIndex];
  21150. var min = boundingBox.minimum;
  21151. var max = boundingBox.maximum;
  21152. var diff = max.subtract(min);
  21153. var median = min.add(diff.scale(0.5));
  21154. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21155. // VBOs
  21156. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21157. if (this.showBackLines) {
  21158. // Back
  21159. engine.setDepthFunctionToGreaterOrEqual();
  21160. this._scene.resetCachedMaterial();
  21161. this._colorShader.setColor4("color", this.backColor.toColor4());
  21162. this._colorShader.bind(worldMatrix);
  21163. // Draw order
  21164. engine.draw(false, 0, 24);
  21165. }
  21166. // Front
  21167. engine.setDepthFunctionToLess();
  21168. this._scene.resetCachedMaterial();
  21169. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21170. this._colorShader.bind(worldMatrix);
  21171. // Draw order
  21172. engine.draw(false, 0, 24);
  21173. }
  21174. this._colorShader.unbind();
  21175. engine.setDepthFunctionToLessOrEqual();
  21176. engine.setDepthWrite(true);
  21177. };
  21178. BoundingBoxRenderer.prototype.dispose = function () {
  21179. this._colorShader.dispose();
  21180. this._vb.dispose();
  21181. this._scene.getEngine()._releaseBuffer(this._ib);
  21182. };
  21183. return BoundingBoxRenderer;
  21184. })();
  21185. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21186. })(BABYLON || (BABYLON = {}));
  21187. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  21188. /**
  21189. * Based on jsTGALoader - Javascript loader for TGA file
  21190. * By Vincent Thibault
  21191. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21192. */
  21193. var BABYLON;
  21194. (function (BABYLON) {
  21195. (function (Internals) {
  21196. var TGATools = (function () {
  21197. function TGATools() {
  21198. }
  21199. TGATools.GetTGAHeader = function (data) {
  21200. var offset = 0;
  21201. var header = {
  21202. id_length: data[offset++],
  21203. colormap_type: data[offset++],
  21204. image_type: data[offset++],
  21205. colormap_index: data[offset++] | data[offset++] << 8,
  21206. colormap_length: data[offset++] | data[offset++] << 8,
  21207. colormap_size: data[offset++],
  21208. origin: [
  21209. data[offset++] | data[offset++] << 8,
  21210. data[offset++] | data[offset++] << 8
  21211. ],
  21212. width: data[offset++] | data[offset++] << 8,
  21213. height: data[offset++] | data[offset++] << 8,
  21214. pixel_size: data[offset++],
  21215. flags: data[offset++]
  21216. };
  21217. return header;
  21218. };
  21219. TGATools.UploadContent = function (gl, data) {
  21220. // Not enough data to contain header ?
  21221. if (data.length < 19) {
  21222. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21223. return;
  21224. }
  21225. // Read Header
  21226. var offset = 18;
  21227. var header = TGATools.GetTGAHeader(data);
  21228. // Assume it's a valid Targa file.
  21229. if (header.id_length + offset > data.length) {
  21230. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21231. return;
  21232. }
  21233. // Skip not needed data
  21234. offset += header.id_length;
  21235. var use_rle = false;
  21236. var use_pal = false;
  21237. var use_rgb = false;
  21238. var use_grey = false;
  21239. switch (header.image_type) {
  21240. case TGATools._TYPE_RLE_INDEXED:
  21241. use_rle = true;
  21242. case TGATools._TYPE_INDEXED:
  21243. use_pal = true;
  21244. break;
  21245. case TGATools._TYPE_RLE_RGB:
  21246. use_rle = true;
  21247. case TGATools._TYPE_RGB:
  21248. use_rgb = true;
  21249. break;
  21250. case TGATools._TYPE_RLE_GREY:
  21251. use_rle = true;
  21252. case TGATools._TYPE_GREY:
  21253. use_grey = true;
  21254. break;
  21255. }
  21256. var pixel_data;
  21257. var numAlphaBits = header.flags & 0xf;
  21258. var pixel_size = header.pixel_size >> 3;
  21259. var pixel_total = header.width * header.height * pixel_size;
  21260. // Read palettes
  21261. var palettes;
  21262. if (use_pal) {
  21263. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21264. }
  21265. // Read LRE
  21266. if (use_rle) {
  21267. pixel_data = new Uint8Array(pixel_total);
  21268. var c, count, i;
  21269. var localOffset = 0;
  21270. var pixels = new Uint8Array(pixel_size);
  21271. while (offset < pixel_total && localOffset < pixel_total) {
  21272. c = data[offset++];
  21273. count = (c & 0x7f) + 1;
  21274. // RLE pixels
  21275. if (c & 0x80) {
  21276. for (i = 0; i < pixel_size; ++i) {
  21277. pixels[i] = data[offset++];
  21278. }
  21279. for (i = 0; i < count; ++i) {
  21280. pixel_data.set(pixels, localOffset + i * pixel_size);
  21281. }
  21282. localOffset += pixel_size * count;
  21283. } else {
  21284. count *= pixel_size;
  21285. for (i = 0; i < count; ++i) {
  21286. pixel_data[localOffset + i] = data[offset++];
  21287. }
  21288. localOffset += count;
  21289. }
  21290. }
  21291. } else {
  21292. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21293. }
  21294. // Load to texture
  21295. var x_start, y_start, x_step, y_step, y_end, x_end;
  21296. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21297. default:
  21298. case TGATools._ORIGIN_UL:
  21299. x_start = 0;
  21300. x_step = 1;
  21301. x_end = header.width;
  21302. y_start = 0;
  21303. y_step = 1;
  21304. y_end = header.height;
  21305. break;
  21306. case TGATools._ORIGIN_BL:
  21307. x_start = 0;
  21308. x_step = 1;
  21309. x_end = header.width;
  21310. y_start = header.height - 1;
  21311. y_step = -1;
  21312. y_end = -1;
  21313. break;
  21314. case TGATools._ORIGIN_UR:
  21315. x_start = header.width - 1;
  21316. x_step = -1;
  21317. x_end = -1;
  21318. y_start = 0;
  21319. y_step = 1;
  21320. y_end = header.height;
  21321. break;
  21322. case TGATools._ORIGIN_BR:
  21323. x_start = header.width - 1;
  21324. x_step = -1;
  21325. x_end = -1;
  21326. y_start = header.height - 1;
  21327. y_step = -1;
  21328. y_end = -1;
  21329. break;
  21330. }
  21331. // Load the specify method
  21332. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21333. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21334. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21335. };
  21336. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21337. var image = pixel_data, colormap = palettes;
  21338. var width = header.width, height = header.height;
  21339. var color, i = 0, x, y;
  21340. var imageData = new Uint8Array(width * height * 4);
  21341. for (y = y_start; y !== y_end; y += y_step) {
  21342. for (x = x_start; x !== x_end; x += x_step, i++) {
  21343. color = image[i];
  21344. imageData[(x + width * y) * 4 + 3] = 255;
  21345. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21346. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21347. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21348. }
  21349. }
  21350. return imageData;
  21351. };
  21352. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21353. var image = pixel_data;
  21354. var width = header.width, height = header.height;
  21355. var color, i = 0, x, y;
  21356. var imageData = new Uint8Array(width * height * 4);
  21357. for (y = y_start; y !== y_end; y += y_step) {
  21358. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21359. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21360. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21361. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21362. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21363. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21364. }
  21365. }
  21366. return imageData;
  21367. };
  21368. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21369. var image = pixel_data;
  21370. var width = header.width, height = header.height;
  21371. var i = 0, x, y;
  21372. var imageData = new Uint8Array(width * height * 4);
  21373. for (y = y_start; y !== y_end; y += y_step) {
  21374. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21375. imageData[(x + width * y) * 4 + 3] = 255;
  21376. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21377. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21378. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21379. }
  21380. }
  21381. return imageData;
  21382. };
  21383. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21384. var image = pixel_data;
  21385. var width = header.width, height = header.height;
  21386. var i = 0, x, y;
  21387. var imageData = new Uint8Array(width * height * 4);
  21388. for (y = y_start; y !== y_end; y += y_step) {
  21389. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21390. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21391. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21392. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21393. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21394. }
  21395. }
  21396. return imageData;
  21397. };
  21398. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21399. var image = pixel_data;
  21400. var width = header.width, height = header.height;
  21401. var color, i = 0, x, y;
  21402. var imageData = new Uint8Array(width * height * 4);
  21403. for (y = y_start; y !== y_end; y += y_step) {
  21404. for (x = x_start; x !== x_end; x += x_step, i++) {
  21405. color = image[i];
  21406. imageData[(x + width * y) * 4 + 0] = color;
  21407. imageData[(x + width * y) * 4 + 1] = color;
  21408. imageData[(x + width * y) * 4 + 2] = color;
  21409. imageData[(x + width * y) * 4 + 3] = 255;
  21410. }
  21411. }
  21412. return imageData;
  21413. };
  21414. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21415. var image = pixel_data;
  21416. var width = header.width, height = header.height;
  21417. var i = 0, x, y;
  21418. var imageData = new Uint8Array(width * height * 4);
  21419. for (y = y_start; y !== y_end; y += y_step) {
  21420. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21421. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21422. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21423. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21424. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21425. }
  21426. }
  21427. return imageData;
  21428. };
  21429. TGATools._TYPE_NO_DATA = 0;
  21430. TGATools._TYPE_INDEXED = 1;
  21431. TGATools._TYPE_RGB = 2;
  21432. TGATools._TYPE_GREY = 3;
  21433. TGATools._TYPE_RLE_INDEXED = 9;
  21434. TGATools._TYPE_RLE_RGB = 10;
  21435. TGATools._TYPE_RLE_GREY = 11;
  21436. TGATools._ORIGIN_MASK = 0x30;
  21437. TGATools._ORIGIN_SHIFT = 0x04;
  21438. TGATools._ORIGIN_BL = 0x00;
  21439. TGATools._ORIGIN_BR = 0x01;
  21440. TGATools._ORIGIN_UL = 0x02;
  21441. TGATools._ORIGIN_UR = 0x03;
  21442. return TGATools;
  21443. })();
  21444. Internals.TGATools = TGATools;
  21445. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21446. var Internals = BABYLON.Internals;
  21447. })(BABYLON || (BABYLON = {}));
  21448. //# sourceMappingURL=babylon.tools.tga.js.map
  21449. var BABYLON;
  21450. (function (BABYLON) {
  21451. (function (Internals) {
  21452. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21453. // All values and structures referenced from:
  21454. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21455. var DDS_MAGIC = 0x20534444;
  21456. 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;
  21457. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21458. 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;
  21459. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21460. function FourCCToInt32(value) {
  21461. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21462. }
  21463. function Int32ToFourCC(value) {
  21464. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21465. }
  21466. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21467. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21468. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21469. var headerLengthInt = 31;
  21470. // Offsets into the header array
  21471. var off_magic = 0;
  21472. var off_size = 1;
  21473. var off_flags = 2;
  21474. var off_height = 3;
  21475. var off_width = 4;
  21476. var off_mipmapCount = 7;
  21477. var off_pfFlags = 20;
  21478. var off_pfFourCC = 21;
  21479. var off_RGBbpp = 22;
  21480. var off_RMask = 23;
  21481. var off_GMask = 24;
  21482. var off_BMask = 25;
  21483. var off_AMask = 26;
  21484. var off_caps1 = 27;
  21485. var off_caps2 = 28;
  21486. ;
  21487. var DDSTools = (function () {
  21488. function DDSTools() {
  21489. }
  21490. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21491. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21492. var mipmapCount = 1;
  21493. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21494. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21495. }
  21496. return {
  21497. width: header[off_width],
  21498. height: header[off_height],
  21499. mipmapCount: mipmapCount,
  21500. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21501. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21502. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21503. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21504. };
  21505. };
  21506. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21507. var byteArray = new Uint8Array(dataLength);
  21508. var srcData = new Uint8Array(arrayBuffer);
  21509. var index = 0;
  21510. for (var y = height - 1; y >= 0; y--) {
  21511. for (var x = 0; x < width; x++) {
  21512. var srcPos = dataOffset + (x + y * width) * 4;
  21513. byteArray[index + 2] = srcData[srcPos];
  21514. byteArray[index + 1] = srcData[srcPos + 1];
  21515. byteArray[index] = srcData[srcPos + 2];
  21516. byteArray[index + 3] = srcData[srcPos + 3];
  21517. index += 4;
  21518. }
  21519. }
  21520. return byteArray;
  21521. };
  21522. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21523. var byteArray = new Uint8Array(dataLength);
  21524. var srcData = new Uint8Array(arrayBuffer);
  21525. var index = 0;
  21526. for (var y = height - 1; y >= 0; y--) {
  21527. for (var x = 0; x < width; x++) {
  21528. var srcPos = dataOffset + (x + y * width) * 3;
  21529. byteArray[index + 2] = srcData[srcPos];
  21530. byteArray[index + 1] = srcData[srcPos + 1];
  21531. byteArray[index] = srcData[srcPos + 2];
  21532. index += 3;
  21533. }
  21534. }
  21535. return byteArray;
  21536. };
  21537. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21538. var byteArray = new Uint8Array(dataLength);
  21539. var srcData = new Uint8Array(arrayBuffer);
  21540. var index = 0;
  21541. for (var y = height - 1; y >= 0; y--) {
  21542. for (var x = 0; x < width; x++) {
  21543. var srcPos = dataOffset + (x + y * width);
  21544. byteArray[index] = srcData[srcPos];
  21545. index++;
  21546. }
  21547. }
  21548. return byteArray;
  21549. };
  21550. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21551. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21552. if (header[off_magic] != DDS_MAGIC) {
  21553. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21554. return;
  21555. }
  21556. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21557. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21558. return;
  21559. }
  21560. if (info.isFourCC) {
  21561. fourCC = header[off_pfFourCC];
  21562. switch (fourCC) {
  21563. case FOURCC_DXT1:
  21564. blockBytes = 8;
  21565. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21566. break;
  21567. case FOURCC_DXT3:
  21568. blockBytes = 16;
  21569. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21570. break;
  21571. case FOURCC_DXT5:
  21572. blockBytes = 16;
  21573. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21574. break;
  21575. default:
  21576. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21577. return;
  21578. }
  21579. }
  21580. mipmapCount = 1;
  21581. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21582. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21583. }
  21584. var bpp = header[off_RGBbpp];
  21585. for (var face = 0; face < faces; face++) {
  21586. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21587. width = header[off_width];
  21588. height = header[off_height];
  21589. dataOffset = header[off_size] + 4;
  21590. for (i = 0; i < mipmapCount; ++i) {
  21591. if (info.isRGB) {
  21592. if (bpp == 24) {
  21593. dataLength = width * height * 3;
  21594. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21595. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21596. } else {
  21597. dataLength = width * height * 4;
  21598. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21599. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21600. }
  21601. } else if (info.isLuminance) {
  21602. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21603. var unpaddedRowSize = width;
  21604. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21605. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21606. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21607. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21608. } else {
  21609. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21610. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21611. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21612. }
  21613. dataOffset += dataLength;
  21614. width *= 0.5;
  21615. height *= 0.5;
  21616. width = Math.max(1.0, width);
  21617. height = Math.max(1.0, height);
  21618. }
  21619. }
  21620. };
  21621. return DDSTools;
  21622. })();
  21623. Internals.DDSTools = DDSTools;
  21624. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21625. var Internals = BABYLON.Internals;
  21626. })(BABYLON || (BABYLON = {}));
  21627. //# sourceMappingURL=babylon.tools.dds.js.map
  21628. var BABYLON;
  21629. (function (BABYLON) {
  21630. var SmartArray = (function () {
  21631. function SmartArray(capacity) {
  21632. this.length = 0;
  21633. this._duplicateId = 0;
  21634. this.data = new Array(capacity);
  21635. this._id = SmartArray._GlobalId++;
  21636. }
  21637. SmartArray.prototype.push = function (value) {
  21638. this.data[this.length++] = value;
  21639. if (this.length > this.data.length) {
  21640. this.data.length *= 2;
  21641. }
  21642. if (!value.__smartArrayFlags) {
  21643. value.__smartArrayFlags = {};
  21644. }
  21645. value.__smartArrayFlags[this._id] = this._duplicateId;
  21646. };
  21647. SmartArray.prototype.pushNoDuplicate = function (value) {
  21648. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21649. return;
  21650. }
  21651. this.push(value);
  21652. };
  21653. SmartArray.prototype.sort = function (compareFn) {
  21654. this.data.sort(compareFn);
  21655. };
  21656. SmartArray.prototype.reset = function () {
  21657. this.length = 0;
  21658. this._duplicateId++;
  21659. };
  21660. SmartArray.prototype.concat = function (array) {
  21661. if (array.length === 0) {
  21662. return;
  21663. }
  21664. if (this.length + array.length > this.data.length) {
  21665. this.data.length = (this.length + array.length) * 2;
  21666. }
  21667. for (var index = 0; index < array.length; index++) {
  21668. this.data[this.length++] = (array.data || array)[index];
  21669. }
  21670. };
  21671. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21672. if (array.length === 0) {
  21673. return;
  21674. }
  21675. if (this.length + array.length > this.data.length) {
  21676. this.data.length = (this.length + array.length) * 2;
  21677. }
  21678. for (var index = 0; index < array.length; index++) {
  21679. var item = (array.data || array)[index];
  21680. this.pushNoDuplicate(item);
  21681. }
  21682. };
  21683. SmartArray.prototype.indexOf = function (value) {
  21684. var position = this.data.indexOf(value);
  21685. if (position >= this.length) {
  21686. return -1;
  21687. }
  21688. return position;
  21689. };
  21690. SmartArray._GlobalId = 0;
  21691. return SmartArray;
  21692. })();
  21693. BABYLON.SmartArray = SmartArray;
  21694. })(BABYLON || (BABYLON = {}));
  21695. //# sourceMappingURL=babylon.smartArray.js.map
  21696. var BABYLON;
  21697. (function (BABYLON) {
  21698. var CannonJSPlugin = (function () {
  21699. function CannonJSPlugin() {
  21700. this._registeredMeshes = [];
  21701. this._physicsMaterials = [];
  21702. this.updateBodyPosition = function (mesh) {
  21703. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21704. var registeredMesh = this._registeredMeshes[index];
  21705. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21706. var body = registeredMesh.body;
  21707. var center = mesh.getBoundingInfo().boundingBox.center;
  21708. body.position.set(center.x, center.z, center.y);
  21709. body.quaternion.x = mesh.rotationQuaternion.x;
  21710. body.quaternion.z = mesh.rotationQuaternion.y;
  21711. body.quaternion.y = mesh.rotationQuaternion.z;
  21712. body.quaternion.w = -mesh.rotationQuaternion.w;
  21713. return;
  21714. }
  21715. }
  21716. };
  21717. }
  21718. CannonJSPlugin.prototype.initialize = function (iterations) {
  21719. if (typeof iterations === "undefined") { iterations = 10; }
  21720. this._world = new CANNON.World();
  21721. this._world.broadphase = new CANNON.NaiveBroadphase();
  21722. this._world.solver.iterations = iterations;
  21723. };
  21724. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21725. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21726. };
  21727. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21728. this._world.step(delta);
  21729. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21730. var registeredMesh = this._registeredMeshes[index];
  21731. if (registeredMesh.isChild) {
  21732. continue;
  21733. }
  21734. // Body position
  21735. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21736. var deltaPos = registeredMesh.delta;
  21737. if (deltaPos) {
  21738. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21739. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21740. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21741. } else {
  21742. registeredMesh.mesh.position.x = bodyX;
  21743. registeredMesh.mesh.position.y = bodyZ;
  21744. registeredMesh.mesh.position.z = bodyY;
  21745. }
  21746. if (!registeredMesh.mesh.rotationQuaternion) {
  21747. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21748. }
  21749. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21750. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21751. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21752. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21753. }
  21754. };
  21755. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21756. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21757. };
  21758. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21759. this.unregisterMesh(mesh);
  21760. mesh.computeWorldMatrix(true);
  21761. switch (impostor) {
  21762. case BABYLON.PhysicsEngine.SphereImpostor:
  21763. var bbox = mesh.getBoundingInfo().boundingBox;
  21764. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21765. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21766. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21767. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21768. case BABYLON.PhysicsEngine.BoxImpostor:
  21769. bbox = mesh.getBoundingInfo().boundingBox;
  21770. var min = bbox.minimumWorld;
  21771. var max = bbox.maximumWorld;
  21772. var box = max.subtract(min).scale(0.5);
  21773. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21774. case BABYLON.PhysicsEngine.PlaneImpostor:
  21775. return this._createPlane(mesh, options);
  21776. case BABYLON.PhysicsEngine.MeshImpostor:
  21777. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21778. var rawFaces = mesh.getIndices();
  21779. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21780. }
  21781. return null;
  21782. };
  21783. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21784. var shape = new CANNON.Sphere(radius);
  21785. if (!options) {
  21786. return shape;
  21787. }
  21788. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21789. };
  21790. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21791. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21792. if (!options) {
  21793. return shape;
  21794. }
  21795. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21796. };
  21797. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21798. var shape = new CANNON.Plane();
  21799. if (!options) {
  21800. return shape;
  21801. }
  21802. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21803. };
  21804. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21805. var verts = [], faces = [];
  21806. mesh.computeWorldMatrix(true);
  21807. for (var i = 0; i < rawVerts.length; i += 3) {
  21808. var transformed = BABYLON.Vector3.Zero();
  21809. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21810. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21811. }
  21812. for (var j = 0; j < rawFaces.length; j += 3) {
  21813. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21814. }
  21815. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21816. if (!options) {
  21817. return shape;
  21818. }
  21819. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21820. };
  21821. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21822. var index;
  21823. var mat;
  21824. for (index = 0; index < this._physicsMaterials.length; index++) {
  21825. mat = this._physicsMaterials[index];
  21826. if (mat.friction === friction && mat.restitution === restitution) {
  21827. return mat;
  21828. }
  21829. }
  21830. var currentMat = new CANNON.Material();
  21831. currentMat.friction = friction;
  21832. currentMat.restitution = restitution;
  21833. this._physicsMaterials.push(currentMat);
  21834. for (index = 0; index < this._physicsMaterials.length; index++) {
  21835. mat = this._physicsMaterials[index];
  21836. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21837. contactMaterial.contactEquationStiffness = 1e10;
  21838. contactMaterial.contactEquationRegularizationTime = 10;
  21839. this._world.addContactMaterial(contactMaterial);
  21840. }
  21841. return currentMat;
  21842. };
  21843. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21844. var initialRotation = null;
  21845. if (mesh.rotationQuaternion) {
  21846. initialRotation = mesh.rotationQuaternion.clone();
  21847. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21848. }
  21849. // The delta between the mesh position and the mesh bounding box center
  21850. var bbox = mesh.getBoundingInfo().boundingBox;
  21851. var deltaPosition = mesh.position.subtract(bbox.center);
  21852. var material = this._addMaterial(friction, restitution);
  21853. var body = new CANNON.RigidBody(mass, shape, material);
  21854. if (initialRotation) {
  21855. body.quaternion.x = initialRotation.x;
  21856. body.quaternion.z = initialRotation.y;
  21857. body.quaternion.y = initialRotation.z;
  21858. body.quaternion.w = -initialRotation.w;
  21859. }
  21860. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21861. this._world.add(body);
  21862. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21863. return body;
  21864. };
  21865. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21866. var compoundShape = new CANNON.Compound();
  21867. for (var index = 0; index < parts.length; index++) {
  21868. var mesh = parts[index].mesh;
  21869. var shape = this.registerMesh(mesh, parts[index].impostor);
  21870. if (index == 0) {
  21871. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21872. } else {
  21873. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21874. }
  21875. }
  21876. var initialMesh = parts[0].mesh;
  21877. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21878. body.parts = parts;
  21879. return body;
  21880. };
  21881. CannonJSPlugin.prototype._unbindBody = function (body) {
  21882. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21883. var registeredMesh = this._registeredMeshes[index];
  21884. if (registeredMesh.body === body) {
  21885. registeredMesh.body = null;
  21886. registeredMesh.delta = 0;
  21887. }
  21888. }
  21889. };
  21890. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21891. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21892. var registeredMesh = this._registeredMeshes[index];
  21893. if (registeredMesh.mesh === mesh) {
  21894. // Remove body
  21895. if (registeredMesh.body) {
  21896. this._world.remove(registeredMesh.body);
  21897. this._unbindBody(registeredMesh.body);
  21898. }
  21899. this._registeredMeshes.splice(index, 1);
  21900. return;
  21901. }
  21902. }
  21903. };
  21904. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21905. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21906. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21907. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21908. var registeredMesh = this._registeredMeshes[index];
  21909. if (registeredMesh.mesh === mesh) {
  21910. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21911. return;
  21912. }
  21913. }
  21914. };
  21915. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21916. var body1 = null, body2 = null;
  21917. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21918. var registeredMesh = this._registeredMeshes[index];
  21919. if (registeredMesh.mesh === mesh1) {
  21920. body1 = registeredMesh.body;
  21921. } else if (registeredMesh.mesh === mesh2) {
  21922. body2 = registeredMesh.body;
  21923. }
  21924. }
  21925. if (!body1 || !body2) {
  21926. return false;
  21927. }
  21928. 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));
  21929. this._world.addConstraint(constraint);
  21930. return true;
  21931. };
  21932. CannonJSPlugin.prototype.dispose = function () {
  21933. while (this._registeredMeshes.length) {
  21934. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21935. }
  21936. };
  21937. CannonJSPlugin.prototype.isSupported = function () {
  21938. return window.CANNON !== undefined;
  21939. };
  21940. return CannonJSPlugin;
  21941. })();
  21942. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21943. })(BABYLON || (BABYLON = {}));
  21944. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21945. var BABYLON;
  21946. (function (BABYLON) {
  21947. var Condition = (function () {
  21948. function Condition(actionManager) {
  21949. this._actionManager = actionManager;
  21950. }
  21951. Condition.prototype.isValid = function () {
  21952. return true;
  21953. };
  21954. Condition.prototype._getProperty = function (propertyPath) {
  21955. return this._actionManager._getProperty(propertyPath);
  21956. };
  21957. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21958. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21959. };
  21960. return Condition;
  21961. })();
  21962. BABYLON.Condition = Condition;
  21963. var ValueCondition = (function (_super) {
  21964. __extends(ValueCondition, _super);
  21965. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21966. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21967. _super.call(this, actionManager);
  21968. this.propertyPath = propertyPath;
  21969. this.value = value;
  21970. this.operator = operator;
  21971. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21972. this._property = this._getProperty(this.propertyPath);
  21973. }
  21974. Object.defineProperty(ValueCondition, "IsEqual", {
  21975. get: function () {
  21976. return ValueCondition._IsEqual;
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(ValueCondition, "IsDifferent", {
  21982. get: function () {
  21983. return ValueCondition._IsDifferent;
  21984. },
  21985. enumerable: true,
  21986. configurable: true
  21987. });
  21988. Object.defineProperty(ValueCondition, "IsGreater", {
  21989. get: function () {
  21990. return ValueCondition._IsGreater;
  21991. },
  21992. enumerable: true,
  21993. configurable: true
  21994. });
  21995. Object.defineProperty(ValueCondition, "IsLesser", {
  21996. get: function () {
  21997. return ValueCondition._IsLesser;
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. // Methods
  22003. ValueCondition.prototype.isValid = function () {
  22004. switch (this.operator) {
  22005. case ValueCondition.IsGreater:
  22006. return this._target[this._property] > this.value;
  22007. case ValueCondition.IsLesser:
  22008. return this._target[this._property] < this.value;
  22009. case ValueCondition.IsEqual:
  22010. case ValueCondition.IsDifferent:
  22011. var check;
  22012. if (this.value.equals) {
  22013. check = this.value.equals(this._target[this._property]);
  22014. } else {
  22015. check = this.value === this._target[this._property];
  22016. }
  22017. return this.operator === ValueCondition.IsEqual ? check : !check;
  22018. }
  22019. return false;
  22020. };
  22021. ValueCondition._IsEqual = 0;
  22022. ValueCondition._IsDifferent = 1;
  22023. ValueCondition._IsGreater = 2;
  22024. ValueCondition._IsLesser = 3;
  22025. return ValueCondition;
  22026. })(Condition);
  22027. BABYLON.ValueCondition = ValueCondition;
  22028. var PredicateCondition = (function (_super) {
  22029. __extends(PredicateCondition, _super);
  22030. function PredicateCondition(actionManager, predicate) {
  22031. _super.call(this, actionManager);
  22032. this.predicate = predicate;
  22033. }
  22034. PredicateCondition.prototype.isValid = function () {
  22035. return this.predicate();
  22036. };
  22037. return PredicateCondition;
  22038. })(Condition);
  22039. BABYLON.PredicateCondition = PredicateCondition;
  22040. var StateCondition = (function (_super) {
  22041. __extends(StateCondition, _super);
  22042. function StateCondition(actionManager, target, value) {
  22043. _super.call(this, actionManager);
  22044. this.value = value;
  22045. this._target = target;
  22046. }
  22047. // Methods
  22048. StateCondition.prototype.isValid = function () {
  22049. return this._target.state === this.value;
  22050. };
  22051. return StateCondition;
  22052. })(Condition);
  22053. BABYLON.StateCondition = StateCondition;
  22054. })(BABYLON || (BABYLON = {}));
  22055. //# sourceMappingURL=babylon.condition.js.map
  22056. var BABYLON;
  22057. (function (BABYLON) {
  22058. var Action = (function () {
  22059. function Action(triggerOptions, condition) {
  22060. this.triggerOptions = triggerOptions;
  22061. if (triggerOptions.parameter) {
  22062. this.trigger = triggerOptions.trigger;
  22063. this._triggerParameter = triggerOptions.parameter;
  22064. } else {
  22065. this.trigger = triggerOptions;
  22066. }
  22067. this._nextActiveAction = this;
  22068. this._condition = condition;
  22069. }
  22070. // Methods
  22071. Action.prototype._prepare = function () {
  22072. };
  22073. Action.prototype.getTriggerParameter = function () {
  22074. return this._triggerParameter;
  22075. };
  22076. Action.prototype._executeCurrent = function (evt) {
  22077. if (this._condition) {
  22078. var currentRenderId = this._actionManager.getScene().getRenderId();
  22079. // We cache the current evaluation for the current frame
  22080. if (this._condition._evaluationId === currentRenderId) {
  22081. if (!this._condition._currentResult) {
  22082. return;
  22083. }
  22084. } else {
  22085. this._condition._evaluationId = currentRenderId;
  22086. if (!this._condition.isValid()) {
  22087. this._condition._currentResult = false;
  22088. return;
  22089. }
  22090. this._condition._currentResult = true;
  22091. }
  22092. }
  22093. this._nextActiveAction.execute(evt);
  22094. if (this._nextActiveAction._child) {
  22095. if (!this._nextActiveAction._child._actionManager) {
  22096. this._nextActiveAction._child._actionManager = this._actionManager;
  22097. }
  22098. this._nextActiveAction = this._nextActiveAction._child;
  22099. } else {
  22100. this._nextActiveAction = this;
  22101. }
  22102. };
  22103. Action.prototype.execute = function (evt) {
  22104. };
  22105. Action.prototype.then = function (action) {
  22106. this._child = action;
  22107. action._actionManager = this._actionManager;
  22108. action._prepare();
  22109. return action;
  22110. };
  22111. Action.prototype._getProperty = function (propertyPath) {
  22112. return this._actionManager._getProperty(propertyPath);
  22113. };
  22114. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22115. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22116. };
  22117. return Action;
  22118. })();
  22119. BABYLON.Action = Action;
  22120. })(BABYLON || (BABYLON = {}));
  22121. //# sourceMappingURL=babylon.action.js.map
  22122. var BABYLON;
  22123. (function (BABYLON) {
  22124. var ActionEvent = (function () {
  22125. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22126. this.source = source;
  22127. this.pointerX = pointerX;
  22128. this.pointerY = pointerY;
  22129. this.meshUnderPointer = meshUnderPointer;
  22130. this.sourceEvent = sourceEvent;
  22131. }
  22132. ActionEvent.CreateNew = function (source, evt) {
  22133. var scene = source.getScene();
  22134. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22135. };
  22136. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22137. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22138. };
  22139. return ActionEvent;
  22140. })();
  22141. BABYLON.ActionEvent = ActionEvent;
  22142. var ActionManager = (function () {
  22143. function ActionManager(scene) {
  22144. // Members
  22145. this.actions = new Array();
  22146. this._scene = scene;
  22147. scene._actionManagers.push(this);
  22148. }
  22149. Object.defineProperty(ActionManager, "NothingTrigger", {
  22150. get: function () {
  22151. return ActionManager._NothingTrigger;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22157. get: function () {
  22158. return ActionManager._OnPickTrigger;
  22159. },
  22160. enumerable: true,
  22161. configurable: true
  22162. });
  22163. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22164. get: function () {
  22165. return ActionManager._OnLeftPickTrigger;
  22166. },
  22167. enumerable: true,
  22168. configurable: true
  22169. });
  22170. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22171. get: function () {
  22172. return ActionManager._OnRightPickTrigger;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22178. get: function () {
  22179. return ActionManager._OnCenterPickTrigger;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22185. get: function () {
  22186. return ActionManager._OnPointerOverTrigger;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22192. get: function () {
  22193. return ActionManager._OnPointerOutTrigger;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22199. get: function () {
  22200. return ActionManager._OnEveryFrameTrigger;
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22206. get: function () {
  22207. return ActionManager._OnIntersectionEnterTrigger;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22213. get: function () {
  22214. return ActionManager._OnIntersectionExitTrigger;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22220. get: function () {
  22221. return ActionManager._OnKeyDownTrigger;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22227. get: function () {
  22228. return ActionManager._OnKeyUpTrigger;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. // Methods
  22234. ActionManager.prototype.dispose = function () {
  22235. var index = this._scene._actionManagers.indexOf(this);
  22236. if (index > -1) {
  22237. this._scene._actionManagers.splice(index, 1);
  22238. }
  22239. };
  22240. ActionManager.prototype.getScene = function () {
  22241. return this._scene;
  22242. };
  22243. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22244. for (var index = 0; index < this.actions.length; index++) {
  22245. var action = this.actions[index];
  22246. if (triggers.indexOf(action.trigger) > -1) {
  22247. return true;
  22248. }
  22249. }
  22250. return false;
  22251. };
  22252. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22253. get: function () {
  22254. for (var index = 0; index < this.actions.length; index++) {
  22255. var action = this.actions[index];
  22256. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22257. return true;
  22258. }
  22259. }
  22260. return false;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22266. get: function () {
  22267. for (var index = 0; index < this.actions.length; index++) {
  22268. var action = this.actions[index];
  22269. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22270. return true;
  22271. }
  22272. }
  22273. return false;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. ActionManager.prototype.registerAction = function (action) {
  22279. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22280. if (this.getScene().actionManager !== this) {
  22281. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22282. return null;
  22283. }
  22284. }
  22285. this.actions.push(action);
  22286. action._actionManager = this;
  22287. action._prepare();
  22288. return action;
  22289. };
  22290. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22291. for (var index = 0; index < this.actions.length; index++) {
  22292. var action = this.actions[index];
  22293. if (action.trigger === trigger) {
  22294. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22295. var parameter = action.getTriggerParameter();
  22296. if (parameter) {
  22297. if (evt.sourceEvent.key !== parameter) {
  22298. continue;
  22299. }
  22300. }
  22301. }
  22302. action._executeCurrent(evt);
  22303. }
  22304. }
  22305. };
  22306. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22307. var properties = propertyPath.split(".");
  22308. for (var index = 0; index < properties.length - 1; index++) {
  22309. target = target[properties[index]];
  22310. }
  22311. return target;
  22312. };
  22313. ActionManager.prototype._getProperty = function (propertyPath) {
  22314. var properties = propertyPath.split(".");
  22315. return properties[properties.length - 1];
  22316. };
  22317. ActionManager._NothingTrigger = 0;
  22318. ActionManager._OnPickTrigger = 1;
  22319. ActionManager._OnLeftPickTrigger = 2;
  22320. ActionManager._OnRightPickTrigger = 3;
  22321. ActionManager._OnCenterPickTrigger = 4;
  22322. ActionManager._OnPointerOverTrigger = 5;
  22323. ActionManager._OnPointerOutTrigger = 6;
  22324. ActionManager._OnEveryFrameTrigger = 7;
  22325. ActionManager._OnIntersectionEnterTrigger = 8;
  22326. ActionManager._OnIntersectionExitTrigger = 9;
  22327. ActionManager._OnKeyDownTrigger = 10;
  22328. ActionManager._OnKeyUpTrigger = 11;
  22329. return ActionManager;
  22330. })();
  22331. BABYLON.ActionManager = ActionManager;
  22332. })(BABYLON || (BABYLON = {}));
  22333. //# sourceMappingURL=babylon.actionManager.js.map
  22334. var BABYLON;
  22335. (function (BABYLON) {
  22336. var InterpolateValueAction = (function (_super) {
  22337. __extends(InterpolateValueAction, _super);
  22338. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22339. if (typeof duration === "undefined") { duration = 1000; }
  22340. _super.call(this, triggerOptions, condition);
  22341. this.propertyPath = propertyPath;
  22342. this.value = value;
  22343. this.duration = duration;
  22344. this.stopOtherAnimations = stopOtherAnimations;
  22345. this._target = target;
  22346. }
  22347. InterpolateValueAction.prototype._prepare = function () {
  22348. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22349. this._property = this._getProperty(this.propertyPath);
  22350. };
  22351. InterpolateValueAction.prototype.execute = function () {
  22352. var scene = this._actionManager.getScene();
  22353. var keys = [
  22354. {
  22355. frame: 0,
  22356. value: this._target[this._property]
  22357. }, {
  22358. frame: 100,
  22359. value: this.value
  22360. }
  22361. ];
  22362. var dataType;
  22363. if (typeof this.value === "number") {
  22364. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22365. } else if (this.value instanceof BABYLON.Color3) {
  22366. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22367. } else if (this.value instanceof BABYLON.Vector3) {
  22368. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22369. } else if (this.value instanceof BABYLON.Matrix) {
  22370. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22371. } else if (this.value instanceof BABYLON.Quaternion) {
  22372. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22373. } else {
  22374. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22375. return;
  22376. }
  22377. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22378. animation.setKeys(keys);
  22379. if (this.stopOtherAnimations) {
  22380. scene.stopAnimation(this._target);
  22381. }
  22382. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22383. };
  22384. return InterpolateValueAction;
  22385. })(BABYLON.Action);
  22386. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22387. })(BABYLON || (BABYLON = {}));
  22388. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22389. var BABYLON;
  22390. (function (BABYLON) {
  22391. var SwitchBooleanAction = (function (_super) {
  22392. __extends(SwitchBooleanAction, _super);
  22393. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22394. _super.call(this, triggerOptions, condition);
  22395. this.propertyPath = propertyPath;
  22396. this._target = target;
  22397. }
  22398. SwitchBooleanAction.prototype._prepare = function () {
  22399. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22400. this._property = this._getProperty(this.propertyPath);
  22401. };
  22402. SwitchBooleanAction.prototype.execute = function () {
  22403. this._target[this._property] = !this._target[this._property];
  22404. };
  22405. return SwitchBooleanAction;
  22406. })(BABYLON.Action);
  22407. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22408. var SetStateAction = (function (_super) {
  22409. __extends(SetStateAction, _super);
  22410. function SetStateAction(triggerOptions, target, value, condition) {
  22411. _super.call(this, triggerOptions, condition);
  22412. this.value = value;
  22413. this._target = target;
  22414. }
  22415. SetStateAction.prototype.execute = function () {
  22416. this._target.state = this.value;
  22417. };
  22418. return SetStateAction;
  22419. })(BABYLON.Action);
  22420. BABYLON.SetStateAction = SetStateAction;
  22421. var SetValueAction = (function (_super) {
  22422. __extends(SetValueAction, _super);
  22423. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22424. _super.call(this, triggerOptions, condition);
  22425. this.propertyPath = propertyPath;
  22426. this.value = value;
  22427. this._target = target;
  22428. }
  22429. SetValueAction.prototype._prepare = function () {
  22430. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22431. this._property = this._getProperty(this.propertyPath);
  22432. };
  22433. SetValueAction.prototype.execute = function () {
  22434. this._target[this._property] = this.value;
  22435. };
  22436. return SetValueAction;
  22437. })(BABYLON.Action);
  22438. BABYLON.SetValueAction = SetValueAction;
  22439. var IncrementValueAction = (function (_super) {
  22440. __extends(IncrementValueAction, _super);
  22441. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22442. _super.call(this, triggerOptions, condition);
  22443. this.propertyPath = propertyPath;
  22444. this.value = value;
  22445. this._target = target;
  22446. }
  22447. IncrementValueAction.prototype._prepare = function () {
  22448. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22449. this._property = this._getProperty(this.propertyPath);
  22450. if (typeof this._target[this._property] !== "number") {
  22451. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22452. }
  22453. };
  22454. IncrementValueAction.prototype.execute = function () {
  22455. this._target[this._property] += this.value;
  22456. };
  22457. return IncrementValueAction;
  22458. })(BABYLON.Action);
  22459. BABYLON.IncrementValueAction = IncrementValueAction;
  22460. var PlayAnimationAction = (function (_super) {
  22461. __extends(PlayAnimationAction, _super);
  22462. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22463. _super.call(this, triggerOptions, condition);
  22464. this.from = from;
  22465. this.to = to;
  22466. this.loop = loop;
  22467. this._target = target;
  22468. }
  22469. PlayAnimationAction.prototype._prepare = function () {
  22470. };
  22471. PlayAnimationAction.prototype.execute = function () {
  22472. var scene = this._actionManager.getScene();
  22473. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22474. };
  22475. return PlayAnimationAction;
  22476. })(BABYLON.Action);
  22477. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22478. var StopAnimationAction = (function (_super) {
  22479. __extends(StopAnimationAction, _super);
  22480. function StopAnimationAction(triggerOptions, target, condition) {
  22481. _super.call(this, triggerOptions, condition);
  22482. this._target = target;
  22483. }
  22484. StopAnimationAction.prototype._prepare = function () {
  22485. };
  22486. StopAnimationAction.prototype.execute = function () {
  22487. var scene = this._actionManager.getScene();
  22488. scene.stopAnimation(this._target);
  22489. };
  22490. return StopAnimationAction;
  22491. })(BABYLON.Action);
  22492. BABYLON.StopAnimationAction = StopAnimationAction;
  22493. var DoNothingAction = (function (_super) {
  22494. __extends(DoNothingAction, _super);
  22495. function DoNothingAction(triggerOptions, condition) {
  22496. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22497. _super.call(this, triggerOptions, condition);
  22498. }
  22499. DoNothingAction.prototype.execute = function () {
  22500. };
  22501. return DoNothingAction;
  22502. })(BABYLON.Action);
  22503. BABYLON.DoNothingAction = DoNothingAction;
  22504. var CombineAction = (function (_super) {
  22505. __extends(CombineAction, _super);
  22506. function CombineAction(triggerOptions, children, condition) {
  22507. _super.call(this, triggerOptions, condition);
  22508. this.children = children;
  22509. }
  22510. CombineAction.prototype._prepare = function () {
  22511. for (var index = 0; index < this.children.length; index++) {
  22512. this.children[index]._actionManager = this._actionManager;
  22513. this.children[index]._prepare();
  22514. }
  22515. };
  22516. CombineAction.prototype.execute = function (evt) {
  22517. for (var index = 0; index < this.children.length; index++) {
  22518. this.children[index].execute(evt);
  22519. }
  22520. };
  22521. return CombineAction;
  22522. })(BABYLON.Action);
  22523. BABYLON.CombineAction = CombineAction;
  22524. var ExecuteCodeAction = (function (_super) {
  22525. __extends(ExecuteCodeAction, _super);
  22526. function ExecuteCodeAction(triggerOptions, func, condition) {
  22527. _super.call(this, triggerOptions, condition);
  22528. this.func = func;
  22529. }
  22530. ExecuteCodeAction.prototype.execute = function (evt) {
  22531. this.func(evt);
  22532. };
  22533. return ExecuteCodeAction;
  22534. })(BABYLON.Action);
  22535. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22536. var SetParentAction = (function (_super) {
  22537. __extends(SetParentAction, _super);
  22538. function SetParentAction(triggerOptions, target, parent, condition) {
  22539. _super.call(this, triggerOptions, condition);
  22540. this._target = target;
  22541. this._parent = parent;
  22542. }
  22543. SetParentAction.prototype._prepare = function () {
  22544. };
  22545. SetParentAction.prototype.execute = function () {
  22546. if (this._target.parent === this._parent) {
  22547. return;
  22548. }
  22549. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22550. invertParentWorldMatrix.invert();
  22551. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22552. this._target.parent = this._parent;
  22553. };
  22554. return SetParentAction;
  22555. })(BABYLON.Action);
  22556. BABYLON.SetParentAction = SetParentAction;
  22557. })(BABYLON || (BABYLON = {}));
  22558. //# sourceMappingURL=babylon.directActions.js.map
  22559. var BABYLON;
  22560. (function (BABYLON) {
  22561. var Geometry = (function () {
  22562. function Geometry(id, scene, vertexData, updatable, mesh) {
  22563. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22564. this._totalVertices = 0;
  22565. this._indices = [];
  22566. this.id = id;
  22567. this._engine = scene.getEngine();
  22568. this._meshes = [];
  22569. this._scene = scene;
  22570. // vertexData
  22571. if (vertexData) {
  22572. this.setAllVerticesData(vertexData, updatable);
  22573. } else {
  22574. this._totalVertices = 0;
  22575. this._indices = [];
  22576. }
  22577. // applyToMesh
  22578. if (mesh) {
  22579. this.applyToMesh(mesh);
  22580. }
  22581. }
  22582. Geometry.prototype.getScene = function () {
  22583. return this._scene;
  22584. };
  22585. Geometry.prototype.getEngine = function () {
  22586. return this._engine;
  22587. };
  22588. Geometry.prototype.isReady = function () {
  22589. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22590. };
  22591. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22592. vertexData.applyToGeometry(this, updatable);
  22593. };
  22594. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22595. this._vertexBuffers = this._vertexBuffers || {};
  22596. if (this._vertexBuffers[kind]) {
  22597. this._vertexBuffers[kind].dispose();
  22598. }
  22599. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22600. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22601. stride = this._vertexBuffers[kind].getStrideSize();
  22602. this._totalVertices = data.length / stride;
  22603. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22604. var meshes = this._meshes;
  22605. var numOfMeshes = meshes.length;
  22606. for (var index = 0; index < numOfMeshes; index++) {
  22607. var mesh = meshes[index];
  22608. mesh._resetPointsArrayCache();
  22609. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22610. mesh._createGlobalSubMesh();
  22611. mesh.computeWorldMatrix(true);
  22612. }
  22613. }
  22614. };
  22615. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22616. var vertexBuffer = this.getVertexBuffer(kind);
  22617. if (!vertexBuffer) {
  22618. return;
  22619. }
  22620. vertexBuffer.updateDirectly(data, offset);
  22621. };
  22622. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22623. var vertexBuffer = this.getVertexBuffer(kind);
  22624. if (!vertexBuffer) {
  22625. return;
  22626. }
  22627. vertexBuffer.update(data);
  22628. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22629. var extend;
  22630. var stride = vertexBuffer.getStrideSize();
  22631. this._totalVertices = data.length / stride;
  22632. if (updateExtends) {
  22633. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22634. }
  22635. var meshes = this._meshes;
  22636. var numOfMeshes = meshes.length;
  22637. for (var index = 0; index < numOfMeshes; index++) {
  22638. var mesh = meshes[index];
  22639. mesh._resetPointsArrayCache();
  22640. if (updateExtends) {
  22641. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22642. }
  22643. }
  22644. }
  22645. };
  22646. Geometry.prototype.getTotalVertices = function () {
  22647. if (!this.isReady()) {
  22648. return 0;
  22649. }
  22650. return this._totalVertices;
  22651. };
  22652. Geometry.prototype.getVerticesData = function (kind) {
  22653. var vertexBuffer = this.getVertexBuffer(kind);
  22654. if (!vertexBuffer) {
  22655. return null;
  22656. }
  22657. return vertexBuffer.getData();
  22658. };
  22659. Geometry.prototype.getVertexBuffer = function (kind) {
  22660. if (!this.isReady()) {
  22661. return null;
  22662. }
  22663. return this._vertexBuffers[kind];
  22664. };
  22665. Geometry.prototype.getVertexBuffers = function () {
  22666. if (!this.isReady()) {
  22667. return null;
  22668. }
  22669. return this._vertexBuffers;
  22670. };
  22671. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22672. if (!this._vertexBuffers) {
  22673. if (this._delayInfo) {
  22674. return this._delayInfo.indexOf(kind) !== -1;
  22675. }
  22676. return false;
  22677. }
  22678. return this._vertexBuffers[kind] !== undefined;
  22679. };
  22680. Geometry.prototype.getVerticesDataKinds = function () {
  22681. var result = [];
  22682. if (!this._vertexBuffers && this._delayInfo) {
  22683. for (var kind in this._delayInfo) {
  22684. result.push(kind);
  22685. }
  22686. } else {
  22687. for (kind in this._vertexBuffers) {
  22688. result.push(kind);
  22689. }
  22690. }
  22691. return result;
  22692. };
  22693. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22694. if (this._indexBuffer) {
  22695. this._engine._releaseBuffer(this._indexBuffer);
  22696. }
  22697. this._indices = indices;
  22698. if (this._meshes.length !== 0 && this._indices) {
  22699. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22700. }
  22701. if (totalVertices !== undefined) {
  22702. this._totalVertices = totalVertices;
  22703. }
  22704. var meshes = this._meshes;
  22705. var numOfMeshes = meshes.length;
  22706. for (var index = 0; index < numOfMeshes; index++) {
  22707. meshes[index]._createGlobalSubMesh();
  22708. }
  22709. };
  22710. Geometry.prototype.getTotalIndices = function () {
  22711. if (!this.isReady()) {
  22712. return 0;
  22713. }
  22714. return this._indices.length;
  22715. };
  22716. Geometry.prototype.getIndices = function () {
  22717. if (!this.isReady()) {
  22718. return null;
  22719. }
  22720. return this._indices;
  22721. };
  22722. Geometry.prototype.getIndexBuffer = function () {
  22723. if (!this.isReady()) {
  22724. return null;
  22725. }
  22726. return this._indexBuffer;
  22727. };
  22728. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22729. var meshes = this._meshes;
  22730. var index = meshes.indexOf(mesh);
  22731. if (index === -1) {
  22732. return;
  22733. }
  22734. for (var kind in this._vertexBuffers) {
  22735. this._vertexBuffers[kind].dispose();
  22736. }
  22737. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22738. this._indexBuffer = null;
  22739. }
  22740. meshes.splice(index, 1);
  22741. mesh._geometry = null;
  22742. if (meshes.length === 0 && shouldDispose) {
  22743. this.dispose();
  22744. }
  22745. };
  22746. Geometry.prototype.applyToMesh = function (mesh) {
  22747. if (mesh._geometry === this) {
  22748. return;
  22749. }
  22750. var previousGeometry = mesh._geometry;
  22751. if (previousGeometry) {
  22752. previousGeometry.releaseForMesh(mesh);
  22753. }
  22754. var meshes = this._meshes;
  22755. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22756. mesh._geometry = this;
  22757. this._scene.pushGeometry(this);
  22758. meshes.push(mesh);
  22759. if (this.isReady()) {
  22760. this._applyToMesh(mesh);
  22761. } else {
  22762. mesh._boundingInfo = this._boundingInfo;
  22763. }
  22764. };
  22765. Geometry.prototype._applyToMesh = function (mesh) {
  22766. var numOfMeshes = this._meshes.length;
  22767. for (var kind in this._vertexBuffers) {
  22768. if (numOfMeshes === 1) {
  22769. this._vertexBuffers[kind].create();
  22770. }
  22771. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22772. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22773. mesh._resetPointsArrayCache();
  22774. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22775. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22776. mesh._createGlobalSubMesh();
  22777. //bounding info was just created again, world matrix should be applied again.
  22778. mesh._updateBoundingInfo();
  22779. }
  22780. }
  22781. // indexBuffer
  22782. if (numOfMeshes === 1 && this._indices) {
  22783. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22784. }
  22785. if (this._indexBuffer) {
  22786. this._indexBuffer.references = numOfMeshes;
  22787. }
  22788. };
  22789. Geometry.prototype.load = function (scene, onLoaded) {
  22790. var _this = this;
  22791. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22792. return;
  22793. }
  22794. if (this.isReady()) {
  22795. if (onLoaded) {
  22796. onLoaded();
  22797. }
  22798. return;
  22799. }
  22800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22801. scene._addPendingData(this);
  22802. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22803. _this._delayLoadingFunction(JSON.parse(data), _this);
  22804. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22805. _this._delayInfo = [];
  22806. scene._removePendingData(_this);
  22807. var meshes = _this._meshes;
  22808. var numOfMeshes = meshes.length;
  22809. for (var index = 0; index < numOfMeshes; index++) {
  22810. _this._applyToMesh(meshes[index]);
  22811. }
  22812. if (onLoaded) {
  22813. onLoaded();
  22814. }
  22815. }, function () {
  22816. }, scene.database);
  22817. };
  22818. Geometry.prototype.dispose = function () {
  22819. var meshes = this._meshes;
  22820. var numOfMeshes = meshes.length;
  22821. var index;
  22822. for (index = 0; index < numOfMeshes; index++) {
  22823. this.releaseForMesh(meshes[index]);
  22824. }
  22825. this._meshes = [];
  22826. for (var kind in this._vertexBuffers) {
  22827. this._vertexBuffers[kind].dispose();
  22828. }
  22829. this._vertexBuffers = [];
  22830. this._totalVertices = 0;
  22831. if (this._indexBuffer) {
  22832. this._engine._releaseBuffer(this._indexBuffer);
  22833. }
  22834. this._indexBuffer = null;
  22835. this._indices = [];
  22836. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22837. this.delayLoadingFile = null;
  22838. this._delayLoadingFunction = null;
  22839. this._delayInfo = [];
  22840. this._boundingInfo = null; // todo: .dispose()
  22841. var geometries = this._scene.getGeometries();
  22842. index = geometries.indexOf(this);
  22843. if (index > -1) {
  22844. geometries.splice(index, 1);
  22845. }
  22846. };
  22847. Geometry.prototype.copy = function (id) {
  22848. var vertexData = new BABYLON.VertexData();
  22849. vertexData.indices = [];
  22850. var indices = this.getIndices();
  22851. for (var index = 0; index < indices.length; index++) {
  22852. vertexData.indices.push(indices[index]);
  22853. }
  22854. var updatable = false;
  22855. var stopChecking = false;
  22856. for (var kind in this._vertexBuffers) {
  22857. vertexData.set(this.getVerticesData(kind), kind);
  22858. if (!stopChecking) {
  22859. updatable = this.getVertexBuffer(kind).isUpdatable();
  22860. stopChecking = !updatable;
  22861. }
  22862. }
  22863. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  22864. geometry.delayLoadState = this.delayLoadState;
  22865. geometry.delayLoadingFile = this.delayLoadingFile;
  22866. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22867. for (kind in this._delayInfo) {
  22868. geometry._delayInfo = geometry._delayInfo || [];
  22869. geometry._delayInfo.push(kind);
  22870. }
  22871. // Bounding info
  22872. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22873. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22874. return geometry;
  22875. };
  22876. // Statics
  22877. Geometry.ExtractFromMesh = function (mesh, id) {
  22878. var geometry = mesh._geometry;
  22879. if (!geometry) {
  22880. return null;
  22881. }
  22882. return geometry.copy(id);
  22883. };
  22884. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22885. // be aware Math.random() could cause collisions
  22886. Geometry.RandomId = function () {
  22887. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22888. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  22889. return v.toString(16);
  22890. });
  22891. };
  22892. return Geometry;
  22893. })();
  22894. BABYLON.Geometry = Geometry;
  22895. (function (Geometry) {
  22896. /////// Primitives //////////////////////////////////////////////
  22897. (function (Primitives) {
  22898. /// Abstract class
  22899. var _Primitive = (function (_super) {
  22900. __extends(_Primitive, _super);
  22901. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22902. this._beingRegenerated = true;
  22903. this._canBeRegenerated = canBeRegenerated;
  22904. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22905. this._beingRegenerated = false;
  22906. }
  22907. _Primitive.prototype.canBeRegenerated = function () {
  22908. return this._canBeRegenerated;
  22909. };
  22910. _Primitive.prototype.regenerate = function () {
  22911. if (!this._canBeRegenerated) {
  22912. return;
  22913. }
  22914. this._beingRegenerated = true;
  22915. this.setAllVerticesData(this._regenerateVertexData(), false);
  22916. this._beingRegenerated = false;
  22917. };
  22918. _Primitive.prototype.asNewGeometry = function (id) {
  22919. return _super.prototype.copy.call(this, id);
  22920. };
  22921. // overrides
  22922. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22923. if (!this._beingRegenerated) {
  22924. return;
  22925. }
  22926. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22927. };
  22928. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22929. if (!this._beingRegenerated) {
  22930. return;
  22931. }
  22932. _super.prototype.setVerticesData.call(this, kind, data, false);
  22933. };
  22934. // to override
  22935. // protected
  22936. _Primitive.prototype._regenerateVertexData = function () {
  22937. throw new Error("Abstract method");
  22938. };
  22939. _Primitive.prototype.copy = function (id) {
  22940. throw new Error("Must be overriden in sub-classes.");
  22941. };
  22942. return _Primitive;
  22943. })(Geometry);
  22944. Primitives._Primitive = _Primitive;
  22945. var Box = (function (_super) {
  22946. __extends(Box, _super);
  22947. function Box(id, scene, size, canBeRegenerated, mesh) {
  22948. this.size = size;
  22949. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22950. }
  22951. Box.prototype._regenerateVertexData = function () {
  22952. return BABYLON.VertexData.CreateBox(this.size);
  22953. };
  22954. Box.prototype.copy = function (id) {
  22955. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22956. };
  22957. return Box;
  22958. })(_Primitive);
  22959. Primitives.Box = Box;
  22960. var Sphere = (function (_super) {
  22961. __extends(Sphere, _super);
  22962. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22963. this.segments = segments;
  22964. this.diameter = diameter;
  22965. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22966. }
  22967. Sphere.prototype._regenerateVertexData = function () {
  22968. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22969. };
  22970. Sphere.prototype.copy = function (id) {
  22971. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22972. };
  22973. return Sphere;
  22974. })(_Primitive);
  22975. Primitives.Sphere = Sphere;
  22976. var Cylinder = (function (_super) {
  22977. __extends(Cylinder, _super);
  22978. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22979. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22980. this.height = height;
  22981. this.diameterTop = diameterTop;
  22982. this.diameterBottom = diameterBottom;
  22983. this.tessellation = tessellation;
  22984. this.subdivisions = subdivisions;
  22985. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22986. }
  22987. Cylinder.prototype._regenerateVertexData = function () {
  22988. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22989. };
  22990. Cylinder.prototype.copy = function (id) {
  22991. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22992. };
  22993. return Cylinder;
  22994. })(_Primitive);
  22995. Primitives.Cylinder = Cylinder;
  22996. var Torus = (function (_super) {
  22997. __extends(Torus, _super);
  22998. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22999. this.diameter = diameter;
  23000. this.thickness = thickness;
  23001. this.tessellation = tessellation;
  23002. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23003. }
  23004. Torus.prototype._regenerateVertexData = function () {
  23005. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23006. };
  23007. Torus.prototype.copy = function (id) {
  23008. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23009. };
  23010. return Torus;
  23011. })(_Primitive);
  23012. Primitives.Torus = Torus;
  23013. var Ground = (function (_super) {
  23014. __extends(Ground, _super);
  23015. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23016. this.width = width;
  23017. this.height = height;
  23018. this.subdivisions = subdivisions;
  23019. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23020. }
  23021. Ground.prototype._regenerateVertexData = function () {
  23022. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23023. };
  23024. Ground.prototype.copy = function (id) {
  23025. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23026. };
  23027. return Ground;
  23028. })(_Primitive);
  23029. Primitives.Ground = Ground;
  23030. var TiledGround = (function (_super) {
  23031. __extends(TiledGround, _super);
  23032. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23033. this.xmin = xmin;
  23034. this.zmin = zmin;
  23035. this.xmax = xmax;
  23036. this.zmax = zmax;
  23037. this.subdivisions = subdivisions;
  23038. this.precision = precision;
  23039. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23040. }
  23041. TiledGround.prototype._regenerateVertexData = function () {
  23042. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23043. };
  23044. TiledGround.prototype.copy = function (id) {
  23045. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23046. };
  23047. return TiledGround;
  23048. })(_Primitive);
  23049. Primitives.TiledGround = TiledGround;
  23050. var Plane = (function (_super) {
  23051. __extends(Plane, _super);
  23052. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23053. this.size = size;
  23054. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23055. }
  23056. Plane.prototype._regenerateVertexData = function () {
  23057. return BABYLON.VertexData.CreatePlane(this.size);
  23058. };
  23059. Plane.prototype.copy = function (id) {
  23060. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23061. };
  23062. return Plane;
  23063. })(_Primitive);
  23064. Primitives.Plane = Plane;
  23065. var TorusKnot = (function (_super) {
  23066. __extends(TorusKnot, _super);
  23067. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23068. this.radius = radius;
  23069. this.tube = tube;
  23070. this.radialSegments = radialSegments;
  23071. this.tubularSegments = tubularSegments;
  23072. this.p = p;
  23073. this.q = q;
  23074. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23075. }
  23076. TorusKnot.prototype._regenerateVertexData = function () {
  23077. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23078. };
  23079. TorusKnot.prototype.copy = function (id) {
  23080. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23081. };
  23082. return TorusKnot;
  23083. })(_Primitive);
  23084. Primitives.TorusKnot = TorusKnot;
  23085. })(Geometry.Primitives || (Geometry.Primitives = {}));
  23086. var Primitives = Geometry.Primitives;
  23087. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  23088. var Geometry = BABYLON.Geometry;
  23089. })(BABYLON || (BABYLON = {}));
  23090. //# sourceMappingURL=babylon.geometry.js.map
  23091. var BABYLON;
  23092. (function (BABYLON) {
  23093. var Gamepads = (function () {
  23094. function Gamepads(ongamedpadconnected) {
  23095. var _this = this;
  23096. this.babylonGamepads = [];
  23097. this.oneGamepadConnected = false;
  23098. this.isMonitoring = false;
  23099. this.gamepadEventSupported = 'GamepadEvent' in window;
  23100. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23101. 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=";
  23102. this._callbackGamepadConnected = ongamedpadconnected;
  23103. if (this.gamepadSupportAvailable) {
  23104. // Checking if the gamepad connected event is supported (like in Firefox)
  23105. if (this.gamepadEventSupported) {
  23106. window.addEventListener('gamepadconnected', function (evt) {
  23107. _this._onGamepadConnected(evt);
  23108. }, false);
  23109. window.addEventListener('gamepaddisconnected', function (evt) {
  23110. _this._onGamepadDisconnected(evt);
  23111. }, false);
  23112. } else {
  23113. this._startMonitoringGamepads();
  23114. }
  23115. if (!this.oneGamepadConnected) {
  23116. this._insertGamepadDOMInstructions();
  23117. }
  23118. } else {
  23119. this._insertGamepadDOMNotSupported();
  23120. }
  23121. }
  23122. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23123. Gamepads.gamepadDOMInfo = document.createElement("div");
  23124. var buttonAImage = document.createElement("img");
  23125. buttonAImage.src = this.buttonADataURL;
  23126. var spanMessage = document.createElement("span");
  23127. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23128. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23129. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23130. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23131. Gamepads.gamepadDOMInfo.style.width = "100%";
  23132. Gamepads.gamepadDOMInfo.style.height = "48px";
  23133. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23134. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23135. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23136. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23137. buttonAImage.style.position = "relative";
  23138. buttonAImage.style.bottom = "8px";
  23139. spanMessage.style.position = "relative";
  23140. spanMessage.style.fontSize = "32px";
  23141. spanMessage.style.bottom = "32px";
  23142. spanMessage.style.color = "green";
  23143. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23144. };
  23145. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23146. Gamepads.gamepadDOMInfo = document.createElement("div");
  23147. var spanMessage = document.createElement("span");
  23148. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23149. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23150. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23151. Gamepads.gamepadDOMInfo.style.width = "100%";
  23152. Gamepads.gamepadDOMInfo.style.height = "40px";
  23153. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23154. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23155. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23156. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23157. spanMessage.style.position = "relative";
  23158. spanMessage.style.fontSize = "32px";
  23159. spanMessage.style.color = "red";
  23160. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23161. };
  23162. Gamepads.prototype.dispose = function () {
  23163. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23164. };
  23165. Gamepads.prototype._onGamepadConnected = function (evt) {
  23166. var newGamepad = this._addNewGamepad(evt.gamepad);
  23167. if (this._callbackGamepadConnected)
  23168. this._callbackGamepadConnected(newGamepad);
  23169. this._startMonitoringGamepads();
  23170. };
  23171. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23172. if (!this.oneGamepadConnected) {
  23173. this.oneGamepadConnected = true;
  23174. if (Gamepads.gamepadDOMInfo) {
  23175. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23176. Gamepads.gamepadDOMInfo = null;
  23177. }
  23178. }
  23179. var newGamepad;
  23180. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23181. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23182. } else {
  23183. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23184. }
  23185. this.babylonGamepads.push(newGamepad);
  23186. return newGamepad;
  23187. };
  23188. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23189. for (var i in this.babylonGamepads) {
  23190. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23191. this.babylonGamepads.splice(i, 1);
  23192. break;
  23193. }
  23194. }
  23195. // If no gamepads are left, stop the polling loop.
  23196. if (this.babylonGamepads.length == 0) {
  23197. this._stopMonitoringGamepads();
  23198. }
  23199. };
  23200. Gamepads.prototype._startMonitoringGamepads = function () {
  23201. if (!this.isMonitoring) {
  23202. this.isMonitoring = true;
  23203. this._checkGamepadsStatus();
  23204. }
  23205. };
  23206. Gamepads.prototype._stopMonitoringGamepads = function () {
  23207. this.isMonitoring = false;
  23208. };
  23209. Gamepads.prototype._checkGamepadsStatus = function () {
  23210. var _this = this;
  23211. // updating gamepad objects
  23212. this._updateGamepadObjects();
  23213. for (var i in this.babylonGamepads) {
  23214. this.babylonGamepads[i].update();
  23215. }
  23216. if (this.isMonitoring) {
  23217. if (window.requestAnimationFrame) {
  23218. window.requestAnimationFrame(function () {
  23219. _this._checkGamepadsStatus();
  23220. });
  23221. } else if (window.mozRequestAnimationFrame) {
  23222. window.mozRequestAnimationFrame(function () {
  23223. _this._checkGamepadsStatus();
  23224. });
  23225. } else if (window.webkitRequestAnimationFrame) {
  23226. window.webkitRequestAnimationFrame(function () {
  23227. _this._checkGamepadsStatus();
  23228. });
  23229. }
  23230. }
  23231. };
  23232. // This function is called only on Chrome, which does not yet support
  23233. // connection/disconnection events, but requires you to monitor
  23234. // an array for changes.
  23235. Gamepads.prototype._updateGamepadObjects = function () {
  23236. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23237. for (var i = 0; i < gamepads.length; i++) {
  23238. if (gamepads[i]) {
  23239. if (!(gamepads[i].index in this.babylonGamepads)) {
  23240. var newGamepad = this._addNewGamepad(gamepads[i]);
  23241. if (this._callbackGamepadConnected) {
  23242. this._callbackGamepadConnected(newGamepad);
  23243. }
  23244. } else {
  23245. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23246. }
  23247. }
  23248. }
  23249. };
  23250. return Gamepads;
  23251. })();
  23252. BABYLON.Gamepads = Gamepads;
  23253. var StickValues = (function () {
  23254. function StickValues(x, y) {
  23255. this.x = x;
  23256. this.y = y;
  23257. }
  23258. return StickValues;
  23259. })();
  23260. BABYLON.StickValues = StickValues;
  23261. var Gamepad = (function () {
  23262. function Gamepad(id, index, browserGamepad) {
  23263. this.id = id;
  23264. this.index = index;
  23265. this.browserGamepad = browserGamepad;
  23266. if (this.browserGamepad.axes.length >= 2) {
  23267. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23268. }
  23269. if (this.browserGamepad.axes.length >= 4) {
  23270. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23271. }
  23272. }
  23273. Gamepad.prototype.onleftstickchanged = function (callback) {
  23274. this._onleftstickchanged = callback;
  23275. };
  23276. Gamepad.prototype.onrightstickchanged = function (callback) {
  23277. this._onrightstickchanged = callback;
  23278. };
  23279. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23280. get: function () {
  23281. return this._leftStick;
  23282. },
  23283. set: function (newValues) {
  23284. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23285. this._onleftstickchanged(newValues);
  23286. }
  23287. this._leftStick = newValues;
  23288. },
  23289. enumerable: true,
  23290. configurable: true
  23291. });
  23292. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23293. get: function () {
  23294. return this._rightStick;
  23295. },
  23296. set: function (newValues) {
  23297. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23298. this._onrightstickchanged(newValues);
  23299. }
  23300. this._rightStick = newValues;
  23301. },
  23302. enumerable: true,
  23303. configurable: true
  23304. });
  23305. Gamepad.prototype.update = function () {
  23306. if (this._leftStick) {
  23307. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23308. }
  23309. if (this._rightStick) {
  23310. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23311. }
  23312. };
  23313. return Gamepad;
  23314. })();
  23315. BABYLON.Gamepad = Gamepad;
  23316. var GenericPad = (function (_super) {
  23317. __extends(GenericPad, _super);
  23318. function GenericPad(id, index, gamepad) {
  23319. _super.call(this, id, index, gamepad);
  23320. this.id = id;
  23321. this.index = index;
  23322. this.gamepad = gamepad;
  23323. this._buttons = new Array(gamepad.buttons.length);
  23324. }
  23325. GenericPad.prototype.onbuttondown = function (callback) {
  23326. this._onbuttondown = callback;
  23327. };
  23328. GenericPad.prototype.onbuttonup = function (callback) {
  23329. this._onbuttonup = callback;
  23330. };
  23331. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23332. if (newValue !== currentValue) {
  23333. if (this._onbuttondown && newValue === 1) {
  23334. this._onbuttondown(buttonIndex);
  23335. }
  23336. if (this._onbuttonup && newValue === 0) {
  23337. this._onbuttonup(buttonIndex);
  23338. }
  23339. }
  23340. return newValue;
  23341. };
  23342. GenericPad.prototype.update = function () {
  23343. _super.prototype.update.call(this);
  23344. for (var index = 0; index < this._buttons.length; index++) {
  23345. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23346. }
  23347. };
  23348. return GenericPad;
  23349. })(Gamepad);
  23350. BABYLON.GenericPad = GenericPad;
  23351. (function (Xbox360Button) {
  23352. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23353. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23354. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23355. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23356. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23357. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23358. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23359. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23360. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23361. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23362. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23363. var Xbox360Button = BABYLON.Xbox360Button;
  23364. (function (Xbox360Dpad) {
  23365. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23366. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23367. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23368. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23369. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23370. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23371. var Xbox360Pad = (function (_super) {
  23372. __extends(Xbox360Pad, _super);
  23373. function Xbox360Pad() {
  23374. _super.apply(this, arguments);
  23375. this._leftTrigger = 0;
  23376. this._rightTrigger = 0;
  23377. this._buttonA = 0;
  23378. this._buttonB = 0;
  23379. this._buttonX = 0;
  23380. this._buttonY = 0;
  23381. this._buttonBack = 0;
  23382. this._buttonStart = 0;
  23383. this._buttonLB = 0;
  23384. this._buttonRB = 0;
  23385. this._buttonLeftStick = 0;
  23386. this._buttonRightStick = 0;
  23387. this._dPadUp = 0;
  23388. this._dPadDown = 0;
  23389. this._dPadLeft = 0;
  23390. this._dPadRight = 0;
  23391. }
  23392. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23393. this._onlefttriggerchanged = callback;
  23394. };
  23395. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23396. this._onrighttriggerchanged = callback;
  23397. };
  23398. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23399. get: function () {
  23400. return this._leftTrigger;
  23401. },
  23402. set: function (newValue) {
  23403. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23404. this._onlefttriggerchanged(newValue);
  23405. }
  23406. this._leftTrigger = newValue;
  23407. },
  23408. enumerable: true,
  23409. configurable: true
  23410. });
  23411. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23412. get: function () {
  23413. return this._rightTrigger;
  23414. },
  23415. set: function (newValue) {
  23416. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23417. this._onrighttriggerchanged(newValue);
  23418. }
  23419. this._rightTrigger = newValue;
  23420. },
  23421. enumerable: true,
  23422. configurable: true
  23423. });
  23424. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23425. this._onbuttondown = callback;
  23426. };
  23427. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23428. this._onbuttonup = callback;
  23429. };
  23430. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23431. this._ondpaddown = callback;
  23432. };
  23433. Xbox360Pad.prototype.ondpadup = function (callback) {
  23434. this._ondpadup = callback;
  23435. };
  23436. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23437. if (newValue !== currentValue) {
  23438. if (this._onbuttondown && newValue === 1) {
  23439. this._onbuttondown(buttonType);
  23440. }
  23441. if (this._onbuttonup && newValue === 0) {
  23442. this._onbuttonup(buttonType);
  23443. }
  23444. }
  23445. return newValue;
  23446. };
  23447. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23448. if (newValue !== currentValue) {
  23449. if (this._ondpaddown && newValue === 1) {
  23450. this._ondpaddown(buttonType);
  23451. }
  23452. if (this._ondpadup && newValue === 0) {
  23453. this._ondpadup(buttonType);
  23454. }
  23455. }
  23456. return newValue;
  23457. };
  23458. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23459. get: function () {
  23460. return this._buttonA;
  23461. },
  23462. set: function (value) {
  23463. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23464. },
  23465. enumerable: true,
  23466. configurable: true
  23467. });
  23468. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23469. get: function () {
  23470. return this._buttonB;
  23471. },
  23472. set: function (value) {
  23473. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23474. },
  23475. enumerable: true,
  23476. configurable: true
  23477. });
  23478. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23479. get: function () {
  23480. return this._buttonX;
  23481. },
  23482. set: function (value) {
  23483. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23484. },
  23485. enumerable: true,
  23486. configurable: true
  23487. });
  23488. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23489. get: function () {
  23490. return this._buttonY;
  23491. },
  23492. set: function (value) {
  23493. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23494. },
  23495. enumerable: true,
  23496. configurable: true
  23497. });
  23498. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23499. get: function () {
  23500. return this._buttonStart;
  23501. },
  23502. set: function (value) {
  23503. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23504. },
  23505. enumerable: true,
  23506. configurable: true
  23507. });
  23508. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23509. get: function () {
  23510. return this._buttonBack;
  23511. },
  23512. set: function (value) {
  23513. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23514. },
  23515. enumerable: true,
  23516. configurable: true
  23517. });
  23518. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23519. get: function () {
  23520. return this._buttonLB;
  23521. },
  23522. set: function (value) {
  23523. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23524. },
  23525. enumerable: true,
  23526. configurable: true
  23527. });
  23528. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23529. get: function () {
  23530. return this._buttonRB;
  23531. },
  23532. set: function (value) {
  23533. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23534. },
  23535. enumerable: true,
  23536. configurable: true
  23537. });
  23538. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23539. get: function () {
  23540. return this._buttonLeftStick;
  23541. },
  23542. set: function (value) {
  23543. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23544. },
  23545. enumerable: true,
  23546. configurable: true
  23547. });
  23548. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23549. get: function () {
  23550. return this._buttonRightStick;
  23551. },
  23552. set: function (value) {
  23553. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23554. },
  23555. enumerable: true,
  23556. configurable: true
  23557. });
  23558. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23559. get: function () {
  23560. return this._dPadUp;
  23561. },
  23562. set: function (value) {
  23563. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23564. },
  23565. enumerable: true,
  23566. configurable: true
  23567. });
  23568. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23569. get: function () {
  23570. return this._dPadDown;
  23571. },
  23572. set: function (value) {
  23573. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23579. get: function () {
  23580. return this._dPadLeft;
  23581. },
  23582. set: function (value) {
  23583. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23589. get: function () {
  23590. return this._dPadRight;
  23591. },
  23592. set: function (value) {
  23593. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. Xbox360Pad.prototype.update = function () {
  23599. _super.prototype.update.call(this);
  23600. this.buttonA = this.browserGamepad.buttons[0].value;
  23601. this.buttonB = this.browserGamepad.buttons[1].value;
  23602. this.buttonX = this.browserGamepad.buttons[2].value;
  23603. this.buttonY = this.browserGamepad.buttons[3].value;
  23604. this.buttonLB = this.browserGamepad.buttons[4].value;
  23605. this.buttonRB = this.browserGamepad.buttons[5].value;
  23606. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23607. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23608. this.buttonBack = this.browserGamepad.buttons[8].value;
  23609. this.buttonStart = this.browserGamepad.buttons[9].value;
  23610. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23611. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23612. this.dPadUp = this.browserGamepad.buttons[12].value;
  23613. this.dPadDown = this.browserGamepad.buttons[13].value;
  23614. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23615. this.dPadRight = this.browserGamepad.buttons[15].value;
  23616. };
  23617. return Xbox360Pad;
  23618. })(Gamepad);
  23619. BABYLON.Xbox360Pad = Xbox360Pad;
  23620. })(BABYLON || (BABYLON = {}));
  23621. //# sourceMappingURL=babylon.gamepads.js.map
  23622. var BABYLON;
  23623. (function (BABYLON) {
  23624. // We're mainly based on the logic defined into the FreeCamera code
  23625. var GamepadCamera = (function (_super) {
  23626. __extends(GamepadCamera, _super);
  23627. function GamepadCamera(name, position, scene) {
  23628. var _this = this;
  23629. _super.call(this, name, position, scene);
  23630. this.angularSensibility = 200;
  23631. this.moveSensibility = 75;
  23632. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23633. _this._onNewGameConnected(gamepad);
  23634. });
  23635. }
  23636. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23637. // Only the first gamepad can control the camera
  23638. if (gamepad.index === 0) {
  23639. this._gamepad = gamepad;
  23640. }
  23641. };
  23642. GamepadCamera.prototype._checkInputs = function () {
  23643. if (!this._gamepad) {
  23644. return;
  23645. }
  23646. var LSValues = this._gamepad.leftStick;
  23647. var normalizedLX = LSValues.x / this.moveSensibility;
  23648. var normalizedLY = LSValues.y / this.moveSensibility;
  23649. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23650. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23651. var RSValues = this._gamepad.rightStick;
  23652. var normalizedRX = RSValues.x / this.angularSensibility;
  23653. var normalizedRY = RSValues.y / this.angularSensibility;
  23654. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23655. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23656. ;
  23657. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23658. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23659. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23660. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23661. };
  23662. GamepadCamera.prototype.dispose = function () {
  23663. this._gamepads.dispose();
  23664. _super.prototype.dispose.call(this);
  23665. };
  23666. return GamepadCamera;
  23667. })(BABYLON.FreeCamera);
  23668. BABYLON.GamepadCamera = GamepadCamera;
  23669. })(BABYLON || (BABYLON = {}));
  23670. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23671. var BABYLON;
  23672. (function (BABYLON) {
  23673. var LinesMesh = (function (_super) {
  23674. __extends(LinesMesh, _super);
  23675. function LinesMesh(name, scene, updatable) {
  23676. if (typeof updatable === "undefined") { updatable = false; }
  23677. _super.call(this, name, scene);
  23678. this.color = new BABYLON.Color3(1, 1, 1);
  23679. this.alpha = 1;
  23680. this._indices = new Array();
  23681. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23682. attributes: ["position"],
  23683. uniforms: ["worldViewProjection", "color"],
  23684. needAlphaBlending: true
  23685. });
  23686. }
  23687. Object.defineProperty(LinesMesh.prototype, "material", {
  23688. get: function () {
  23689. return this._colorShader;
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23695. get: function () {
  23696. return false;
  23697. },
  23698. enumerable: true,
  23699. configurable: true
  23700. });
  23701. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23702. get: function () {
  23703. return false;
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23709. var engine = this.getScene().getEngine();
  23710. var indexToBind = this._geometry.getIndexBuffer();
  23711. // VBOs
  23712. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23713. // Color
  23714. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23715. };
  23716. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23717. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23718. return;
  23719. }
  23720. var engine = this.getScene().getEngine();
  23721. // Draw order
  23722. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23723. };
  23724. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23725. return null;
  23726. };
  23727. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23728. this._colorShader.dispose();
  23729. _super.prototype.dispose.call(this, doNotRecurse);
  23730. };
  23731. return LinesMesh;
  23732. })(BABYLON.Mesh);
  23733. BABYLON.LinesMesh = LinesMesh;
  23734. })(BABYLON || (BABYLON = {}));
  23735. //# sourceMappingURL=babylon.linesMesh.js.map
  23736. var BABYLON;
  23737. (function (BABYLON) {
  23738. var OutlineRenderer = (function () {
  23739. function OutlineRenderer(scene) {
  23740. this._scene = scene;
  23741. }
  23742. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23743. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23744. var scene = this._scene;
  23745. var engine = this._scene.getEngine();
  23746. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23747. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23748. return;
  23749. }
  23750. var mesh = subMesh.getRenderingMesh();
  23751. var material = subMesh.getMaterial();
  23752. engine.enableEffect(this._effect);
  23753. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23754. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23755. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23756. // Bones
  23757. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23758. if (useBones) {
  23759. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23760. }
  23761. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23762. // Alpha test
  23763. if (material && material.needAlphaTesting()) {
  23764. var alphaTexture = material.getAlphaTestTexture();
  23765. this._effect.setTexture("diffuseSampler", alphaTexture);
  23766. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23767. }
  23768. if (hardwareInstancedRendering) {
  23769. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23770. } else {
  23771. if (batch.renderSelf[subMesh._id]) {
  23772. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23773. // Draw
  23774. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23775. }
  23776. if (batch.visibleInstances[subMesh._id]) {
  23777. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23778. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23779. this._effect.setMatrix("world", instance.getWorldMatrix());
  23780. // Draw
  23781. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23782. }
  23783. }
  23784. }
  23785. };
  23786. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23787. var defines = [];
  23788. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23789. var mesh = subMesh.getMesh();
  23790. var material = subMesh.getMaterial();
  23791. // Alpha test
  23792. if (material && material.needAlphaTesting()) {
  23793. defines.push("#define ALPHATEST");
  23794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23795. attribs.push(BABYLON.VertexBuffer.UVKind);
  23796. defines.push("#define UV1");
  23797. }
  23798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23799. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23800. defines.push("#define UV2");
  23801. }
  23802. }
  23803. // Bones
  23804. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23805. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23806. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23807. defines.push("#define BONES");
  23808. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23809. }
  23810. // Instances
  23811. if (useInstances) {
  23812. defines.push("#define INSTANCES");
  23813. attribs.push("world0");
  23814. attribs.push("world1");
  23815. attribs.push("world2");
  23816. attribs.push("world3");
  23817. }
  23818. // Get correct effect
  23819. var join = defines.join("\n");
  23820. if (this._cachedDefines != join) {
  23821. this._cachedDefines = join;
  23822. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23823. }
  23824. return this._effect.isReady();
  23825. };
  23826. return OutlineRenderer;
  23827. })();
  23828. BABYLON.OutlineRenderer = OutlineRenderer;
  23829. })(BABYLON || (BABYLON = {}));
  23830. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23831. var BABYLON;
  23832. (function (BABYLON) {
  23833. var MeshAssetTask = (function () {
  23834. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23835. this.name = name;
  23836. this.meshesNames = meshesNames;
  23837. this.rootUrl = rootUrl;
  23838. this.sceneFilename = sceneFilename;
  23839. this.isCompleted = false;
  23840. }
  23841. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23842. var _this = this;
  23843. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23844. _this.loadedMeshes = meshes;
  23845. _this.loadedParticleSystems = particleSystems;
  23846. _this.loadedSkeletons = skeletons;
  23847. _this.isCompleted = true;
  23848. if (_this.onSuccess) {
  23849. _this.onSuccess(_this);
  23850. }
  23851. onSuccess();
  23852. }, null, function () {
  23853. if (_this.onError) {
  23854. _this.onError(_this);
  23855. }
  23856. onError();
  23857. });
  23858. };
  23859. return MeshAssetTask;
  23860. })();
  23861. BABYLON.MeshAssetTask = MeshAssetTask;
  23862. var TextFileAssetTask = (function () {
  23863. function TextFileAssetTask(name, url) {
  23864. this.name = name;
  23865. this.url = url;
  23866. this.isCompleted = false;
  23867. }
  23868. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23869. var _this = this;
  23870. BABYLON.Tools.LoadFile(this.url, function (data) {
  23871. _this.text = data;
  23872. _this.isCompleted = true;
  23873. if (_this.onSuccess) {
  23874. _this.onSuccess(_this);
  23875. }
  23876. onSuccess();
  23877. }, null, scene.database, false, function () {
  23878. if (_this.onError) {
  23879. _this.onError(_this);
  23880. }
  23881. onError();
  23882. });
  23883. };
  23884. return TextFileAssetTask;
  23885. })();
  23886. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23887. var BinaryFileAssetTask = (function () {
  23888. function BinaryFileAssetTask(name, url) {
  23889. this.name = name;
  23890. this.url = url;
  23891. this.isCompleted = false;
  23892. }
  23893. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23894. var _this = this;
  23895. BABYLON.Tools.LoadFile(this.url, function (data) {
  23896. _this.data = data;
  23897. _this.isCompleted = true;
  23898. if (_this.onSuccess) {
  23899. _this.onSuccess(_this);
  23900. }
  23901. onSuccess();
  23902. }, null, scene.database, true, function () {
  23903. if (_this.onError) {
  23904. _this.onError(_this);
  23905. }
  23906. onError();
  23907. });
  23908. };
  23909. return BinaryFileAssetTask;
  23910. })();
  23911. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23912. var ImageAssetTask = (function () {
  23913. function ImageAssetTask(name, url) {
  23914. this.name = name;
  23915. this.url = url;
  23916. this.isCompleted = false;
  23917. }
  23918. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23919. var _this = this;
  23920. var img = new Image();
  23921. img.onload = function () {
  23922. _this.image = img;
  23923. _this.isCompleted = true;
  23924. if (_this.onSuccess) {
  23925. _this.onSuccess(_this);
  23926. }
  23927. onSuccess();
  23928. };
  23929. img.onerror = function () {
  23930. if (_this.onError) {
  23931. _this.onError(_this);
  23932. }
  23933. onError();
  23934. };
  23935. img.src = this.url;
  23936. };
  23937. return ImageAssetTask;
  23938. })();
  23939. BABYLON.ImageAssetTask = ImageAssetTask;
  23940. var TextureAssetTask = (function () {
  23941. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23942. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23943. this.name = name;
  23944. this.url = url;
  23945. this.noMipmap = noMipmap;
  23946. this.invertY = invertY;
  23947. this.samplingMode = samplingMode;
  23948. this.isCompleted = false;
  23949. }
  23950. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23951. var _this = this;
  23952. var onload = function () {
  23953. _this.isCompleted = true;
  23954. if (_this.onSuccess) {
  23955. _this.onSuccess(_this);
  23956. }
  23957. onSuccess();
  23958. };
  23959. var onerror = function () {
  23960. if (_this.onError) {
  23961. _this.onError(_this);
  23962. }
  23963. onError();
  23964. };
  23965. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23966. };
  23967. return TextureAssetTask;
  23968. })();
  23969. BABYLON.TextureAssetTask = TextureAssetTask;
  23970. var AssetsManager = (function () {
  23971. function AssetsManager(scene) {
  23972. this._tasks = new Array();
  23973. this._waitingTasksCount = 0;
  23974. this.useDefaultLoadingScreen = true;
  23975. this._scene = scene;
  23976. }
  23977. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23978. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23979. this._tasks.push(task);
  23980. return task;
  23981. };
  23982. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23983. var task = new TextFileAssetTask(taskName, url);
  23984. this._tasks.push(task);
  23985. return task;
  23986. };
  23987. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23988. var task = new BinaryFileAssetTask(taskName, url);
  23989. this._tasks.push(task);
  23990. return task;
  23991. };
  23992. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23993. var task = new ImageAssetTask(taskName, url);
  23994. this._tasks.push(task);
  23995. return task;
  23996. };
  23997. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23998. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23999. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24000. this._tasks.push(task);
  24001. return task;
  24002. };
  24003. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24004. this._waitingTasksCount--;
  24005. if (this._waitingTasksCount === 0) {
  24006. if (this.onFinish) {
  24007. this.onFinish(this._tasks);
  24008. }
  24009. this._scene.getEngine().hideLoadingUI();
  24010. }
  24011. };
  24012. AssetsManager.prototype._runTask = function (task) {
  24013. var _this = this;
  24014. task.run(this._scene, function () {
  24015. if (_this.onTaskSuccess) {
  24016. _this.onTaskSuccess(task);
  24017. }
  24018. _this._decreaseWaitingTasksCount();
  24019. }, function () {
  24020. if (_this.onTaskError) {
  24021. _this.onTaskError(task);
  24022. }
  24023. _this._decreaseWaitingTasksCount();
  24024. });
  24025. };
  24026. AssetsManager.prototype.reset = function () {
  24027. this._tasks = new Array();
  24028. return this;
  24029. };
  24030. AssetsManager.prototype.load = function () {
  24031. this._waitingTasksCount = this._tasks.length;
  24032. if (this._waitingTasksCount === 0) {
  24033. if (this.onFinish) {
  24034. this.onFinish(this._tasks);
  24035. }
  24036. return this;
  24037. }
  24038. if (this.useDefaultLoadingScreen) {
  24039. this._scene.getEngine().displayLoadingUI();
  24040. }
  24041. for (var index = 0; index < this._tasks.length; index++) {
  24042. var task = this._tasks[index];
  24043. this._runTask(task);
  24044. }
  24045. return this;
  24046. };
  24047. return AssetsManager;
  24048. })();
  24049. BABYLON.AssetsManager = AssetsManager;
  24050. })(BABYLON || (BABYLON = {}));
  24051. //# sourceMappingURL=babylon.assetsManager.js.map
  24052. var BABYLON;
  24053. (function (BABYLON) {
  24054. var VRDeviceOrientationCamera = (function (_super) {
  24055. __extends(VRDeviceOrientationCamera, _super);
  24056. function VRDeviceOrientationCamera(name, position, scene) {
  24057. _super.call(this, name, position, scene);
  24058. this._alpha = 0;
  24059. this._beta = 0;
  24060. this._gamma = 0;
  24061. }
  24062. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24063. this._alpha = +evt.alpha | 0;
  24064. this._beta = +evt.beta | 0;
  24065. this._gamma = +evt.gamma | 0;
  24066. if (this._gamma < 0) {
  24067. this._gamma = 90 + this._gamma;
  24068. } else {
  24069. // Incline it in the correct angle.
  24070. this._gamma = 270 - this._gamma;
  24071. }
  24072. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24073. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24074. this.rotation.z = this._beta / 180.0 * Math.PI;
  24075. };
  24076. return VRDeviceOrientationCamera;
  24077. })(BABYLON.OculusCamera);
  24078. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24079. })(BABYLON || (BABYLON = {}));
  24080. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24081. var BABYLON;
  24082. (function (BABYLON) {
  24083. var WebVRCamera = (function (_super) {
  24084. __extends(WebVRCamera, _super);
  24085. function WebVRCamera(name, position, scene) {
  24086. _super.call(this, name, position, scene);
  24087. this._hmdDevice = null;
  24088. this._sensorDevice = null;
  24089. this._cacheState = null;
  24090. this._cacheQuaternion = new BABYLON.Quaternion();
  24091. this._cacheRotation = BABYLON.Vector3.Zero();
  24092. this._vrEnabled = false;
  24093. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24094. }
  24095. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24096. var size = devices.length;
  24097. var i = 0;
  24098. // Reset devices.
  24099. this._sensorDevice = null;
  24100. this._hmdDevice = null;
  24101. while (i < size && this._hmdDevice === null) {
  24102. if (devices[i] instanceof HMDVRDevice) {
  24103. this._hmdDevice = devices[i];
  24104. }
  24105. i++;
  24106. }
  24107. i = 0;
  24108. while (i < size && this._sensorDevice === null) {
  24109. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24110. this._sensorDevice = devices[i];
  24111. }
  24112. i++;
  24113. }
  24114. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24115. };
  24116. WebVRCamera.prototype._update = function () {
  24117. if (this._vrEnabled) {
  24118. this._cacheState = this._sensorDevice.getState();
  24119. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24120. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24121. this.rotation.x = -this._cacheRotation.z;
  24122. this.rotation.y = -this._cacheRotation.y;
  24123. this.rotation.z = this._cacheRotation.x;
  24124. }
  24125. _super.prototype._update.call(this);
  24126. };
  24127. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24128. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24129. if (navigator.getVRDevices) {
  24130. navigator.getVRDevices().then(this._getWebVRDevices);
  24131. } else if (navigator.mozGetVRDevices) {
  24132. navigator.mozGetVRDevices(this._getWebVRDevices);
  24133. }
  24134. };
  24135. WebVRCamera.prototype.detachControl = function (element) {
  24136. _super.prototype.detachControl.call(this, element);
  24137. this._vrEnabled = false;
  24138. };
  24139. return WebVRCamera;
  24140. })(BABYLON.OculusCamera);
  24141. BABYLON.WebVRCamera = WebVRCamera;
  24142. })(BABYLON || (BABYLON = {}));
  24143. //# sourceMappingURL=babylon.webVRCamera.js.map
  24144. var BABYLON;
  24145. (function (BABYLON) {
  24146. // Standard optimizations
  24147. var SceneOptimization = (function () {
  24148. function SceneOptimization(priority) {
  24149. if (typeof priority === "undefined") { priority = 0; }
  24150. this.priority = priority;
  24151. this.apply = function (scene) {
  24152. return true;
  24153. };
  24154. }
  24155. return SceneOptimization;
  24156. })();
  24157. BABYLON.SceneOptimization = SceneOptimization;
  24158. var TextureOptimization = (function (_super) {
  24159. __extends(TextureOptimization, _super);
  24160. function TextureOptimization(priority, maximumSize) {
  24161. if (typeof priority === "undefined") { priority = 0; }
  24162. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  24163. var _this = this;
  24164. _super.call(this, priority);
  24165. this.priority = priority;
  24166. this.maximumSize = maximumSize;
  24167. this.apply = function (scene) {
  24168. var allDone = true;
  24169. for (var index = 0; index < scene.textures.length; index++) {
  24170. var texture = scene.textures[index];
  24171. if (!texture.canRescale) {
  24172. continue;
  24173. }
  24174. var currentSize = texture.getSize();
  24175. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24176. if (maxDimension > _this.maximumSize) {
  24177. texture.scale(0.5);
  24178. allDone = false;
  24179. }
  24180. }
  24181. return allDone;
  24182. };
  24183. }
  24184. return TextureOptimization;
  24185. })(SceneOptimization);
  24186. BABYLON.TextureOptimization = TextureOptimization;
  24187. var HardwareScalingOptimization = (function (_super) {
  24188. __extends(HardwareScalingOptimization, _super);
  24189. function HardwareScalingOptimization(priority, maximumScale) {
  24190. if (typeof priority === "undefined") { priority = 0; }
  24191. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  24192. var _this = this;
  24193. _super.call(this, priority);
  24194. this.priority = priority;
  24195. this.maximumScale = maximumScale;
  24196. this._currentScale = 1;
  24197. this.apply = function (scene) {
  24198. _this._currentScale++;
  24199. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24200. return _this._currentScale >= _this.maximumScale;
  24201. };
  24202. }
  24203. return HardwareScalingOptimization;
  24204. })(SceneOptimization);
  24205. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24206. var ShadowsOptimization = (function (_super) {
  24207. __extends(ShadowsOptimization, _super);
  24208. function ShadowsOptimization() {
  24209. _super.apply(this, arguments);
  24210. this.apply = function (scene) {
  24211. scene.shadowsEnabled = false;
  24212. return true;
  24213. };
  24214. }
  24215. return ShadowsOptimization;
  24216. })(SceneOptimization);
  24217. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24218. var PostProcessesOptimization = (function (_super) {
  24219. __extends(PostProcessesOptimization, _super);
  24220. function PostProcessesOptimization() {
  24221. _super.apply(this, arguments);
  24222. this.apply = function (scene) {
  24223. scene.postProcessesEnabled = false;
  24224. return true;
  24225. };
  24226. }
  24227. return PostProcessesOptimization;
  24228. })(SceneOptimization);
  24229. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24230. var LensFlaresOptimization = (function (_super) {
  24231. __extends(LensFlaresOptimization, _super);
  24232. function LensFlaresOptimization() {
  24233. _super.apply(this, arguments);
  24234. this.apply = function (scene) {
  24235. scene.lensFlaresEnabled = false;
  24236. return true;
  24237. };
  24238. }
  24239. return LensFlaresOptimization;
  24240. })(SceneOptimization);
  24241. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24242. var ParticlesOptimization = (function (_super) {
  24243. __extends(ParticlesOptimization, _super);
  24244. function ParticlesOptimization() {
  24245. _super.apply(this, arguments);
  24246. this.apply = function (scene) {
  24247. scene.particlesEnabled = false;
  24248. return true;
  24249. };
  24250. }
  24251. return ParticlesOptimization;
  24252. })(SceneOptimization);
  24253. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24254. var RenderTargetsOptimization = (function (_super) {
  24255. __extends(RenderTargetsOptimization, _super);
  24256. function RenderTargetsOptimization() {
  24257. _super.apply(this, arguments);
  24258. this.apply = function (scene) {
  24259. scene.renderTargetsEnabled = false;
  24260. return true;
  24261. };
  24262. }
  24263. return RenderTargetsOptimization;
  24264. })(SceneOptimization);
  24265. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24266. var MergeMeshesOptimization = (function (_super) {
  24267. __extends(MergeMeshesOptimization, _super);
  24268. function MergeMeshesOptimization() {
  24269. _super.apply(this, arguments);
  24270. var _this = this;
  24271. this._canBeMerged = function (abstractMesh) {
  24272. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24273. return false;
  24274. }
  24275. var mesh = abstractMesh;
  24276. if (!mesh.isVisible || !mesh.isEnabled()) {
  24277. return false;
  24278. }
  24279. if (mesh.instances.length > 0) {
  24280. return false;
  24281. }
  24282. if (mesh.skeleton || mesh.hasLODLevels) {
  24283. return false;
  24284. }
  24285. return true;
  24286. };
  24287. this.apply = function (scene) {
  24288. var globalPool = scene.meshes.slice(0);
  24289. var globalLength = globalPool.length;
  24290. for (var index = 0; index < globalLength; index++) {
  24291. var currentPool = new Array();
  24292. var current = globalPool[index];
  24293. // Checks
  24294. if (!_this._canBeMerged(current)) {
  24295. continue;
  24296. }
  24297. currentPool.push(current);
  24298. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24299. var otherMesh = globalPool[subIndex];
  24300. if (!_this._canBeMerged(otherMesh)) {
  24301. continue;
  24302. }
  24303. if (otherMesh.material !== current.material) {
  24304. continue;
  24305. }
  24306. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24307. continue;
  24308. }
  24309. currentPool.push(otherMesh);
  24310. globalLength--;
  24311. globalPool.splice(subIndex, 1);
  24312. subIndex--;
  24313. }
  24314. if (currentPool.length < 2) {
  24315. continue;
  24316. }
  24317. // Merge meshes
  24318. BABYLON.Mesh.MergeMeshes(currentPool);
  24319. }
  24320. return true;
  24321. };
  24322. }
  24323. return MergeMeshesOptimization;
  24324. })(SceneOptimization);
  24325. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24326. // Options
  24327. var SceneOptimizerOptions = (function () {
  24328. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24329. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24330. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24331. this.targetFrameRate = targetFrameRate;
  24332. this.trackerDuration = trackerDuration;
  24333. this.optimizations = new Array();
  24334. }
  24335. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24336. var result = new SceneOptimizerOptions(targetFrameRate);
  24337. var priority = 0;
  24338. result.optimizations.push(new MergeMeshesOptimization(priority));
  24339. result.optimizations.push(new ShadowsOptimization(priority));
  24340. result.optimizations.push(new LensFlaresOptimization(priority));
  24341. // Next priority
  24342. priority++;
  24343. result.optimizations.push(new PostProcessesOptimization(priority));
  24344. result.optimizations.push(new ParticlesOptimization(priority));
  24345. // Next priority
  24346. priority++;
  24347. result.optimizations.push(new TextureOptimization(priority, 1024));
  24348. return result;
  24349. };
  24350. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24351. var result = new SceneOptimizerOptions(targetFrameRate);
  24352. var priority = 0;
  24353. result.optimizations.push(new MergeMeshesOptimization(priority));
  24354. result.optimizations.push(new ShadowsOptimization(priority));
  24355. result.optimizations.push(new LensFlaresOptimization(priority));
  24356. // Next priority
  24357. priority++;
  24358. result.optimizations.push(new PostProcessesOptimization(priority));
  24359. result.optimizations.push(new ParticlesOptimization(priority));
  24360. // Next priority
  24361. priority++;
  24362. result.optimizations.push(new TextureOptimization(priority, 512));
  24363. // Next priority
  24364. priority++;
  24365. result.optimizations.push(new RenderTargetsOptimization(priority));
  24366. // Next priority
  24367. priority++;
  24368. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24369. return result;
  24370. };
  24371. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24372. var result = new SceneOptimizerOptions(targetFrameRate);
  24373. var priority = 0;
  24374. result.optimizations.push(new MergeMeshesOptimization(priority));
  24375. result.optimizations.push(new ShadowsOptimization(priority));
  24376. result.optimizations.push(new LensFlaresOptimization(priority));
  24377. // Next priority
  24378. priority++;
  24379. result.optimizations.push(new PostProcessesOptimization(priority));
  24380. result.optimizations.push(new ParticlesOptimization(priority));
  24381. // Next priority
  24382. priority++;
  24383. result.optimizations.push(new TextureOptimization(priority, 256));
  24384. // Next priority
  24385. priority++;
  24386. result.optimizations.push(new RenderTargetsOptimization(priority));
  24387. // Next priority
  24388. priority++;
  24389. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24390. return result;
  24391. };
  24392. return SceneOptimizerOptions;
  24393. })();
  24394. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24395. // Scene optimizer tool
  24396. var SceneOptimizer = (function () {
  24397. function SceneOptimizer() {
  24398. }
  24399. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24400. // TODO: add an epsilon
  24401. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24402. if (onSuccess) {
  24403. onSuccess();
  24404. }
  24405. return;
  24406. }
  24407. // Apply current level of optimizations
  24408. var allDone = true;
  24409. var noOptimizationApplied = true;
  24410. for (var index = 0; index < options.optimizations.length; index++) {
  24411. var optimization = options.optimizations[index];
  24412. if (optimization.priority === currentPriorityLevel) {
  24413. noOptimizationApplied = false;
  24414. allDone = allDone && optimization.apply(scene);
  24415. }
  24416. }
  24417. // If no optimization was applied, this is a failure :(
  24418. if (noOptimizationApplied) {
  24419. if (onFailure) {
  24420. onFailure();
  24421. }
  24422. return;
  24423. }
  24424. // If all optimizations were done, move to next level
  24425. if (allDone) {
  24426. currentPriorityLevel++;
  24427. }
  24428. // Let's the system running for a specific amount of time before checking FPS
  24429. scene.executeWhenReady(function () {
  24430. setTimeout(function () {
  24431. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24432. }, options.trackerDuration);
  24433. });
  24434. };
  24435. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24436. if (!options) {
  24437. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24438. }
  24439. // Let's the system running for a specific amount of time before checking FPS
  24440. scene.executeWhenReady(function () {
  24441. setTimeout(function () {
  24442. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24443. }, options.trackerDuration);
  24444. });
  24445. };
  24446. return SceneOptimizer;
  24447. })();
  24448. BABYLON.SceneOptimizer = SceneOptimizer;
  24449. })(BABYLON || (BABYLON = {}));
  24450. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24451. var BABYLON;
  24452. (function (BABYLON) {
  24453. (function (Internals) {
  24454. var MeshLODLevel = (function () {
  24455. function MeshLODLevel(distance, mesh) {
  24456. this.distance = distance;
  24457. this.mesh = mesh;
  24458. }
  24459. return MeshLODLevel;
  24460. })();
  24461. Internals.MeshLODLevel = MeshLODLevel;
  24462. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24463. var Internals = BABYLON.Internals;
  24464. })(BABYLON || (BABYLON = {}));
  24465. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24466. var BABYLON;
  24467. (function (BABYLON) {
  24468. var AudioEngine = (function () {
  24469. function AudioEngine() {
  24470. this.audioContext = null;
  24471. this.canUseWebAudio = false;
  24472. try {
  24473. if (typeof AudioContext !== 'undefined') {
  24474. this.audioContext = new AudioContext();
  24475. this.canUseWebAudio = true;
  24476. } else if (typeof webkitAudioContext !== 'undefined') {
  24477. this.audioContext = new webkitAudioContext();
  24478. this.canUseWebAudio = true;
  24479. }
  24480. } catch (e) {
  24481. this.canUseWebAudio = false;
  24482. }
  24483. // create a global volume gain node
  24484. if (this.canUseWebAudio) {
  24485. this.masterGain = this.audioContext.createGain();
  24486. this.masterGain.gain.value = 1;
  24487. this.masterGain.connect(this.audioContext.destination);
  24488. }
  24489. }
  24490. AudioEngine.prototype.getGlobalVolume = function () {
  24491. if (this.canUseWebAudio) {
  24492. return this.masterGain.gain.value;
  24493. } else {
  24494. return -1;
  24495. }
  24496. };
  24497. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24498. if (this.canUseWebAudio) {
  24499. this.masterGain.gain.value = newVolume;
  24500. }
  24501. };
  24502. return AudioEngine;
  24503. })();
  24504. BABYLON.AudioEngine = AudioEngine;
  24505. })(BABYLON || (BABYLON = {}));
  24506. //# sourceMappingURL=babylon.audioengine.js.map
  24507. var BABYLON;
  24508. (function (BABYLON) {
  24509. var Sound = (function () {
  24510. /**
  24511. * Create a sound and attach it to a scene
  24512. * @param name Name of your sound
  24513. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24514. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24515. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24516. */
  24517. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24518. var _this = this;
  24519. this.autoplay = false;
  24520. this.loop = false;
  24521. this.useCustomAttenuation = false;
  24522. this.spatialSound = false;
  24523. this.refDistance = 1;
  24524. this.rolloffFactor = 1;
  24525. this.maxDistance = 100;
  24526. this.distanceModel = "linear";
  24527. this.panningModel = "HRTF";
  24528. this.startTime = 0;
  24529. this.startOffset = 0;
  24530. this._position = BABYLON.Vector3.Zero();
  24531. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24532. this._volume = 1;
  24533. this._isLoaded = false;
  24534. this._isReadyToPlay = false;
  24535. this._isPlaying = false;
  24536. this._isDirectional = false;
  24537. // Used if you'd like to create a directional sound.
  24538. // If not set, the sound will be omnidirectional
  24539. this._coneInnerAngle = 360;
  24540. this._coneOuterAngle = 360;
  24541. this._coneOuterGain = 0;
  24542. this._name = name;
  24543. this._scene = scene;
  24544. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24545. this._readyToPlayCallback = readyToPlayCallback;
  24546. // Default custom attenuation function is a linear attenuation
  24547. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24548. if (currentDistance < maxDistance) {
  24549. return currentVolume * (1 - currentDistance / maxDistance);
  24550. } else {
  24551. return 0;
  24552. }
  24553. };
  24554. if (options) {
  24555. this.autoplay = options.autoplay || false;
  24556. this.loop = options.loop || false;
  24557. this._volume = options.volume || 1;
  24558. this.spatialSound = options.spatialSound || false;
  24559. this.maxDistance = options.maxDistance || 100;
  24560. this.useCustomAttenuation = options.useCustomAttenation || false;
  24561. this.rolloffFactor = options.rolloffFactor || 1;
  24562. this.refDistance = options.refDistance || 1;
  24563. this.distanceModel = options.distanceModel || "linear";
  24564. this.panningModel = options.panningModel || "HRTF";
  24565. }
  24566. if (this._audioEngine.canUseWebAudio) {
  24567. this._soundGain = this._audioEngine.audioContext.createGain();
  24568. this._soundGain.gain.value = this._volume;
  24569. if (this.spatialSound) {
  24570. this._createSpatialParameters();
  24571. } else {
  24572. this._audioNode = this._soundGain;
  24573. }
  24574. this._scene.mainSoundTrack.AddSound(this);
  24575. if (typeof (urlOrArrayBuffer) === "string") {
  24576. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24577. _this._soundLoaded(data);
  24578. }, null, null, true);
  24579. } else {
  24580. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24581. this._soundLoaded(urlOrArrayBuffer);
  24582. } else {
  24583. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24584. }
  24585. }
  24586. }
  24587. }
  24588. Sound.prototype.updateOptions = function (options) {
  24589. if (options) {
  24590. this.loop = options.loop || this.loop;
  24591. this.maxDistance = options.maxDistance || this.maxDistance;
  24592. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24593. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24594. this.refDistance = options.refDistance || this.refDistance;
  24595. this.distanceModel = options.distanceModel || this.distanceModel;
  24596. this.panningModel = options.panningModel || this.panningModel;
  24597. }
  24598. };
  24599. Sound.prototype._createSpatialParameters = function () {
  24600. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24601. if (this.useCustomAttenuation) {
  24602. // Tricks to disable in a way embedded Web Audio attenuation
  24603. this._soundPanner.distanceModel = "linear";
  24604. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24605. this._soundPanner.refDistance = 1;
  24606. this._soundPanner.rolloffFactor = 1;
  24607. this._soundPanner.panningModel = "HRTF";
  24608. } else {
  24609. this._soundPanner.distanceModel = this.distanceModel;
  24610. this._soundPanner.maxDistance = this.maxDistance;
  24611. this._soundPanner.refDistance = this.refDistance;
  24612. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24613. this._soundPanner.panningModel = this.panningModel;
  24614. }
  24615. this._soundPanner.connect(this._soundGain);
  24616. this._audioNode = this._soundPanner;
  24617. };
  24618. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24619. if (this._audioEngine.canUseWebAudio) {
  24620. this._audioNode.disconnect();
  24621. this._audioNode.connect(soundTrackAudioNode);
  24622. }
  24623. };
  24624. /**
  24625. * Transform this sound into a directional source
  24626. * @param coneInnerAngle Size of the inner cone in degree
  24627. * @param coneOuterAngle Size of the outer cone in degree
  24628. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24629. */
  24630. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24631. if (coneOuterAngle < coneInnerAngle) {
  24632. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24633. return;
  24634. }
  24635. this._coneInnerAngle = coneInnerAngle;
  24636. this._coneOuterAngle = coneOuterAngle;
  24637. this._coneOuterGain = coneOuterGain;
  24638. this._isDirectional = true;
  24639. if (this._isPlaying && this.loop) {
  24640. this.stop();
  24641. this.play();
  24642. }
  24643. };
  24644. Sound.prototype.setPosition = function (newPosition) {
  24645. this._position = newPosition;
  24646. if (this._isPlaying && this.spatialSound) {
  24647. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24648. }
  24649. };
  24650. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24651. this._localDirection = newLocalDirection;
  24652. if (this._connectedMesh && this._isPlaying) {
  24653. this._updateDirection();
  24654. }
  24655. };
  24656. Sound.prototype._updateDirection = function () {
  24657. var mat = this._connectedMesh.getWorldMatrix();
  24658. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24659. direction.normalize();
  24660. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24661. };
  24662. Sound.prototype.updateDistanceFromListener = function () {
  24663. if (this._connectedMesh && this.useCustomAttenuation) {
  24664. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24665. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  24666. }
  24667. };
  24668. Sound.prototype.setAttenuationFunction = function (callback) {
  24669. this._customAttenuationFunction = callback;
  24670. };
  24671. /**
  24672. * Play the sound
  24673. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24674. */
  24675. Sound.prototype.play = function (time) {
  24676. if (this._isReadyToPlay) {
  24677. try {
  24678. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24679. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24680. this._soundSource.buffer = this._audioBuffer;
  24681. if (this.spatialSound) {
  24682. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24683. if (this._isDirectional) {
  24684. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24685. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24686. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24687. if (this._connectedMesh) {
  24688. this._updateDirection();
  24689. } else {
  24690. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24691. }
  24692. }
  24693. }
  24694. this._soundSource.connect(this._audioNode);
  24695. this._soundSource.loop = this.loop;
  24696. this.startTime = startTime;
  24697. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  24698. this._isPlaying = true;
  24699. } catch (ex) {
  24700. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24701. }
  24702. }
  24703. };
  24704. /**
  24705. * Stop the sound
  24706. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24707. */
  24708. Sound.prototype.stop = function (time) {
  24709. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24710. this._soundSource.stop(stopTime);
  24711. this._isPlaying = false;
  24712. };
  24713. Sound.prototype.pause = function () {
  24714. this._soundSource.stop(0);
  24715. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  24716. };
  24717. Sound.prototype.setVolume = function (newVolume) {
  24718. this._volume = newVolume;
  24719. this._soundGain.gain.value = newVolume;
  24720. };
  24721. Sound.prototype.getVolume = function () {
  24722. return this._volume;
  24723. };
  24724. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24725. var _this = this;
  24726. this._connectedMesh = meshToConnectTo;
  24727. if (!this.spatialSound) {
  24728. this._createSpatialParameters();
  24729. this.spatialSound = true;
  24730. if (this._isPlaying && this.loop) {
  24731. this.stop();
  24732. this.play();
  24733. }
  24734. }
  24735. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24736. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24737. });
  24738. };
  24739. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24740. this.setPosition(connectedMesh.position);
  24741. if (this._isDirectional && this._isPlaying) {
  24742. this._updateDirection();
  24743. }
  24744. };
  24745. Sound.prototype._soundLoaded = function (audioData) {
  24746. var _this = this;
  24747. this._isLoaded = true;
  24748. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24749. _this._audioBuffer = buffer;
  24750. _this._isReadyToPlay = true;
  24751. if (_this.autoplay) {
  24752. _this.play();
  24753. }
  24754. if (_this._readyToPlayCallback) {
  24755. _this._readyToPlayCallback();
  24756. }
  24757. }, function (error) {
  24758. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24759. });
  24760. };
  24761. return Sound;
  24762. })();
  24763. BABYLON.Sound = Sound;
  24764. })(BABYLON || (BABYLON = {}));
  24765. //# sourceMappingURL=babylon.sound.js.map
  24766. var BABYLON;
  24767. (function (BABYLON) {
  24768. var SoundTrack = (function () {
  24769. function SoundTrack(scene, options) {
  24770. this.id = -1;
  24771. this._isMainTrack = false;
  24772. this._scene = scene;
  24773. this._audioEngine = scene.getEngine().getAudioEngine();
  24774. this.soundCollection = new Array();
  24775. if (this._audioEngine.canUseWebAudio) {
  24776. this._trackGain = this._audioEngine.audioContext.createGain();
  24777. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24778. //this._trackConvolver.connect(this._trackGain);
  24779. this._trackGain.connect(this._audioEngine.masterGain);
  24780. if (options) {
  24781. if (options.volume) {
  24782. this._trackGain.gain.value = options.volume;
  24783. }
  24784. if (options.mainTrack) {
  24785. this._isMainTrack = options.mainTrack;
  24786. }
  24787. }
  24788. }
  24789. if (!this._isMainTrack) {
  24790. this._scene.soundTracks.push(this);
  24791. this.id = this._scene.soundTracks.length - 1;
  24792. }
  24793. }
  24794. SoundTrack.prototype.AddSound = function (sound) {
  24795. sound.connectToSoundTrackAudioNode(this._trackGain);
  24796. if (sound.soundTrackId) {
  24797. if (sound.soundTrackId === -1) {
  24798. this._scene.mainSoundTrack.RemoveSound(sound);
  24799. } else {
  24800. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24801. }
  24802. }
  24803. this.soundCollection.push(sound);
  24804. sound.soundTrackId = this.id;
  24805. };
  24806. SoundTrack.prototype.RemoveSound = function (sound) {
  24807. var index = this.soundCollection.indexOf(sound);
  24808. if (index !== -1) {
  24809. this.soundCollection.splice(index, 1);
  24810. }
  24811. };
  24812. SoundTrack.prototype.setVolume = function (newVolume) {
  24813. if (this._audioEngine.canUseWebAudio) {
  24814. this._trackGain.gain.value = newVolume;
  24815. }
  24816. };
  24817. return SoundTrack;
  24818. })();
  24819. BABYLON.SoundTrack = SoundTrack;
  24820. })(BABYLON || (BABYLON = {}));
  24821. //# sourceMappingURL=babylon.soundtrack.js.map
  24822. var BABYLON;
  24823. (function (BABYLON) {
  24824. var DebugLayer = (function () {
  24825. function DebugLayer(scene) {
  24826. var _this = this;
  24827. this._enabled = false;
  24828. this._labelsEnabled = false;
  24829. this._displayStatistics = true;
  24830. this._displayTree = false;
  24831. this._displayLogs = false;
  24832. this._identityMatrix = BABYLON.Matrix.Identity();
  24833. this.axisRatio = 0.02;
  24834. this.accentColor = "orange";
  24835. this._scene = scene;
  24836. this._syncPositions = function () {
  24837. var engine = _this._scene.getEngine();
  24838. var canvasRect = engine.getRenderingCanvasClientRect();
  24839. if (_this._showUI) {
  24840. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  24841. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  24842. _this._statsDiv.style.width = "400px";
  24843. _this._statsDiv.style.height = "auto";
  24844. _this._statsSubsetDiv.style.maxHeight = "240px";
  24845. _this._optionsDiv.style.left = "0px";
  24846. _this._optionsDiv.style.top = "10px";
  24847. _this._optionsDiv.style.width = "200px";
  24848. _this._optionsDiv.style.height = "auto";
  24849. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24850. _this._logDiv.style.left = "0px";
  24851. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24852. _this._logDiv.style.width = "600px";
  24853. _this._logDiv.style.height = "160px";
  24854. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24855. _this._treeDiv.style.top = "10px";
  24856. _this._treeDiv.style.width = "300px";
  24857. _this._treeDiv.style.height = "auto";
  24858. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  24859. }
  24860. _this._globalDiv.style.left = canvasRect.left + "px";
  24861. _this._globalDiv.style.top = canvasRect.top + "px";
  24862. _this._drawingCanvas.style.left = "0px";
  24863. _this._drawingCanvas.style.top = "0px";
  24864. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24865. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24866. var devicePixelRatio = window.devicePixelRatio || 1;
  24867. var context = _this._drawingContext;
  24868. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24869. _this._ratio = devicePixelRatio / backingStoreRatio;
  24870. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24871. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24872. };
  24873. this._onCanvasClick = function (evt) {
  24874. _this._clickPosition = {
  24875. x: evt.clientX * _this._ratio,
  24876. y: evt.clientY * _this._ratio
  24877. };
  24878. };
  24879. this._syncData = function () {
  24880. if (_this._showUI) {
  24881. if (_this._displayStatistics) {
  24882. _this._displayStats();
  24883. _this._statsDiv.style.display = "";
  24884. } else {
  24885. _this._statsDiv.style.display = "none";
  24886. }
  24887. if (_this._displayLogs) {
  24888. _this._logDiv.style.display = "";
  24889. } else {
  24890. _this._logDiv.style.display = "none";
  24891. }
  24892. if (_this._displayTree) {
  24893. _this._treeDiv.style.display = "";
  24894. if (_this._needToRefreshMeshesTree) {
  24895. _this._needToRefreshMeshesTree = false;
  24896. _this._refreshMeshesTreeContent();
  24897. }
  24898. } else {
  24899. _this._treeDiv.style.display = "none";
  24900. }
  24901. }
  24902. if (_this._labelsEnabled || !_this._showUI) {
  24903. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24904. var engine = _this._scene.getEngine();
  24905. var viewport = _this._scene.activeCamera.viewport;
  24906. var globalViewport = viewport.toGlobal(engine);
  24907. // Meshes
  24908. var meshes = _this._scene.getActiveMeshes();
  24909. for (var index = 0; index < meshes.length; index++) {
  24910. var mesh = meshes.data[index];
  24911. var position = mesh.getBoundingInfo().boundingSphere.center;
  24912. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24913. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24914. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24915. }
  24916. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24917. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24918. mesh.renderOverlay = !mesh.renderOverlay;
  24919. }, function () {
  24920. return mesh.renderOverlay ? 'red' : 'black';
  24921. });
  24922. }
  24923. }
  24924. // Cameras
  24925. var cameras = _this._scene.cameras;
  24926. for (index = 0; index < cameras.length; index++) {
  24927. var camera = cameras[index];
  24928. if (camera === _this._scene.activeCamera) {
  24929. continue;
  24930. }
  24931. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24932. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24933. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24934. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24935. _this._scene.activeCamera = camera;
  24936. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24937. }, function () {
  24938. return "purple";
  24939. });
  24940. }
  24941. }
  24942. // Lights
  24943. var lights = _this._scene.lights;
  24944. for (index = 0; index < lights.length; index++) {
  24945. var light = lights[index];
  24946. if (light.position) {
  24947. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24948. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24949. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24950. light.setEnabled(!light.isEnabled());
  24951. }, function () {
  24952. return light.isEnabled() ? "orange" : "gray";
  24953. });
  24954. }
  24955. }
  24956. }
  24957. }
  24958. _this._clickPosition = undefined;
  24959. };
  24960. }
  24961. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24962. while (this._treeSubsetDiv.hasChildNodes()) {
  24963. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24964. }
  24965. // Add meshes
  24966. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24967. sortedArray.sort(function (a, b) {
  24968. if (a.name === b.name) {
  24969. return 0;
  24970. }
  24971. return (a.name > b.name) ? 1 : -1;
  24972. });
  24973. for (var index = 0; index < sortedArray.length; index++) {
  24974. var mesh = sortedArray[index];
  24975. if (!mesh.isEnabled()) {
  24976. continue;
  24977. }
  24978. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24979. m.isVisible = element.checked;
  24980. }, mesh);
  24981. }
  24982. };
  24983. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24984. this._drawingContext.beginPath();
  24985. this._drawingContext.moveTo(zero.x, zero.y);
  24986. this._drawingContext.lineTo(unit.x, unit.y);
  24987. this._drawingContext.strokeStyle = color;
  24988. this._drawingContext.lineWidth = 4;
  24989. this._drawingContext.stroke();
  24990. this._drawingContext.font = "normal 14px Segoe UI";
  24991. this._drawingContext.fillStyle = color;
  24992. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24993. };
  24994. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24995. var position = mesh.getBoundingInfo().boundingSphere.center;
  24996. var worldMatrix = mesh.getWorldMatrix();
  24997. 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());
  24998. var unit = (unprojectedVector.subtract(position)).length();
  24999. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25000. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25001. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25002. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25003. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25004. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25005. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25006. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25007. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25008. };
  25009. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25010. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25011. this._drawingContext.font = "normal 12px Segoe UI";
  25012. var textMetrics = this._drawingContext.measureText(text);
  25013. var centerX = projectedPosition.x - textMetrics.width / 2;
  25014. var centerY = projectedPosition.y;
  25015. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25016. onClick();
  25017. }
  25018. this._drawingContext.beginPath();
  25019. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25020. this._drawingContext.fillStyle = getFillStyle();
  25021. this._drawingContext.globalAlpha = 0.5;
  25022. this._drawingContext.fill();
  25023. this._drawingContext.globalAlpha = 1.0;
  25024. this._drawingContext.strokeStyle = '#FFFFFF';
  25025. this._drawingContext.lineWidth = 1;
  25026. this._drawingContext.stroke();
  25027. this._drawingContext.fillStyle = "#FFFFFF";
  25028. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25029. this._drawingContext.beginPath();
  25030. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25031. this._drawingContext.fill();
  25032. }
  25033. };
  25034. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25035. if (!this._clickPosition) {
  25036. return false;
  25037. }
  25038. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25039. return false;
  25040. }
  25041. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25042. return false;
  25043. }
  25044. return true;
  25045. };
  25046. DebugLayer.prototype.isVisible = function () {
  25047. return this._enabled;
  25048. };
  25049. DebugLayer.prototype.hide = function () {
  25050. if (!this._enabled) {
  25051. return;
  25052. }
  25053. this._enabled = false;
  25054. var engine = this._scene.getEngine();
  25055. this._scene.unregisterAfterRender(this._syncData);
  25056. document.body.removeChild(this._globalDiv);
  25057. window.removeEventListener("resize", this._syncPositions);
  25058. this._scene.forceShowBoundingBoxes = false;
  25059. this._scene.forceWireframe = false;
  25060. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25061. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25062. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25063. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25064. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25065. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25066. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25067. this._scene.shadowsEnabled = true;
  25068. this._scene.particlesEnabled = true;
  25069. this._scene.postProcessesEnabled = true;
  25070. this._scene.collisionsEnabled = true;
  25071. this._scene.lightsEnabled = true;
  25072. this._scene.texturesEnabled = true;
  25073. this._scene.lensFlaresEnabled = true;
  25074. this._scene.proceduralTexturesEnabled = true;
  25075. this._scene.renderTargetsEnabled = true;
  25076. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25077. };
  25078. DebugLayer.prototype.show = function (showUI) {
  25079. if (typeof showUI === "undefined") { showUI = true; }
  25080. if (this._enabled) {
  25081. return;
  25082. }
  25083. this._enabled = true;
  25084. this._showUI = showUI;
  25085. var engine = this._scene.getEngine();
  25086. this._globalDiv = document.createElement("div");
  25087. document.body.appendChild(this._globalDiv);
  25088. this._generateDOMelements();
  25089. window.addEventListener("resize", this._syncPositions);
  25090. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25091. this._syncPositions();
  25092. this._scene.registerAfterRender(this._syncData);
  25093. };
  25094. DebugLayer.prototype._clearLabels = function () {
  25095. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25096. for (var index = 0; index < this._scene.meshes.length; index++) {
  25097. var mesh = this._scene.meshes[index];
  25098. mesh.renderOverlay = false;
  25099. }
  25100. };
  25101. DebugLayer.prototype._generateheader = function (root, text) {
  25102. var header = document.createElement("div");
  25103. header.innerHTML = text + "&nbsp;";
  25104. header.style.textAlign = "right";
  25105. header.style.width = "100%";
  25106. header.style.color = "white";
  25107. header.style.backgroundColor = "Black";
  25108. header.style.padding = "5px 5px 4px 0px";
  25109. header.style.marginLeft = "-5px";
  25110. header.style.fontWeight = "bold";
  25111. root.appendChild(header);
  25112. };
  25113. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25114. var label = document.createElement("label");
  25115. label.innerHTML = title;
  25116. label.style.color = color;
  25117. root.appendChild(label);
  25118. root.appendChild(document.createElement("br"));
  25119. };
  25120. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25121. if (typeof tag === "undefined") { tag = null; }
  25122. var label = document.createElement("label");
  25123. var boundingBoxesCheckbox = document.createElement("input");
  25124. boundingBoxesCheckbox.type = "checkbox";
  25125. boundingBoxesCheckbox.checked = initialState;
  25126. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25127. task(evt.target, tag);
  25128. });
  25129. label.appendChild(boundingBoxesCheckbox);
  25130. var container = document.createElement("span");
  25131. var leftPart = document.createElement("span");
  25132. var rightPart = document.createElement("span");
  25133. rightPart.style.cssFloat = "right";
  25134. leftPart.innerHTML = leftTitle;
  25135. rightPart.innerHTML = rightTitle;
  25136. rightPart.style.fontSize = "12px";
  25137. rightPart.style.maxWidth = "200px";
  25138. container.appendChild(leftPart);
  25139. container.appendChild(rightPart);
  25140. label.appendChild(container);
  25141. root.appendChild(label);
  25142. root.appendChild(document.createElement("br"));
  25143. };
  25144. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25145. if (typeof tag === "undefined") { tag = null; }
  25146. var label = document.createElement("label");
  25147. var boundingBoxesCheckbox = document.createElement("input");
  25148. boundingBoxesCheckbox.type = "checkbox";
  25149. boundingBoxesCheckbox.checked = initialState;
  25150. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25151. task(evt.target, tag);
  25152. });
  25153. label.appendChild(boundingBoxesCheckbox);
  25154. label.appendChild(document.createTextNode(title));
  25155. root.appendChild(label);
  25156. root.appendChild(document.createElement("br"));
  25157. };
  25158. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25159. if (typeof tag === "undefined") { tag = null; }
  25160. var label = document.createElement("label");
  25161. var boundingBoxesRadio = document.createElement("input");
  25162. boundingBoxesRadio.type = "radio";
  25163. boundingBoxesRadio.name = name;
  25164. boundingBoxesRadio.checked = initialState;
  25165. boundingBoxesRadio.addEventListener("change", function (evt) {
  25166. task(evt.target, tag);
  25167. });
  25168. label.appendChild(boundingBoxesRadio);
  25169. label.appendChild(document.createTextNode(title));
  25170. root.appendChild(label);
  25171. root.appendChild(document.createElement("br"));
  25172. };
  25173. DebugLayer.prototype._generateDOMelements = function () {
  25174. var _this = this;
  25175. this._globalDiv.id = "DebugLayer";
  25176. this._globalDiv.style.position = "absolute";
  25177. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25178. this._globalDiv.style.fontSize = "14px";
  25179. this._globalDiv.style.color = "white";
  25180. // Drawing canvas
  25181. this._drawingCanvas = document.createElement("canvas");
  25182. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25183. this._drawingCanvas.style.position = "absolute";
  25184. this._drawingCanvas.style.pointerEvents = "none";
  25185. this._drawingContext = this._drawingCanvas.getContext("2d");
  25186. this._globalDiv.appendChild(this._drawingCanvas);
  25187. if (this._showUI) {
  25188. var background = "rgba(128, 128, 128, 0.4)";
  25189. var border = "rgb(180, 180, 180) solid 1px";
  25190. // Stats
  25191. this._statsDiv = document.createElement("div");
  25192. this._statsDiv.id = "DebugLayerStats";
  25193. this._statsDiv.style.border = border;
  25194. this._statsDiv.style.position = "absolute";
  25195. this._statsDiv.style.background = background;
  25196. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25197. this._generateheader(this._statsDiv, "STATISTICS");
  25198. this._statsSubsetDiv = document.createElement("div");
  25199. this._statsSubsetDiv.style.paddingTop = "5px";
  25200. this._statsSubsetDiv.style.paddingBottom = "5px";
  25201. this._statsSubsetDiv.style.overflowY = "auto";
  25202. this._statsDiv.appendChild(this._statsSubsetDiv);
  25203. // Tree
  25204. this._treeDiv = document.createElement("div");
  25205. this._treeDiv.id = "DebugLayerTree";
  25206. this._treeDiv.style.border = border;
  25207. this._treeDiv.style.position = "absolute";
  25208. this._treeDiv.style.background = background;
  25209. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25210. this._treeDiv.style.display = "none";
  25211. this._generateheader(this._treeDiv, "MESHES TREE");
  25212. this._treeSubsetDiv = document.createElement("div");
  25213. this._treeSubsetDiv.style.paddingTop = "5px";
  25214. this._treeSubsetDiv.style.paddingRight = "5px";
  25215. this._treeSubsetDiv.style.overflowY = "auto";
  25216. this._treeSubsetDiv.style.maxHeight = "300px";
  25217. this._treeDiv.appendChild(this._treeSubsetDiv);
  25218. this._needToRefreshMeshesTree = true;
  25219. // Logs
  25220. this._logDiv = document.createElement("div");
  25221. this._logDiv.style.border = border;
  25222. this._logDiv.id = "DebugLayerLogs";
  25223. this._logDiv.style.position = "absolute";
  25224. this._logDiv.style.background = background;
  25225. this._logDiv.style.padding = "0px 0px 0px 5px";
  25226. this._logDiv.style.display = "none";
  25227. this._generateheader(this._logDiv, "LOGS");
  25228. this._logSubsetDiv = document.createElement("div");
  25229. this._logSubsetDiv.style.height = "127px";
  25230. this._logSubsetDiv.style.paddingTop = "5px";
  25231. this._logSubsetDiv.style.overflowY = "auto";
  25232. this._logSubsetDiv.style.fontSize = "12px";
  25233. this._logSubsetDiv.style.fontFamily = "consolas";
  25234. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25235. this._logDiv.appendChild(this._logSubsetDiv);
  25236. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25237. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25238. };
  25239. // Options
  25240. this._optionsDiv = document.createElement("div");
  25241. this._optionsDiv.id = "DebugLayerOptions";
  25242. this._optionsDiv.style.border = border;
  25243. this._optionsDiv.style.position = "absolute";
  25244. this._optionsDiv.style.background = background;
  25245. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25246. this._optionsDiv.style.overflowY = "auto";
  25247. this._generateheader(this._optionsDiv, "OPTIONS");
  25248. this._optionsSubsetDiv = document.createElement("div");
  25249. this._optionsSubsetDiv.style.paddingTop = "5px";
  25250. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25251. this._optionsSubsetDiv.style.overflowY = "auto";
  25252. this._optionsSubsetDiv.style.maxHeight = "200px";
  25253. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25254. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25255. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25256. _this._displayStatistics = element.checked;
  25257. });
  25258. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25259. _this._displayLogs = element.checked;
  25260. });
  25261. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25262. _this._displayTree = element.checked;
  25263. _this._needToRefreshMeshesTree = true;
  25264. });
  25265. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25266. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25267. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25268. _this._scene.forceShowBoundingBoxes = element.checked;
  25269. });
  25270. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25271. _this._labelsEnabled = element.checked;
  25272. if (!_this._labelsEnabled) {
  25273. _this._clearLabels();
  25274. }
  25275. });
  25276. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25277. if (element.checked) {
  25278. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25279. } else {
  25280. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25281. }
  25282. });
  25283. ;
  25284. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25285. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25286. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25287. if (element.checked) {
  25288. _this._scene.forceWireframe = false;
  25289. _this._scene.forcePointsCloud = false;
  25290. }
  25291. });
  25292. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25293. if (element.checked) {
  25294. _this._scene.forceWireframe = true;
  25295. _this._scene.forcePointsCloud = false;
  25296. }
  25297. });
  25298. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25299. if (element.checked) {
  25300. _this._scene.forceWireframe = false;
  25301. _this._scene.forcePointsCloud = true;
  25302. }
  25303. });
  25304. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25305. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25306. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25307. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25308. });
  25309. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25310. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25311. });
  25312. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25313. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25314. });
  25315. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25316. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25317. });
  25318. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25319. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25320. });
  25321. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25322. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25323. });
  25324. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25325. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25326. });
  25327. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25328. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25329. });
  25330. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25331. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25332. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25333. _this._scene.animationsEnabled = element.checked;
  25334. });
  25335. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25336. _this._scene.collisionsEnabled = element.checked;
  25337. });
  25338. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25339. _this._scene.fogEnabled = element.checked;
  25340. });
  25341. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25342. _this._scene.lensFlaresEnabled = element.checked;
  25343. });
  25344. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25345. _this._scene.lightsEnabled = element.checked;
  25346. });
  25347. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25348. _this._scene.particlesEnabled = element.checked;
  25349. });
  25350. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25351. _this._scene.postProcessesEnabled = element.checked;
  25352. });
  25353. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25354. _this._scene.proceduralTexturesEnabled = element.checked;
  25355. });
  25356. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25357. _this._scene.renderTargetsEnabled = element.checked;
  25358. });
  25359. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25360. _this._scene.shadowsEnabled = element.checked;
  25361. });
  25362. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25363. _this._scene.skeletonsEnabled = element.checked;
  25364. });
  25365. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25366. _this._scene.texturesEnabled = element.checked;
  25367. });
  25368. this._globalDiv.appendChild(this._statsDiv);
  25369. this._globalDiv.appendChild(this._logDiv);
  25370. this._globalDiv.appendChild(this._optionsDiv);
  25371. this._globalDiv.appendChild(this._treeDiv);
  25372. }
  25373. };
  25374. DebugLayer.prototype._displayStats = function () {
  25375. var scene = this._scene;
  25376. var engine = scene.getEngine();
  25377. var glInfo = engine.getGlInfo();
  25378. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  25379. if (this.customStatsFunction) {
  25380. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25381. }
  25382. };
  25383. return DebugLayer;
  25384. })();
  25385. BABYLON.DebugLayer = DebugLayer;
  25386. })(BABYLON || (BABYLON = {}));
  25387. //# sourceMappingURL=babylon.debugLayer.js.map
  25388. var BABYLON;
  25389. (function (BABYLON) {
  25390. var RawTexture = (function (_super) {
  25391. __extends(RawTexture, _super);
  25392. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25393. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25394. if (typeof invertY === "undefined") { invertY = false; }
  25395. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25396. _super.call(this, null, scene, !generateMipMaps, invertY);
  25397. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25398. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25399. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25400. }
  25401. // Statics
  25402. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25403. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25404. if (typeof invertY === "undefined") { invertY = false; }
  25405. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25406. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25407. };
  25408. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25409. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25410. if (typeof invertY === "undefined") { invertY = false; }
  25411. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25412. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25413. };
  25414. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25415. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25416. if (typeof invertY === "undefined") { invertY = false; }
  25417. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25418. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25419. };
  25420. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25421. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25422. if (typeof invertY === "undefined") { invertY = false; }
  25423. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25424. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25425. };
  25426. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25427. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25428. if (typeof invertY === "undefined") { invertY = false; }
  25429. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25430. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25431. };
  25432. return RawTexture;
  25433. })(BABYLON.Texture);
  25434. BABYLON.RawTexture = RawTexture;
  25435. })(BABYLON || (BABYLON = {}));
  25436. //# sourceMappingURL=babylon.rawTexture.js.map
  25437. var BABYLON;
  25438. (function (BABYLON) {
  25439. var IndexedVector2 = (function (_super) {
  25440. __extends(IndexedVector2, _super);
  25441. function IndexedVector2(original, index) {
  25442. _super.call(this, original.x, original.y);
  25443. this.index = index;
  25444. }
  25445. return IndexedVector2;
  25446. })(BABYLON.Vector2);
  25447. var PolygonPoints = (function () {
  25448. function PolygonPoints() {
  25449. this.elements = new Array();
  25450. }
  25451. PolygonPoints.prototype.add = function (originalPoints) {
  25452. var _this = this;
  25453. var result = new Array();
  25454. originalPoints.forEach(function (point) {
  25455. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25456. var newPoint = new IndexedVector2(point, _this.elements.length);
  25457. result.push(newPoint);
  25458. _this.elements.push(newPoint);
  25459. }
  25460. });
  25461. return result;
  25462. };
  25463. PolygonPoints.prototype.computeBounds = function () {
  25464. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25465. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25466. this.elements.forEach(function (point) {
  25467. // x
  25468. if (point.x < lmin.x) {
  25469. lmin.x = point.x;
  25470. } else if (point.x > lmax.x) {
  25471. lmax.x = point.x;
  25472. }
  25473. // y
  25474. if (point.y < lmin.y) {
  25475. lmin.y = point.y;
  25476. } else if (point.y > lmax.y) {
  25477. lmax.y = point.y;
  25478. }
  25479. });
  25480. return {
  25481. min: lmin,
  25482. max: lmax,
  25483. width: lmax.x - lmin.x,
  25484. height: lmax.y - lmin.y
  25485. };
  25486. };
  25487. return PolygonPoints;
  25488. })();
  25489. var Polygon = (function () {
  25490. function Polygon() {
  25491. }
  25492. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25493. return [
  25494. new BABYLON.Vector2(xmin, ymin),
  25495. new BABYLON.Vector2(xmax, ymin),
  25496. new BABYLON.Vector2(xmax, ymax),
  25497. new BABYLON.Vector2(xmin, ymax)
  25498. ];
  25499. };
  25500. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25501. if (typeof cx === "undefined") { cx = 0; }
  25502. if (typeof cy === "undefined") { cy = 0; }
  25503. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25504. var result = new Array();
  25505. var angle = 0;
  25506. var increment = (Math.PI * 2) / numberOfSides;
  25507. for (var i = 0; i < numberOfSides; i++) {
  25508. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25509. angle -= increment;
  25510. }
  25511. return result;
  25512. };
  25513. Polygon.Parse = function (input) {
  25514. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25515. return (!isNaN(val));
  25516. });
  25517. var i, result = [];
  25518. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25519. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25520. }
  25521. return result;
  25522. };
  25523. Polygon.StartingAt = function (x, y) {
  25524. return BABYLON.Path2.StartingAt(x, y);
  25525. };
  25526. return Polygon;
  25527. })();
  25528. BABYLON.Polygon = Polygon;
  25529. var PolygonMeshBuilder = (function () {
  25530. function PolygonMeshBuilder(name, contours, scene) {
  25531. this._points = new PolygonPoints();
  25532. if (!("poly2tri" in window)) {
  25533. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25534. }
  25535. this._name = name;
  25536. this._scene = scene;
  25537. var points;
  25538. if (contours instanceof BABYLON.Path2) {
  25539. points = contours.getPoints();
  25540. } else {
  25541. points = contours;
  25542. }
  25543. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25544. }
  25545. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25546. this._swctx.addHole(this._points.add(hole));
  25547. return this;
  25548. };
  25549. PolygonMeshBuilder.prototype.build = function (updatable) {
  25550. if (typeof updatable === "undefined") { updatable = false; }
  25551. var result = new BABYLON.Mesh(this._name, this._scene);
  25552. var normals = [];
  25553. var positions = [];
  25554. var uvs = [];
  25555. var bounds = this._points.computeBounds();
  25556. this._points.elements.forEach(function (p) {
  25557. normals.push(0, 1.0, 0);
  25558. positions.push(p.x, 0, p.y);
  25559. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25560. });
  25561. var indices = [];
  25562. this._swctx.triangulate();
  25563. this._swctx.getTriangles().forEach(function (triangle) {
  25564. triangle.getPoints().forEach(function (point) {
  25565. indices.push(point.index);
  25566. });
  25567. });
  25568. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25569. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25570. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25571. result.setIndices(indices);
  25572. return result;
  25573. };
  25574. return PolygonMeshBuilder;
  25575. })();
  25576. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25577. })(BABYLON || (BABYLON = {}));
  25578. //# sourceMappingURL=babylon.polygonMesh.js.map
  25579. var BABYLON;
  25580. (function (BABYLON) {
  25581. var SimplificationSettings = (function () {
  25582. function SimplificationSettings(quality, distance) {
  25583. this.quality = quality;
  25584. this.distance = distance;
  25585. }
  25586. return SimplificationSettings;
  25587. })();
  25588. BABYLON.SimplificationSettings = SimplificationSettings;
  25589. /**
  25590. * The implemented types of simplification.
  25591. * At the moment only Quadratic Error Decimation is implemented.
  25592. */
  25593. (function (SimplificationType) {
  25594. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  25595. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  25596. var SimplificationType = BABYLON.SimplificationType;
  25597. var DecimationTriangle = (function () {
  25598. function DecimationTriangle(vertices) {
  25599. this.vertices = vertices;
  25600. this.error = new Array(4);
  25601. this.deleted = false;
  25602. this.isDirty = false;
  25603. this.borderFactor = 0;
  25604. }
  25605. return DecimationTriangle;
  25606. })();
  25607. BABYLON.DecimationTriangle = DecimationTriangle;
  25608. var DecimationVertex = (function () {
  25609. function DecimationVertex(position, normal, uv, id) {
  25610. this.position = position;
  25611. this.normal = normal;
  25612. this.uv = uv;
  25613. this.id = id;
  25614. this.isBorder = true;
  25615. this.q = new QuadraticMatrix();
  25616. this.triangleCount = 0;
  25617. this.triangleStart = 0;
  25618. }
  25619. return DecimationVertex;
  25620. })();
  25621. BABYLON.DecimationVertex = DecimationVertex;
  25622. var QuadraticMatrix = (function () {
  25623. function QuadraticMatrix(data) {
  25624. this.data = new Array(10);
  25625. for (var i = 0; i < 10; ++i) {
  25626. if (data && data[i]) {
  25627. this.data[i] = data[i];
  25628. } else {
  25629. this.data[i] = 0;
  25630. }
  25631. }
  25632. }
  25633. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  25634. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  25635. return det;
  25636. };
  25637. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  25638. for (var i = 0; i < 10; ++i) {
  25639. this.data[i] += matrix.data[i];
  25640. }
  25641. };
  25642. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  25643. for (var i = 0; i < 10; ++i) {
  25644. this.data[i] += data[i];
  25645. }
  25646. };
  25647. QuadraticMatrix.prototype.add = function (matrix) {
  25648. var m = new QuadraticMatrix();
  25649. for (var i = 0; i < 10; ++i) {
  25650. m.data[i] = this.data[i] + matrix.data[i];
  25651. }
  25652. return m;
  25653. };
  25654. QuadraticMatrix.FromData = function (a, b, c, d) {
  25655. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  25656. };
  25657. //returning an array to avoid garbage collection
  25658. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  25659. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  25660. };
  25661. return QuadraticMatrix;
  25662. })();
  25663. BABYLON.QuadraticMatrix = QuadraticMatrix;
  25664. var Reference = (function () {
  25665. function Reference(vertexId, triangleId) {
  25666. this.vertexId = vertexId;
  25667. this.triangleId = triangleId;
  25668. }
  25669. return Reference;
  25670. })();
  25671. BABYLON.Reference = Reference;
  25672. /**
  25673. * An implementation of the Quadratic Error simplification algorithm.
  25674. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  25675. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  25676. * @author RaananW
  25677. */
  25678. var QuadraticErrorSimplification = (function () {
  25679. function QuadraticErrorSimplification(_mesh) {
  25680. this._mesh = _mesh;
  25681. this.initialised = false;
  25682. this.syncIterations = 5000;
  25683. this.aggressiveness = 7;
  25684. this.decimationIterations = 100;
  25685. }
  25686. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  25687. var _this = this;
  25688. this.initWithMesh(this._mesh, function () {
  25689. _this.runDecimation(settings, successCallback);
  25690. });
  25691. };
  25692. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  25693. var _this = this;
  25694. var targetCount = ~~(this.triangles.length * settings.quality);
  25695. var deletedTriangles = 0;
  25696. var triangleCount = this.triangles.length;
  25697. var iterationFunction = function (iteration, callback) {
  25698. setTimeout(function () {
  25699. if (iteration % 5 === 0) {
  25700. _this.updateMesh(iteration === 0);
  25701. }
  25702. for (var i = 0; i < _this.triangles.length; ++i) {
  25703. _this.triangles[i].isDirty = false;
  25704. }
  25705. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  25706. var trianglesIterator = function (i) {
  25707. var t = _this.triangles[i];
  25708. if (!t)
  25709. return;
  25710. if (t.error[3] > threshold) {
  25711. return;
  25712. }
  25713. if (t.deleted) {
  25714. return;
  25715. }
  25716. if (t.isDirty) {
  25717. return;
  25718. }
  25719. for (var j = 0; j < 3; ++j) {
  25720. if (t.error[j] < threshold) {
  25721. var deleted0 = [];
  25722. var deleted1 = [];
  25723. var i0 = t.vertices[j];
  25724. var i1 = t.vertices[(j + 1) % 3];
  25725. var v0 = _this.vertices[i0];
  25726. var v1 = _this.vertices[i1];
  25727. if (v0.isBorder !== v1.isBorder)
  25728. continue;
  25729. var p = BABYLON.Vector3.Zero();
  25730. var n = BABYLON.Vector3.Zero();
  25731. var uv = BABYLON.Vector2.Zero();
  25732. _this.calculateError(v0, v1, p, n, uv);
  25733. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  25734. continue;
  25735. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  25736. continue;
  25737. v0.position = p;
  25738. v0.normal = n;
  25739. v0.uv = uv;
  25740. v0.q = v1.q.add(v0.q);
  25741. var tStart = _this.references.length;
  25742. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  25743. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  25744. var tCount = _this.references.length - tStart;
  25745. if (tCount <= v0.triangleCount) {
  25746. if (tCount) {
  25747. for (var c = 0; c < tCount; c++) {
  25748. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  25749. }
  25750. }
  25751. } else {
  25752. v0.triangleStart = tStart;
  25753. }
  25754. v0.triangleCount = tCount;
  25755. break;
  25756. }
  25757. }
  25758. };
  25759. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  25760. return (triangleCount - deletedTriangles <= targetCount);
  25761. });
  25762. }, 0);
  25763. };
  25764. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  25765. if (triangleCount - deletedTriangles <= targetCount)
  25766. loop.breakLoop();
  25767. else {
  25768. iterationFunction(loop.index, function () {
  25769. loop.executeNext();
  25770. });
  25771. }
  25772. }, function () {
  25773. setTimeout(function () {
  25774. successCallback(_this.reconstructMesh());
  25775. }, 0);
  25776. });
  25777. };
  25778. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  25779. var _this = this;
  25780. if (!mesh)
  25781. return;
  25782. this.vertices = [];
  25783. this.triangles = [];
  25784. this._mesh = mesh;
  25785. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25786. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25787. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25788. var indices = mesh.getIndices();
  25789. var vertexInit = function (i) {
  25790. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), BABYLON.Vector2.FromArray(uvs, i * 2), i);
  25791. _this.vertices.push(vertex);
  25792. };
  25793. var totalVertices = mesh.getTotalVertices();
  25794. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  25795. var indicesInit = function (i) {
  25796. var pos = i * 3;
  25797. var i0 = indices[pos + 0];
  25798. var i1 = indices[pos + 1];
  25799. var i2 = indices[pos + 2];
  25800. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  25801. _this.triangles.push(triangle);
  25802. };
  25803. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  25804. _this.init(callback);
  25805. });
  25806. });
  25807. };
  25808. QuadraticErrorSimplification.prototype.init = function (callback) {
  25809. var _this = this;
  25810. var triangleInit1 = function (i) {
  25811. var t = _this.triangles[i];
  25812. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  25813. for (var j = 0; j < 3; j++) {
  25814. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  25815. }
  25816. };
  25817. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  25818. var triangleInit2 = function (i) {
  25819. var t = _this.triangles[i];
  25820. for (var j = 0; j < 3; ++j) {
  25821. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  25822. }
  25823. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  25824. };
  25825. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  25826. _this.initialised = true;
  25827. callback();
  25828. });
  25829. });
  25830. };
  25831. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  25832. var newTriangles = [];
  25833. var i;
  25834. for (i = 0; i < this.vertices.length; ++i) {
  25835. this.vertices[i].triangleCount = 0;
  25836. }
  25837. var t;
  25838. var j;
  25839. for (i = 0; i < this.triangles.length; ++i) {
  25840. if (!this.triangles[i].deleted) {
  25841. t = this.triangles[i];
  25842. for (j = 0; j < 3; ++j) {
  25843. this.vertices[t.vertices[j]].triangleCount = 1;
  25844. }
  25845. newTriangles.push(t);
  25846. }
  25847. }
  25848. var newVerticesOrder = [];
  25849. //compact vertices, get the IDs of the vertices used.
  25850. var dst = 0;
  25851. for (i = 0; i < this.vertices.length; ++i) {
  25852. if (this.vertices[i].triangleCount) {
  25853. this.vertices[i].triangleStart = dst;
  25854. this.vertices[dst].position = this.vertices[i].position;
  25855. this.vertices[dst].normal = this.vertices[i].normal;
  25856. this.vertices[dst].uv = this.vertices[i].uv;
  25857. newVerticesOrder.push(i);
  25858. dst++;
  25859. }
  25860. }
  25861. for (i = 0; i < newTriangles.length; ++i) {
  25862. t = newTriangles[i];
  25863. for (j = 0; j < 3; ++j) {
  25864. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  25865. }
  25866. }
  25867. this.vertices = this.vertices.slice(0, dst);
  25868. var newPositionData = [];
  25869. var newNormalData = [];
  25870. var newUVsData = [];
  25871. for (i = 0; i < newVerticesOrder.length; ++i) {
  25872. newPositionData.push(this.vertices[i].position.x);
  25873. newPositionData.push(this.vertices[i].position.y);
  25874. newPositionData.push(this.vertices[i].position.z);
  25875. newNormalData.push(this.vertices[i].normal.x);
  25876. newNormalData.push(this.vertices[i].normal.y);
  25877. newNormalData.push(this.vertices[i].normal.z);
  25878. newUVsData.push(this.vertices[i].uv.x);
  25879. newUVsData.push(this.vertices[i].uv.y);
  25880. }
  25881. var newIndicesArray = [];
  25882. for (i = 0; i < newTriangles.length; ++i) {
  25883. newIndicesArray.push(newTriangles[i].vertices[0]);
  25884. newIndicesArray.push(newTriangles[i].vertices[1]);
  25885. newIndicesArray.push(newTriangles[i].vertices[2]);
  25886. }
  25887. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  25888. newMesh.material = this._mesh.material;
  25889. newMesh.parent = this._mesh.parent;
  25890. newMesh.setIndices(newIndicesArray);
  25891. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  25892. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  25893. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  25894. //preparing the skeleton support
  25895. if (this._mesh.skeleton) {
  25896. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  25897. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  25898. }
  25899. return newMesh;
  25900. };
  25901. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  25902. for (var i = 0; i < vertex1.triangleCount; ++i) {
  25903. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  25904. if (t.deleted)
  25905. continue;
  25906. var s = this.references[vertex1.triangleStart + i].vertexId;
  25907. var id1 = t.vertices[(s + 1) % 3];
  25908. var id2 = t.vertices[(s + 2) % 3];
  25909. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  25910. deletedArray[i] = true;
  25911. continue;
  25912. }
  25913. var d1 = this.vertices[id1].position.subtract(point);
  25914. d1 = d1.normalize();
  25915. var d2 = this.vertices[id2].position.subtract(point);
  25916. d2 = d2.normalize();
  25917. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  25918. return true;
  25919. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  25920. deletedArray[i] = false;
  25921. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  25922. return true;
  25923. }
  25924. return false;
  25925. };
  25926. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  25927. var newDeleted = deletedTriangles;
  25928. for (var i = 0; i < vertex.triangleCount; ++i) {
  25929. var ref = this.references[vertex.triangleStart + i];
  25930. var t = this.triangles[ref.triangleId];
  25931. if (t.deleted)
  25932. continue;
  25933. if (deletedArray[i]) {
  25934. t.deleted = true;
  25935. newDeleted++;
  25936. continue;
  25937. }
  25938. t.vertices[ref.vertexId] = vertexId;
  25939. t.isDirty = true;
  25940. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  25941. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  25942. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  25943. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  25944. this.references.push(ref);
  25945. }
  25946. return newDeleted;
  25947. };
  25948. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  25949. for (var i = 0; i < this.vertices.length; ++i) {
  25950. var vCount = [];
  25951. var vId = [];
  25952. var v = this.vertices[i];
  25953. var j;
  25954. for (j = 0; j < v.triangleCount; ++j) {
  25955. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  25956. for (var ii = 0; ii < 3; ii++) {
  25957. var ofs = 0;
  25958. var id = triangle.vertices[ii];
  25959. while (ofs < vCount.length) {
  25960. if (vId[ofs] === id)
  25961. break;
  25962. ++ofs;
  25963. }
  25964. if (ofs === vCount.length) {
  25965. vCount.push(1);
  25966. vId.push(id);
  25967. } else {
  25968. vCount[ofs]++;
  25969. }
  25970. }
  25971. }
  25972. for (j = 0; j < vCount.length; ++j) {
  25973. if (vCount[j] === 1) {
  25974. this.vertices[vId[j]].isBorder = true;
  25975. } else {
  25976. this.vertices[vId[j]].isBorder = false;
  25977. }
  25978. }
  25979. }
  25980. };
  25981. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  25982. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  25983. var i;
  25984. if (!identifyBorders) {
  25985. var newTrianglesVector = [];
  25986. for (i = 0; i < this.triangles.length; ++i) {
  25987. if (!this.triangles[i].deleted) {
  25988. newTrianglesVector.push(this.triangles[i]);
  25989. }
  25990. }
  25991. this.triangles = newTrianglesVector;
  25992. }
  25993. for (i = 0; i < this.vertices.length; ++i) {
  25994. this.vertices[i].triangleCount = 0;
  25995. this.vertices[i].triangleStart = 0;
  25996. }
  25997. var t;
  25998. var j;
  25999. var v;
  26000. for (i = 0; i < this.triangles.length; ++i) {
  26001. t = this.triangles[i];
  26002. for (j = 0; j < 3; ++j) {
  26003. v = this.vertices[t.vertices[j]];
  26004. v.triangleCount++;
  26005. }
  26006. }
  26007. var tStart = 0;
  26008. for (i = 0; i < this.vertices.length; ++i) {
  26009. this.vertices[i].triangleStart = tStart;
  26010. tStart += this.vertices[i].triangleCount;
  26011. this.vertices[i].triangleCount = 0;
  26012. }
  26013. var newReferences = new Array(this.triangles.length * 3);
  26014. for (i = 0; i < this.triangles.length; ++i) {
  26015. t = this.triangles[i];
  26016. for (j = 0; j < 3; ++j) {
  26017. v = this.vertices[t.vertices[j]];
  26018. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26019. v.triangleCount++;
  26020. }
  26021. }
  26022. this.references = newReferences;
  26023. if (identifyBorders) {
  26024. this.identifyBorder();
  26025. }
  26026. };
  26027. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26028. var x = point.x;
  26029. var y = point.y;
  26030. var z = point.z;
  26031. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  26032. };
  26033. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult) {
  26034. var q = vertex1.q.add(vertex2.q);
  26035. var border = vertex1.isBorder && vertex2.isBorder;
  26036. var error = 0;
  26037. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26038. if (qDet !== 0 && !border) {
  26039. if (!pointResult) {
  26040. pointResult = BABYLON.Vector3.Zero();
  26041. }
  26042. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26043. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26044. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26045. error = this.vertexError(q, pointResult);
  26046. //TODO this should be correctly calculated
  26047. if (normalResult) {
  26048. normalResult.copyFrom(vertex1.normal);
  26049. uvResult.copyFrom(vertex1.uv);
  26050. }
  26051. } else {
  26052. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26053. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  26054. var error1 = this.vertexError(q, vertex1.position);
  26055. var error2 = this.vertexError(q, vertex2.position);
  26056. var error3 = this.vertexError(q, p3);
  26057. error = Math.min(error1, error2, error3);
  26058. if (error === error1) {
  26059. if (pointResult) {
  26060. pointResult.copyFrom(vertex1.position);
  26061. normalResult.copyFrom(vertex1.normal);
  26062. uvResult.copyFrom(vertex1.uv);
  26063. }
  26064. } else if (error === error2) {
  26065. if (pointResult) {
  26066. pointResult.copyFrom(vertex2.position);
  26067. normalResult.copyFrom(vertex2.normal);
  26068. uvResult.copyFrom(vertex2.uv);
  26069. }
  26070. } else {
  26071. if (pointResult) {
  26072. pointResult.copyFrom(p3);
  26073. normalResult.copyFrom(norm3);
  26074. uvResult.copyFrom(vertex1.uv);
  26075. }
  26076. }
  26077. }
  26078. return error;
  26079. };
  26080. return QuadraticErrorSimplification;
  26081. })();
  26082. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  26083. })(BABYLON || (BABYLON = {}));
  26084. //# sourceMappingURL=babylon.meshSimplification.js.map