babylon.2.1-alpha.debug.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290
  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 (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { 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. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. 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));
  346. 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));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. 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;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. 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));
  685. 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));
  686. 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));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. 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);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. 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;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. 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)
  1152. }
  1153. else {
  1154. 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)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. 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));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. 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)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. 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))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocal(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. 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]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. 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]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. 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);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1889. // cc.kmVec3Cross(u, s, f);
  1890. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1895. //cc.kmMat4Identity(pOut);
  1896. //pOut.mat[0] = s.x;
  1897. //pOut.mat[4] = s.y;
  1898. //pOut.mat[8] = s.z;
  1899. //pOut.mat[1] = u.x;
  1900. //pOut.mat[5] = u.y;
  1901. //pOut.mat[9] = u.z;
  1902. //pOut.mat[2] = -f.x;
  1903. //pOut.mat[6] = -f.y;
  1904. //pOut.mat[10] = -f.z;
  1905. var zero = SIMD.float32x4.splat(0.0);
  1906. s = SIMD.float32x4.neg(s);
  1907. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1908. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1909. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1910. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1911. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1912. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1913. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1914. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1915. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1916. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1917. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1918. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1919. var b3 = SIMD.float32x4.neg(eye);
  1920. b3 = SIMD.float32x4.withW(b3, 1.0);
  1921. // cc.kmMat4Multiply(pOut, pOut, translate);
  1922. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1923. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1924. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1925. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1926. };
  1927. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1933. var hw = 2.0 / width;
  1934. var hh = 2.0 / height;
  1935. var id = 1.0 / (zfar - znear);
  1936. var nid = znear / (znear - zfar);
  1937. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1938. };
  1939. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1942. return matrix;
  1943. };
  1944. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1945. result.m[0] = 2.0 / (right - left);
  1946. result.m[1] = result.m[2] = result.m[3] = 0;
  1947. result.m[5] = 2.0 / (top - bottom);
  1948. result.m[4] = result.m[6] = result.m[7] = 0;
  1949. result.m[10] = -1.0 / (znear - zfar);
  1950. result.m[8] = result.m[9] = result.m[11] = 0;
  1951. result.m[12] = (left + right) / (left - right);
  1952. result.m[13] = (top + bottom) / (bottom - top);
  1953. result.m[14] = znear / (znear - zfar);
  1954. result.m[15] = 1.0;
  1955. };
  1956. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1957. var matrix = Matrix.Zero();
  1958. matrix.m[0] = (2.0 * znear) / width;
  1959. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1960. matrix.m[5] = (2.0 * znear) / height;
  1961. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1962. matrix.m[10] = -zfar / (znear - zfar);
  1963. matrix.m[8] = matrix.m[9] = 0.0;
  1964. matrix.m[11] = 1.0;
  1965. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1966. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1967. return matrix;
  1968. };
  1969. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1970. var matrix = Matrix.Zero();
  1971. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1972. return matrix;
  1973. };
  1974. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1975. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1976. var tan = 1.0 / (Math.tan(fov * 0.5));
  1977. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1978. if (v_fixed) {
  1979. result.m[0] = tan / aspect;
  1980. }
  1981. else {
  1982. result.m[0] = tan;
  1983. }
  1984. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1985. if (v_fixed) {
  1986. result.m[5] = tan;
  1987. }
  1988. else {
  1989. result.m[5] = tan * aspect;
  1990. }
  1991. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1992. result.m[8] = result.m[9] = 0.0;
  1993. result.m[10] = -zfar / (znear - zfar);
  1994. result.m[11] = 1.0;
  1995. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1996. result.m[14] = (znear * zfar) / (znear - zfar);
  1997. };
  1998. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1999. var cw = viewport.width;
  2000. var ch = viewport.height;
  2001. var cx = viewport.x;
  2002. var cy = viewport.y;
  2003. 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);
  2004. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2005. };
  2006. Matrix.Transpose = function (matrix) {
  2007. var result = new Matrix();
  2008. result.m[0] = matrix.m[0];
  2009. result.m[1] = matrix.m[4];
  2010. result.m[2] = matrix.m[8];
  2011. result.m[3] = matrix.m[12];
  2012. result.m[4] = matrix.m[1];
  2013. result.m[5] = matrix.m[5];
  2014. result.m[6] = matrix.m[9];
  2015. result.m[7] = matrix.m[13];
  2016. result.m[8] = matrix.m[2];
  2017. result.m[9] = matrix.m[6];
  2018. result.m[10] = matrix.m[10];
  2019. result.m[11] = matrix.m[14];
  2020. result.m[12] = matrix.m[3];
  2021. result.m[13] = matrix.m[7];
  2022. result.m[14] = matrix.m[11];
  2023. result.m[15] = matrix.m[15];
  2024. return result;
  2025. };
  2026. Matrix.Reflection = function (plane) {
  2027. var matrix = new Matrix();
  2028. Matrix.ReflectionToRef(plane, matrix);
  2029. return matrix;
  2030. };
  2031. Matrix.ReflectionToRef = function (plane, result) {
  2032. plane.normalize();
  2033. var x = plane.normal.x;
  2034. var y = plane.normal.y;
  2035. var z = plane.normal.z;
  2036. var temp = -2 * x;
  2037. var temp2 = -2 * y;
  2038. var temp3 = -2 * z;
  2039. result.m[0] = (temp * x) + 1;
  2040. result.m[1] = temp2 * x;
  2041. result.m[2] = temp3 * x;
  2042. result.m[3] = 0.0;
  2043. result.m[4] = temp * y;
  2044. result.m[5] = (temp2 * y) + 1;
  2045. result.m[6] = temp3 * y;
  2046. result.m[7] = 0.0;
  2047. result.m[8] = temp * z;
  2048. result.m[9] = temp2 * z;
  2049. result.m[10] = (temp3 * z) + 1;
  2050. result.m[11] = 0.0;
  2051. result.m[12] = temp * plane.d;
  2052. result.m[13] = temp2 * plane.d;
  2053. result.m[14] = temp3 * plane.d;
  2054. result.m[15] = 1.0;
  2055. };
  2056. Matrix._tempQuaternion = new Quaternion();
  2057. Matrix._xAxis = Vector3.Zero();
  2058. Matrix._yAxis = Vector3.Zero();
  2059. Matrix._zAxis = Vector3.Zero();
  2060. return Matrix;
  2061. })();
  2062. BABYLON.Matrix = Matrix;
  2063. var Plane = (function () {
  2064. function Plane(a, b, c, d) {
  2065. this.normal = new Vector3(a, b, c);
  2066. this.d = d;
  2067. }
  2068. Plane.prototype.asArray = function () {
  2069. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2070. };
  2071. // Methods
  2072. Plane.prototype.clone = function () {
  2073. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2074. };
  2075. Plane.prototype.normalize = function () {
  2076. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2077. var magnitude = 0;
  2078. if (norm !== 0) {
  2079. magnitude = 1.0 / norm;
  2080. }
  2081. this.normal.x *= magnitude;
  2082. this.normal.y *= magnitude;
  2083. this.normal.z *= magnitude;
  2084. this.d *= magnitude;
  2085. return this;
  2086. };
  2087. Plane.prototype.transform = function (transformation) {
  2088. var transposedMatrix = Matrix.Transpose(transformation);
  2089. var x = this.normal.x;
  2090. var y = this.normal.y;
  2091. var z = this.normal.z;
  2092. var d = this.d;
  2093. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2094. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2095. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2096. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2097. return new Plane(normalX, normalY, normalZ, finalD);
  2098. };
  2099. Plane.prototype.dotCoordinate = function (point) {
  2100. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2101. };
  2102. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2103. var x1 = point2.x - point1.x;
  2104. var y1 = point2.y - point1.y;
  2105. var z1 = point2.z - point1.z;
  2106. var x2 = point3.x - point1.x;
  2107. var y2 = point3.y - point1.y;
  2108. var z2 = point3.z - point1.z;
  2109. var yz = (y1 * z2) - (z1 * y2);
  2110. var xz = (z1 * x2) - (x1 * z2);
  2111. var xy = (x1 * y2) - (y1 * x2);
  2112. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2113. var invPyth;
  2114. if (pyth !== 0) {
  2115. invPyth = 1.0 / pyth;
  2116. }
  2117. else {
  2118. invPyth = 0;
  2119. }
  2120. this.normal.x = yz * invPyth;
  2121. this.normal.y = xz * invPyth;
  2122. this.normal.z = xy * invPyth;
  2123. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2124. return this;
  2125. };
  2126. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2127. var dot = Vector3.Dot(this.normal, direction);
  2128. return (dot <= epsilon);
  2129. };
  2130. Plane.prototype.signedDistanceTo = function (point) {
  2131. return Vector3.Dot(point, this.normal) + this.d;
  2132. };
  2133. // Statics
  2134. Plane.FromArray = function (array) {
  2135. return new Plane(array[0], array[1], array[2], array[3]);
  2136. };
  2137. Plane.FromPoints = function (point1, point2, point3) {
  2138. var result = new Plane(0, 0, 0, 0);
  2139. result.copyFromPoints(point1, point2, point3);
  2140. return result;
  2141. };
  2142. Plane.FromPositionAndNormal = function (origin, normal) {
  2143. var result = new Plane(0, 0, 0, 0);
  2144. normal.normalize();
  2145. result.normal = normal;
  2146. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2147. return result;
  2148. };
  2149. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2150. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2151. return Vector3.Dot(point, normal) + d;
  2152. };
  2153. return Plane;
  2154. })();
  2155. BABYLON.Plane = Plane;
  2156. var Viewport = (function () {
  2157. function Viewport(x, y, width, height) {
  2158. this.x = x;
  2159. this.y = y;
  2160. this.width = width;
  2161. this.height = height;
  2162. }
  2163. Viewport.prototype.toGlobal = function (engine) {
  2164. var width = engine.getRenderWidth();
  2165. var height = engine.getRenderHeight();
  2166. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2167. };
  2168. return Viewport;
  2169. })();
  2170. BABYLON.Viewport = Viewport;
  2171. var Frustum = (function () {
  2172. function Frustum() {
  2173. }
  2174. Frustum.GetPlanes = function (transform) {
  2175. var frustumPlanes = [];
  2176. for (var index = 0; index < 6; index++) {
  2177. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2178. }
  2179. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2180. return frustumPlanes;
  2181. };
  2182. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2183. // Near
  2184. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2185. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2186. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2187. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2188. frustumPlanes[0].normalize();
  2189. // Far
  2190. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2191. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2192. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2193. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2194. frustumPlanes[1].normalize();
  2195. // Left
  2196. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2197. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2198. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2199. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2200. frustumPlanes[2].normalize();
  2201. // Right
  2202. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2203. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2204. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2205. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2206. frustumPlanes[3].normalize();
  2207. // Top
  2208. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2209. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2210. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2211. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2212. frustumPlanes[4].normalize();
  2213. // Bottom
  2214. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2215. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2216. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2217. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2218. frustumPlanes[5].normalize();
  2219. };
  2220. return Frustum;
  2221. })();
  2222. BABYLON.Frustum = Frustum;
  2223. var Ray = (function () {
  2224. function Ray(origin, direction, length) {
  2225. if (length === void 0) { length = Number.MAX_VALUE; }
  2226. this.origin = origin;
  2227. this.direction = direction;
  2228. this.length = length;
  2229. }
  2230. // Methods
  2231. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2232. var d = 0.0;
  2233. var maxValue = Number.MAX_VALUE;
  2234. if (Math.abs(this.direction.x) < 0.0000001) {
  2235. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2236. return false;
  2237. }
  2238. }
  2239. else {
  2240. var inv = 1.0 / this.direction.x;
  2241. var min = (minimum.x - this.origin.x) * inv;
  2242. var max = (maximum.x - this.origin.x) * inv;
  2243. if (max === -Infinity) {
  2244. max = Infinity;
  2245. }
  2246. if (min > max) {
  2247. var temp = min;
  2248. min = max;
  2249. max = temp;
  2250. }
  2251. d = Math.max(min, d);
  2252. maxValue = Math.min(max, maxValue);
  2253. if (d > maxValue) {
  2254. return false;
  2255. }
  2256. }
  2257. if (Math.abs(this.direction.y) < 0.0000001) {
  2258. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2259. return false;
  2260. }
  2261. }
  2262. else {
  2263. inv = 1.0 / this.direction.y;
  2264. min = (minimum.y - this.origin.y) * inv;
  2265. max = (maximum.y - this.origin.y) * inv;
  2266. if (max === -Infinity) {
  2267. max = Infinity;
  2268. }
  2269. if (min > max) {
  2270. temp = min;
  2271. min = max;
  2272. max = temp;
  2273. }
  2274. d = Math.max(min, d);
  2275. maxValue = Math.min(max, maxValue);
  2276. if (d > maxValue) {
  2277. return false;
  2278. }
  2279. }
  2280. if (Math.abs(this.direction.z) < 0.0000001) {
  2281. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2282. return false;
  2283. }
  2284. }
  2285. else {
  2286. inv = 1.0 / this.direction.z;
  2287. min = (minimum.z - this.origin.z) * inv;
  2288. max = (maximum.z - this.origin.z) * inv;
  2289. if (max === -Infinity) {
  2290. max = Infinity;
  2291. }
  2292. if (min > max) {
  2293. temp = min;
  2294. min = max;
  2295. max = temp;
  2296. }
  2297. d = Math.max(min, d);
  2298. maxValue = Math.min(max, maxValue);
  2299. if (d > maxValue) {
  2300. return false;
  2301. }
  2302. }
  2303. return true;
  2304. };
  2305. Ray.prototype.intersectsBox = function (box) {
  2306. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2307. };
  2308. Ray.prototype.intersectsSphere = function (sphere) {
  2309. var x = sphere.center.x - this.origin.x;
  2310. var y = sphere.center.y - this.origin.y;
  2311. var z = sphere.center.z - this.origin.z;
  2312. var pyth = (x * x) + (y * y) + (z * z);
  2313. var rr = sphere.radius * sphere.radius;
  2314. if (pyth <= rr) {
  2315. return true;
  2316. }
  2317. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2318. if (dot < 0.0) {
  2319. return false;
  2320. }
  2321. var temp = pyth - (dot * dot);
  2322. return temp <= rr;
  2323. };
  2324. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2325. if (!this._edge1) {
  2326. this._edge1 = Vector3.Zero();
  2327. this._edge2 = Vector3.Zero();
  2328. this._pvec = Vector3.Zero();
  2329. this._tvec = Vector3.Zero();
  2330. this._qvec = Vector3.Zero();
  2331. }
  2332. vertex1.subtractToRef(vertex0, this._edge1);
  2333. vertex2.subtractToRef(vertex0, this._edge2);
  2334. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2335. var det = Vector3.Dot(this._edge1, this._pvec);
  2336. if (det === 0) {
  2337. return null;
  2338. }
  2339. var invdet = 1 / det;
  2340. this.origin.subtractToRef(vertex0, this._tvec);
  2341. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2342. if (bu < 0 || bu > 1.0) {
  2343. return null;
  2344. }
  2345. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2346. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2347. if (bv < 0 || bu + bv > 1.0) {
  2348. return null;
  2349. }
  2350. //check if the distance is longer than the predefined length.
  2351. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2352. if (distance > this.length) {
  2353. return null;
  2354. }
  2355. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2356. };
  2357. // Statics
  2358. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2359. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2360. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2361. var direction = end.subtract(start);
  2362. direction.normalize();
  2363. return new Ray(start, direction);
  2364. };
  2365. /**
  2366. * 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
  2367. * transformed to the given world matrix.
  2368. * @param origin The origin point
  2369. * @param end The end point
  2370. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2371. */
  2372. Ray.CreateNewFromTo = function (origin, end, world) {
  2373. if (world === void 0) { world = Matrix.Identity(); }
  2374. var direction = end.subtract(origin);
  2375. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2376. direction.normalize();
  2377. return Ray.Transform(new Ray(origin, direction, length), world);
  2378. };
  2379. Ray.Transform = function (ray, matrix) {
  2380. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2381. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2382. return new Ray(newOrigin, newDirection, ray.length);
  2383. };
  2384. return Ray;
  2385. })();
  2386. BABYLON.Ray = Ray;
  2387. (function (Space) {
  2388. Space[Space["LOCAL"] = 0] = "LOCAL";
  2389. Space[Space["WORLD"] = 1] = "WORLD";
  2390. })(BABYLON.Space || (BABYLON.Space = {}));
  2391. var Space = BABYLON.Space;
  2392. var Axis = (function () {
  2393. function Axis() {
  2394. }
  2395. Axis.X = new Vector3(1, 0, 0);
  2396. Axis.Y = new Vector3(0, 1, 0);
  2397. Axis.Z = new Vector3(0, 0, 1);
  2398. return Axis;
  2399. })();
  2400. BABYLON.Axis = Axis;
  2401. ;
  2402. var BezierCurve = (function () {
  2403. function BezierCurve() {
  2404. }
  2405. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2406. // Extract X (which is equal to time here)
  2407. var f0 = 1 - 3 * x2 + 3 * x1;
  2408. var f1 = 3 * x2 - 6 * x1;
  2409. var f2 = 3 * x1;
  2410. var refinedT = t;
  2411. for (var i = 0; i < 5; i++) {
  2412. var refinedT2 = refinedT * refinedT;
  2413. var refinedT3 = refinedT2 * refinedT;
  2414. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2415. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2416. refinedT -= (x - t) * slope;
  2417. refinedT = Math.min(1, Math.max(0, refinedT));
  2418. }
  2419. // Resolve cubic bezier for the given x
  2420. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2421. };
  2422. return BezierCurve;
  2423. })();
  2424. BABYLON.BezierCurve = BezierCurve;
  2425. (function (Orientation) {
  2426. Orientation[Orientation["CW"] = 0] = "CW";
  2427. Orientation[Orientation["CCW"] = 1] = "CCW";
  2428. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2429. var Orientation = BABYLON.Orientation;
  2430. var Angle = (function () {
  2431. function Angle(radians) {
  2432. var _this = this;
  2433. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2434. this.radians = function () { return _this._radians; };
  2435. this._radians = radians;
  2436. if (this._radians < 0)
  2437. this._radians += (2 * Math.PI);
  2438. }
  2439. Angle.BetweenTwoPoints = function (a, b) {
  2440. var delta = b.subtract(a);
  2441. var theta = Math.atan2(delta.y, delta.x);
  2442. return new Angle(theta);
  2443. };
  2444. Angle.FromRadians = function (radians) {
  2445. return new Angle(radians);
  2446. };
  2447. Angle.FromDegrees = function (degrees) {
  2448. return new Angle(degrees * Math.PI / 180);
  2449. };
  2450. return Angle;
  2451. })();
  2452. BABYLON.Angle = Angle;
  2453. var Arc2 = (function () {
  2454. function Arc2(startPoint, midPoint, endPoint) {
  2455. this.startPoint = startPoint;
  2456. this.midPoint = midPoint;
  2457. this.endPoint = endPoint;
  2458. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2459. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2460. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2461. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2462. 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);
  2463. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2464. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2465. var a1 = this.startAngle.degrees();
  2466. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2467. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2468. // angles correction
  2469. if (a2 - a1 > +180.0)
  2470. a2 -= 360.0;
  2471. if (a2 - a1 < -180.0)
  2472. a2 += 360.0;
  2473. if (a3 - a2 > +180.0)
  2474. a3 -= 360.0;
  2475. if (a3 - a2 < -180.0)
  2476. a3 += 360.0;
  2477. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2478. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2479. }
  2480. return Arc2;
  2481. })();
  2482. BABYLON.Arc2 = Arc2;
  2483. var PathCursor = (function () {
  2484. function PathCursor(path) {
  2485. this.path = path;
  2486. this._onchange = new Array();
  2487. this.value = 0;
  2488. this.animations = new Array();
  2489. }
  2490. PathCursor.prototype.getPoint = function () {
  2491. var point = this.path.getPointAtLengthPosition(this.value);
  2492. return new Vector3(point.x, 0, point.y);
  2493. };
  2494. PathCursor.prototype.moveAhead = function (step) {
  2495. if (step === void 0) { step = 0.002; }
  2496. this.move(step);
  2497. return this;
  2498. };
  2499. PathCursor.prototype.moveBack = function (step) {
  2500. if (step === void 0) { step = 0.002; }
  2501. this.move(-step);
  2502. return this;
  2503. };
  2504. PathCursor.prototype.move = function (step) {
  2505. if (Math.abs(step) > 1) {
  2506. throw "step size should be less than 1.";
  2507. }
  2508. this.value += step;
  2509. this.ensureLimits();
  2510. this.raiseOnChange();
  2511. return this;
  2512. };
  2513. PathCursor.prototype.ensureLimits = function () {
  2514. while (this.value > 1) {
  2515. this.value -= 1;
  2516. }
  2517. while (this.value < 0) {
  2518. this.value += 1;
  2519. }
  2520. return this;
  2521. };
  2522. // used by animation engine
  2523. PathCursor.prototype.markAsDirty = function (propertyName) {
  2524. this.ensureLimits();
  2525. this.raiseOnChange();
  2526. return this;
  2527. };
  2528. PathCursor.prototype.raiseOnChange = function () {
  2529. var _this = this;
  2530. this._onchange.forEach(function (f) { return f(_this); });
  2531. return this;
  2532. };
  2533. PathCursor.prototype.onchange = function (f) {
  2534. this._onchange.push(f);
  2535. return this;
  2536. };
  2537. return PathCursor;
  2538. })();
  2539. BABYLON.PathCursor = PathCursor;
  2540. var Path2 = (function () {
  2541. function Path2(x, y) {
  2542. this._points = new Array();
  2543. this._length = 0;
  2544. this.closed = false;
  2545. this._points.push(new Vector2(x, y));
  2546. }
  2547. Path2.prototype.addLineTo = function (x, y) {
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add lines to closed paths");
  2550. return this;
  2551. }
  2552. var newPoint = new Vector2(x, y);
  2553. var previousPoint = this._points[this._points.length - 1];
  2554. this._points.push(newPoint);
  2555. this._length += newPoint.subtract(previousPoint).length();
  2556. return this;
  2557. };
  2558. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2559. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2560. if (closed) {
  2561. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2562. return this;
  2563. }
  2564. var startPoint = this._points[this._points.length - 1];
  2565. var midPoint = new Vector2(midX, midY);
  2566. var endPoint = new Vector2(endX, endY);
  2567. var arc = new Arc2(startPoint, midPoint, endPoint);
  2568. var increment = arc.angle.radians() / numberOfSegments;
  2569. if (arc.orientation === 0 /* CW */)
  2570. increment *= -1;
  2571. var currentAngle = arc.startAngle.radians() + increment;
  2572. for (var i = 0; i < numberOfSegments; i++) {
  2573. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2574. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2575. this.addLineTo(x, y);
  2576. currentAngle += increment;
  2577. }
  2578. return this;
  2579. };
  2580. Path2.prototype.close = function () {
  2581. this.closed = true;
  2582. return this;
  2583. };
  2584. Path2.prototype.length = function () {
  2585. var result = this._length;
  2586. if (!this.closed) {
  2587. var lastPoint = this._points[this._points.length - 1];
  2588. var firstPoint = this._points[0];
  2589. result += (firstPoint.subtract(lastPoint).length());
  2590. }
  2591. return result;
  2592. };
  2593. Path2.prototype.getPoints = function () {
  2594. return this._points;
  2595. };
  2596. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2597. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2598. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2599. return Vector2.Zero();
  2600. }
  2601. var lengthPosition = normalizedLengthPosition * this.length();
  2602. var previousOffset = 0;
  2603. for (var i = 0; i < this._points.length; i++) {
  2604. var j = (i + 1) % this._points.length;
  2605. var a = this._points[i];
  2606. var b = this._points[j];
  2607. var bToA = b.subtract(a);
  2608. var nextOffset = (bToA.length() + previousOffset);
  2609. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2610. var dir = bToA.normalize();
  2611. var localOffset = lengthPosition - previousOffset;
  2612. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2613. }
  2614. previousOffset = nextOffset;
  2615. }
  2616. BABYLON.Tools.Error("internal error");
  2617. return Vector2.Zero();
  2618. };
  2619. Path2.StartingAt = function (x, y) {
  2620. return new Path2(x, y);
  2621. };
  2622. return Path2;
  2623. })();
  2624. BABYLON.Path2 = Path2;
  2625. var Path3D = (function () {
  2626. function Path3D(path) {
  2627. this.path = path;
  2628. this._curve = new Array();
  2629. this._distances = new Array();
  2630. this._tangents = new Array();
  2631. this._normals = new Array();
  2632. this._binormals = new Array();
  2633. this._curve = path.slice(); // copy array
  2634. this._compute();
  2635. }
  2636. Path3D.prototype.getCurve = function () {
  2637. return this._curve;
  2638. };
  2639. Path3D.prototype.getTangents = function () {
  2640. return this._tangents;
  2641. };
  2642. Path3D.prototype.getNormals = function () {
  2643. return this._normals;
  2644. };
  2645. Path3D.prototype.getBinormals = function () {
  2646. return this._binormals;
  2647. };
  2648. Path3D.prototype.getDistances = function () {
  2649. return this._distances;
  2650. };
  2651. Path3D.prototype.update = function (path) {
  2652. for (var i = 0; i < path.length; i++) {
  2653. this._curve[i] = path[i];
  2654. }
  2655. this._compute();
  2656. return this;
  2657. };
  2658. // private function compute() : computes tangents, normals and binormals
  2659. Path3D.prototype._compute = function () {
  2660. var l = this._curve.length;
  2661. // first and last tangents
  2662. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2663. this._tangents[0].normalize();
  2664. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2665. this._tangents[l - 1].normalize();
  2666. // normals and binormals at first point : arbitrary vector with _normalVector()
  2667. var tg0 = this._tangents[0];
  2668. var pp0 = this._normalVector(this._curve[0], tg0);
  2669. this._normals[0] = pp0;
  2670. this._normals[0].normalize();
  2671. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2672. this._normals[0].normalize();
  2673. this._distances[0] = 0;
  2674. // normals and binormals : next points
  2675. var prev; // previous vector (segment)
  2676. var cur; // current vector (segment)
  2677. var curTang; // current tangent
  2678. var prevNorm; // previous normal
  2679. var prevBinor; // previous binormal
  2680. for (var i = 1; i < l; i++) {
  2681. // tangents
  2682. prev = this._curve[i].subtract(this._curve[i - 1]);
  2683. if (i < l - 1) {
  2684. cur = this._curve[i + 1].subtract(this._curve[i]);
  2685. this._tangents[i] = prev.add(cur);
  2686. this._tangents[i].normalize();
  2687. }
  2688. this._distances[i] = this._distances[i - 1] + prev.length();
  2689. // normals and binormals
  2690. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2691. curTang = this._tangents[i];
  2692. prevNorm = this._normals[i - 1];
  2693. prevBinor = this._binormals[i - 1];
  2694. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2695. this._normals[i].normalize();
  2696. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2697. this._binormals[i].normalize();
  2698. }
  2699. };
  2700. // private function normalVector(v0, vt) :
  2701. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2702. Path3D.prototype._normalVector = function (v0, vt) {
  2703. var point;
  2704. if (vt.x !== 1) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (vt.y !== 1) {
  2708. point = new Vector3(0, 1, 0);
  2709. }
  2710. else if (vt.z !== 1) {
  2711. point = new Vector3(0, 0, 1);
  2712. }
  2713. var normal0 = Vector3.Cross(vt, point);
  2714. normal0.normalize();
  2715. return normal0;
  2716. };
  2717. return Path3D;
  2718. })();
  2719. BABYLON.Path3D = Path3D;
  2720. var Curve3 = (function () {
  2721. function Curve3(points) {
  2722. this._points = points;
  2723. }
  2724. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2725. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2726. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2727. var bez = new Array();
  2728. var step = 1 / nbPoints;
  2729. var equation = function (t, val0, val1, val2) {
  2730. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2731. return res;
  2732. };
  2733. for (var i = 0; i <= 1; i += step) {
  2734. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2735. }
  2736. return new Curve3(bez);
  2737. };
  2738. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2739. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2740. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2741. var bez = new Array();
  2742. var step = 1 / nbPoints;
  2743. var equation = function (t, val0, val1, val2, val3) {
  2744. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= 1; i += step) {
  2748. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. Curve3.prototype.getPoints = function () {
  2753. return this._points;
  2754. };
  2755. Curve3.prototype.continue = function (curve) {
  2756. var lastPoint = this._points[this._points.length - 1];
  2757. var continuedPoints = this._points.slice();
  2758. var curvePoints = curve.getPoints();
  2759. for (var i = 1; i < curvePoints.length; i++) {
  2760. continuedPoints.push(curvePoints[i].add(lastPoint));
  2761. }
  2762. return new Curve3(continuedPoints);
  2763. };
  2764. return Curve3;
  2765. })();
  2766. BABYLON.Curve3 = Curve3;
  2767. // Vertex formats
  2768. var PositionNormalVertex = (function () {
  2769. function PositionNormalVertex(position, normal) {
  2770. if (position === void 0) { position = Vector3.Zero(); }
  2771. if (normal === void 0) { normal = Vector3.Up(); }
  2772. this.position = position;
  2773. this.normal = normal;
  2774. }
  2775. PositionNormalVertex.prototype.clone = function () {
  2776. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2777. };
  2778. return PositionNormalVertex;
  2779. })();
  2780. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2781. var PositionNormalTextureVertex = (function () {
  2782. function PositionNormalTextureVertex(position, normal, uv) {
  2783. if (position === void 0) { position = Vector3.Zero(); }
  2784. if (normal === void 0) { normal = Vector3.Up(); }
  2785. if (uv === void 0) { uv = Vector2.Zero(); }
  2786. this.position = position;
  2787. this.normal = normal;
  2788. this.uv = uv;
  2789. }
  2790. PositionNormalTextureVertex.prototype.clone = function () {
  2791. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2792. };
  2793. return PositionNormalTextureVertex;
  2794. })();
  2795. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2796. // SIMD
  2797. if (window.SIMD !== undefined) {
  2798. // Replace functions
  2799. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2800. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2801. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2802. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2803. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2804. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2805. get: function () {
  2806. return this._data[0];
  2807. },
  2808. set: function (value) {
  2809. if (!this._data) {
  2810. this._data = new Float32Array(3);
  2811. }
  2812. this._data[0] = value;
  2813. }
  2814. });
  2815. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2816. get: function () {
  2817. return this._data[1];
  2818. },
  2819. set: function (value) {
  2820. this._data[1] = value;
  2821. }
  2822. });
  2823. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2824. get: function () {
  2825. return this._data[2];
  2826. },
  2827. set: function (value) {
  2828. this._data[2] = value;
  2829. }
  2830. });
  2831. }
  2832. })(BABYLON || (BABYLON = {}));
  2833. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2834. (function (BABYLON) {
  2835. // Screenshots
  2836. var screenshotCanvas;
  2837. var cloneValue = function (source, destinationObject) {
  2838. if (!source)
  2839. return null;
  2840. if (source instanceof BABYLON.Mesh) {
  2841. return null;
  2842. }
  2843. if (source instanceof BABYLON.SubMesh) {
  2844. return source.clone(destinationObject);
  2845. }
  2846. else if (source.clone) {
  2847. return source.clone();
  2848. }
  2849. return null;
  2850. };
  2851. var Tools = (function () {
  2852. function Tools() {
  2853. }
  2854. Tools.GetFilename = function (path) {
  2855. var index = path.lastIndexOf("/");
  2856. if (index < 0)
  2857. return path;
  2858. return path.substring(index + 1);
  2859. };
  2860. Tools.GetDOMTextContent = function (element) {
  2861. var result = "";
  2862. var child = element.firstChild;
  2863. while (child) {
  2864. if (child.nodeType === 3) {
  2865. result += child.textContent;
  2866. }
  2867. child = child.nextSibling;
  2868. }
  2869. return result;
  2870. };
  2871. Tools.ToDegrees = function (angle) {
  2872. return angle * 180 / Math.PI;
  2873. };
  2874. Tools.ToRadians = function (angle) {
  2875. return angle * Math.PI / 180;
  2876. };
  2877. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2878. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2879. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2880. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2881. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2882. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2883. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2884. }
  2885. return {
  2886. minimum: minimum,
  2887. maximum: maximum
  2888. };
  2889. };
  2890. Tools.ExtractMinAndMax = function (positions, start, count) {
  2891. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2892. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2893. for (var index = start; index < start + count; index++) {
  2894. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2895. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2896. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2897. }
  2898. return {
  2899. minimum: minimum,
  2900. maximum: maximum
  2901. };
  2902. };
  2903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2904. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2905. return undefined;
  2906. return Array.isArray(obj) ? obj : [obj];
  2907. };
  2908. // Misc.
  2909. Tools.GetPointerPrefix = function () {
  2910. var eventPrefix = "pointer";
  2911. // Check if hand.js is referenced or if the browser natively supports pointer events
  2912. if (!navigator.pointerEnabled) {
  2913. eventPrefix = "mouse";
  2914. }
  2915. return eventPrefix;
  2916. };
  2917. Tools.QueueNewFrame = function (func) {
  2918. if (window.requestAnimationFrame)
  2919. window.requestAnimationFrame(func);
  2920. else if (window.msRequestAnimationFrame)
  2921. window.msRequestAnimationFrame(func);
  2922. else if (window.webkitRequestAnimationFrame)
  2923. window.webkitRequestAnimationFrame(func);
  2924. else if (window.mozRequestAnimationFrame)
  2925. window.mozRequestAnimationFrame(func);
  2926. else if (window.oRequestAnimationFrame)
  2927. window.oRequestAnimationFrame(func);
  2928. else {
  2929. window.setTimeout(func, 16);
  2930. }
  2931. };
  2932. Tools.RequestFullscreen = function (element) {
  2933. if (element.requestFullscreen)
  2934. element.requestFullscreen();
  2935. else if (element.msRequestFullscreen)
  2936. element.msRequestFullscreen();
  2937. else if (element.webkitRequestFullscreen)
  2938. element.webkitRequestFullscreen();
  2939. else if (element.mozRequestFullScreen)
  2940. element.mozRequestFullScreen();
  2941. };
  2942. Tools.ExitFullscreen = function () {
  2943. if (document.exitFullscreen) {
  2944. document.exitFullscreen();
  2945. }
  2946. else if (document.mozCancelFullScreen) {
  2947. document.mozCancelFullScreen();
  2948. }
  2949. else if (document.webkitCancelFullScreen) {
  2950. document.webkitCancelFullScreen();
  2951. }
  2952. else if (document.msCancelFullScreen) {
  2953. document.msCancelFullScreen();
  2954. }
  2955. };
  2956. // External files
  2957. Tools.CleanUrl = function (url) {
  2958. url = url.replace(/#/mg, "%23");
  2959. return url;
  2960. };
  2961. Tools.LoadImage = function (url, onload, onerror, database) {
  2962. url = Tools.CleanUrl(url);
  2963. var img = new Image();
  2964. if (url.substr(0, 5) !== "data:")
  2965. img.crossOrigin = 'anonymous';
  2966. img.onload = function () {
  2967. onload(img);
  2968. };
  2969. img.onerror = function (err) {
  2970. onerror(img, err);
  2971. };
  2972. var noIndexedDB = function () {
  2973. img.src = url;
  2974. };
  2975. var loadFromIndexedDB = function () {
  2976. database.loadImageFromDB(url, img);
  2977. };
  2978. //ANY database to do!
  2979. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2980. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2981. }
  2982. else {
  2983. if (url.indexOf("file:") === -1) {
  2984. noIndexedDB();
  2985. }
  2986. else {
  2987. try {
  2988. var textureName = url.substring(5);
  2989. var blobURL;
  2990. try {
  2991. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2992. }
  2993. catch (ex) {
  2994. // Chrome doesn't support oneTimeOnly parameter
  2995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2996. }
  2997. img.src = blobURL;
  2998. }
  2999. catch (e) {
  3000. Tools.Log("Error while trying to load texture: " + textureName);
  3001. img.src = null;
  3002. }
  3003. }
  3004. }
  3005. return img;
  3006. };
  3007. //ANY
  3008. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3009. url = Tools.CleanUrl(url);
  3010. var noIndexedDB = function () {
  3011. var request = new XMLHttpRequest();
  3012. var loadUrl = Tools.BaseUrl + url;
  3013. request.open('GET', loadUrl, true);
  3014. if (useArrayBuffer) {
  3015. request.responseType = "arraybuffer";
  3016. }
  3017. request.onprogress = progressCallBack;
  3018. request.onreadystatechange = function () {
  3019. if (request.readyState === 4) {
  3020. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3021. callback(!useArrayBuffer ? request.responseText : request.response);
  3022. }
  3023. else {
  3024. if (onError) {
  3025. onError();
  3026. }
  3027. else {
  3028. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3029. }
  3030. }
  3031. }
  3032. };
  3033. request.send(null);
  3034. };
  3035. var loadFromIndexedDB = function () {
  3036. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3037. };
  3038. if (url.indexOf("file:") !== -1) {
  3039. var fileName = url.substring(5);
  3040. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3041. }
  3042. else {
  3043. // Caching all files
  3044. if (database && database.enableSceneOffline) {
  3045. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3046. }
  3047. else {
  3048. noIndexedDB();
  3049. }
  3050. }
  3051. };
  3052. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3053. var reader = new FileReader();
  3054. reader.onload = function (e) {
  3055. //target doesn't have result from ts 1.3
  3056. callback(e.target['result']);
  3057. };
  3058. reader.onprogress = progressCallback;
  3059. reader.readAsDataURL(fileToLoad);
  3060. };
  3061. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3062. var reader = new FileReader();
  3063. reader.onerror = function (e) {
  3064. Tools.Log("Error while reading file: " + fileToLoad.name);
  3065. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3066. };
  3067. reader.onload = function (e) {
  3068. //target doesn't have result from ts 1.3
  3069. callback(e.target['result']);
  3070. };
  3071. reader.onprogress = progressCallBack;
  3072. if (!useArrayBuffer) {
  3073. // Asynchronous read
  3074. reader.readAsText(fileToLoad);
  3075. }
  3076. else {
  3077. reader.readAsArrayBuffer(fileToLoad);
  3078. }
  3079. };
  3080. // Misc.
  3081. Tools.Clamp = function (value, min, max) {
  3082. if (min === void 0) { min = 0; }
  3083. if (max === void 0) { max = 1; }
  3084. return Math.min(max, Math.max(min, value));
  3085. };
  3086. // Returns -1 when value is a negative number and
  3087. // +1 when value is a positive number.
  3088. Tools.Sign = function (value) {
  3089. value = +value; // convert to a number
  3090. if (value === 0 || isNaN(value))
  3091. return value;
  3092. return value > 0 ? 1 : -1;
  3093. };
  3094. Tools.Format = function (value, decimals) {
  3095. if (decimals === void 0) { decimals = 2; }
  3096. return value.toFixed(decimals);
  3097. };
  3098. Tools.CheckExtends = function (v, min, max) {
  3099. if (v.x < min.x)
  3100. min.x = v.x;
  3101. if (v.y < min.y)
  3102. min.y = v.y;
  3103. if (v.z < min.z)
  3104. min.z = v.z;
  3105. if (v.x > max.x)
  3106. max.x = v.x;
  3107. if (v.y > max.y)
  3108. max.y = v.y;
  3109. if (v.z > max.z)
  3110. max.z = v.z;
  3111. };
  3112. Tools.WithinEpsilon = function (a, b, epsilon) {
  3113. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3114. var num = a - b;
  3115. return -epsilon <= num && num <= epsilon;
  3116. };
  3117. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3118. for (var prop in source) {
  3119. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3120. continue;
  3121. }
  3122. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3123. continue;
  3124. }
  3125. var sourceValue = source[prop];
  3126. var typeOfSourceValue = typeof sourceValue;
  3127. if (typeOfSourceValue === "function") {
  3128. continue;
  3129. }
  3130. if (typeOfSourceValue === "object") {
  3131. if (sourceValue instanceof Array) {
  3132. destination[prop] = [];
  3133. if (sourceValue.length > 0) {
  3134. if (typeof sourceValue[0] == "object") {
  3135. for (var index = 0; index < sourceValue.length; index++) {
  3136. var clonedValue = cloneValue(sourceValue[index], destination);
  3137. if (destination[prop].indexOf(clonedValue) === -1) {
  3138. destination[prop].push(clonedValue);
  3139. }
  3140. }
  3141. }
  3142. else {
  3143. destination[prop] = sourceValue.slice(0);
  3144. }
  3145. }
  3146. }
  3147. else {
  3148. destination[prop] = cloneValue(sourceValue, destination);
  3149. }
  3150. }
  3151. else {
  3152. destination[prop] = sourceValue;
  3153. }
  3154. }
  3155. };
  3156. Tools.IsEmpty = function (obj) {
  3157. for (var i in obj) {
  3158. return false;
  3159. }
  3160. return true;
  3161. };
  3162. Tools.RegisterTopRootEvents = function (events) {
  3163. for (var index = 0; index < events.length; index++) {
  3164. var event = events[index];
  3165. window.addEventListener(event.name, event.handler, false);
  3166. try {
  3167. if (window.parent) {
  3168. window.parent.addEventListener(event.name, event.handler, false);
  3169. }
  3170. }
  3171. catch (e) {
  3172. }
  3173. }
  3174. };
  3175. Tools.UnregisterTopRootEvents = function (events) {
  3176. for (var index = 0; index < events.length; index++) {
  3177. var event = events[index];
  3178. window.removeEventListener(event.name, event.handler);
  3179. try {
  3180. if (window.parent) {
  3181. window.parent.removeEventListener(event.name, event.handler);
  3182. }
  3183. }
  3184. catch (e) {
  3185. }
  3186. }
  3187. };
  3188. Tools.DumpFramebuffer = function (width, height, engine) {
  3189. // Read the contents of the framebuffer
  3190. var numberOfChannelsByLine = width * 4;
  3191. var halfHeight = height / 2;
  3192. //Reading datas from WebGL
  3193. var data = engine.readPixels(0, 0, width, height);
  3194. for (var i = 0; i < halfHeight; i++) {
  3195. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3196. var currentCell = j + i * numberOfChannelsByLine;
  3197. var targetLine = height - i - 1;
  3198. var targetCell = j + targetLine * numberOfChannelsByLine;
  3199. var temp = data[currentCell];
  3200. data[currentCell] = data[targetCell];
  3201. data[targetCell] = temp;
  3202. }
  3203. }
  3204. // Create a 2D canvas to store the result
  3205. if (!screenshotCanvas) {
  3206. screenshotCanvas = document.createElement('canvas');
  3207. }
  3208. screenshotCanvas.width = width;
  3209. screenshotCanvas.height = height;
  3210. var context = screenshotCanvas.getContext('2d');
  3211. // Copy the pixels to a 2D canvas
  3212. var imageData = context.createImageData(width, height);
  3213. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3214. var castData = imageData.data;
  3215. castData.set(data);
  3216. context.putImageData(imageData, 0, 0);
  3217. var base64Image = screenshotCanvas.toDataURL();
  3218. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3219. if (("download" in document.createElement("a"))) {
  3220. var a = window.document.createElement("a");
  3221. a.href = base64Image;
  3222. var date = new Date();
  3223. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3224. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3225. window.document.body.appendChild(a);
  3226. a.addEventListener("click", function () {
  3227. a.parentElement.removeChild(a);
  3228. });
  3229. a.click();
  3230. }
  3231. else {
  3232. var newWindow = window.open("");
  3233. var img = newWindow.document.createElement("img");
  3234. img.src = base64Image;
  3235. newWindow.document.body.appendChild(img);
  3236. }
  3237. };
  3238. Tools.CreateScreenshot = function (engine, camera, size) {
  3239. var width;
  3240. var height;
  3241. var scene = camera.getScene();
  3242. var previousCamera = null;
  3243. if (scene.activeCamera !== camera) {
  3244. previousCamera = scene.activeCamera;
  3245. scene.activeCamera = camera;
  3246. }
  3247. //If a precision value is specified
  3248. if (size.precision) {
  3249. width = Math.round(engine.getRenderWidth() * size.precision);
  3250. height = Math.round(width / engine.getAspectRatio(camera));
  3251. size = { width: width, height: height };
  3252. }
  3253. else if (size.width && size.height) {
  3254. width = size.width;
  3255. height = size.height;
  3256. }
  3257. else if (size.width && !size.height) {
  3258. width = size.width;
  3259. height = Math.round(width / engine.getAspectRatio(camera));
  3260. size = { width: width, height: height };
  3261. }
  3262. else if (size.height && !size.width) {
  3263. height = size.height;
  3264. width = Math.round(height * engine.getAspectRatio(camera));
  3265. size = { width: width, height: height };
  3266. }
  3267. else if (!isNaN(size)) {
  3268. height = size;
  3269. width = size;
  3270. }
  3271. else {
  3272. Tools.Error("Invalid 'size' parameter !");
  3273. return;
  3274. }
  3275. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3276. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3277. texture.renderList = scene.meshes;
  3278. texture.onAfterRender = function () {
  3279. Tools.DumpFramebuffer(width, height, engine);
  3280. };
  3281. scene.incrementRenderId();
  3282. texture.render(true);
  3283. texture.dispose();
  3284. if (previousCamera) {
  3285. scene.activeCamera = previousCamera;
  3286. }
  3287. };
  3288. // XHR response validator for local file scenario
  3289. Tools.ValidateXHRData = function (xhr, dataType) {
  3290. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3291. if (dataType === void 0) { dataType = 7; }
  3292. try {
  3293. if (dataType & 1) {
  3294. if (xhr.responseText && xhr.responseText.length > 0) {
  3295. return true;
  3296. }
  3297. else if (dataType === 1) {
  3298. return false;
  3299. }
  3300. }
  3301. if (dataType & 2) {
  3302. // Check header width and height since there is no "TGA" magic number
  3303. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3304. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3305. return true;
  3306. }
  3307. else if (dataType === 2) {
  3308. return false;
  3309. }
  3310. }
  3311. if (dataType & 4) {
  3312. // Check for the "DDS" magic number
  3313. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3314. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3315. return true;
  3316. }
  3317. else {
  3318. return false;
  3319. }
  3320. }
  3321. }
  3322. catch (e) {
  3323. }
  3324. return false;
  3325. };
  3326. Object.defineProperty(Tools, "NoneLogLevel", {
  3327. get: function () {
  3328. return Tools._NoneLogLevel;
  3329. },
  3330. enumerable: true,
  3331. configurable: true
  3332. });
  3333. Object.defineProperty(Tools, "MessageLogLevel", {
  3334. get: function () {
  3335. return Tools._MessageLogLevel;
  3336. },
  3337. enumerable: true,
  3338. configurable: true
  3339. });
  3340. Object.defineProperty(Tools, "WarningLogLevel", {
  3341. get: function () {
  3342. return Tools._WarningLogLevel;
  3343. },
  3344. enumerable: true,
  3345. configurable: true
  3346. });
  3347. Object.defineProperty(Tools, "ErrorLogLevel", {
  3348. get: function () {
  3349. return Tools._ErrorLogLevel;
  3350. },
  3351. enumerable: true,
  3352. configurable: true
  3353. });
  3354. Object.defineProperty(Tools, "AllLogLevel", {
  3355. get: function () {
  3356. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3357. },
  3358. enumerable: true,
  3359. configurable: true
  3360. });
  3361. Tools._AddLogEntry = function (entry) {
  3362. Tools._LogCache = entry + Tools._LogCache;
  3363. if (Tools.OnNewCacheEntry) {
  3364. Tools.OnNewCacheEntry(entry);
  3365. }
  3366. };
  3367. Tools._FormatMessage = function (message) {
  3368. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3369. var date = new Date();
  3370. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3371. };
  3372. Tools._LogDisabled = function (message) {
  3373. // nothing to do
  3374. };
  3375. Tools._LogEnabled = function (message) {
  3376. var formattedMessage = Tools._FormatMessage(message);
  3377. console.log("BJS - " + formattedMessage);
  3378. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3379. Tools._AddLogEntry(entry);
  3380. };
  3381. Tools._WarnDisabled = function (message) {
  3382. // nothing to do
  3383. };
  3384. Tools._WarnEnabled = function (message) {
  3385. var formattedMessage = Tools._FormatMessage(message);
  3386. console.warn("BJS - " + formattedMessage);
  3387. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3388. Tools._AddLogEntry(entry);
  3389. };
  3390. Tools._ErrorDisabled = function (message) {
  3391. // nothing to do
  3392. };
  3393. Tools._ErrorEnabled = function (message) {
  3394. var formattedMessage = Tools._FormatMessage(message);
  3395. console.error("BJS - " + formattedMessage);
  3396. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3397. Tools._AddLogEntry(entry);
  3398. };
  3399. Object.defineProperty(Tools, "LogCache", {
  3400. get: function () {
  3401. return Tools._LogCache;
  3402. },
  3403. enumerable: true,
  3404. configurable: true
  3405. });
  3406. Object.defineProperty(Tools, "LogLevels", {
  3407. set: function (level) {
  3408. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3409. Tools.Log = Tools._LogEnabled;
  3410. }
  3411. else {
  3412. Tools.Log = Tools._LogDisabled;
  3413. }
  3414. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3415. Tools.Warn = Tools._WarnEnabled;
  3416. }
  3417. else {
  3418. Tools.Warn = Tools._WarnDisabled;
  3419. }
  3420. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3421. Tools.Error = Tools._ErrorEnabled;
  3422. }
  3423. else {
  3424. Tools.Error = Tools._ErrorDisabled;
  3425. }
  3426. },
  3427. enumerable: true,
  3428. configurable: true
  3429. });
  3430. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3431. get: function () {
  3432. return Tools._PerformanceNoneLogLevel;
  3433. },
  3434. enumerable: true,
  3435. configurable: true
  3436. });
  3437. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3438. get: function () {
  3439. return Tools._PerformanceUserMarkLogLevel;
  3440. },
  3441. enumerable: true,
  3442. configurable: true
  3443. });
  3444. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3445. get: function () {
  3446. return Tools._PerformanceConsoleLogLevel;
  3447. },
  3448. enumerable: true,
  3449. configurable: true
  3450. });
  3451. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3452. set: function (level) {
  3453. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3454. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3455. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3456. return;
  3457. }
  3458. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3459. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3460. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3461. return;
  3462. }
  3463. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3464. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3465. },
  3466. enumerable: true,
  3467. configurable: true
  3468. });
  3469. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3470. };
  3471. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3472. };
  3473. Tools._StartUserMark = function (counterName, condition) {
  3474. if (condition === void 0) { condition = true; }
  3475. if (!condition || !Tools._performance.mark) {
  3476. return;
  3477. }
  3478. Tools._performance.mark(counterName + "-Begin");
  3479. };
  3480. Tools._EndUserMark = function (counterName, condition) {
  3481. if (condition === void 0) { condition = true; }
  3482. if (!condition || !Tools._performance.mark) {
  3483. return;
  3484. }
  3485. Tools._performance.mark(counterName + "-End");
  3486. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3487. };
  3488. Tools._StartPerformanceConsole = function (counterName, condition) {
  3489. if (condition === void 0) { condition = true; }
  3490. if (!condition) {
  3491. return;
  3492. }
  3493. Tools._StartUserMark(counterName, condition);
  3494. if (console.time) {
  3495. console.time(counterName);
  3496. }
  3497. };
  3498. Tools._EndPerformanceConsole = function (counterName, condition) {
  3499. if (condition === void 0) { condition = true; }
  3500. if (!condition) {
  3501. return;
  3502. }
  3503. Tools._EndUserMark(counterName, condition);
  3504. if (console.time) {
  3505. console.timeEnd(counterName);
  3506. }
  3507. };
  3508. Object.defineProperty(Tools, "Now", {
  3509. get: function () {
  3510. if (window.performance && window.performance.now) {
  3511. return window.performance.now();
  3512. }
  3513. return new Date().getTime();
  3514. },
  3515. enumerable: true,
  3516. configurable: true
  3517. });
  3518. // Deprecated
  3519. Tools.GetFps = function () {
  3520. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3521. return 0;
  3522. };
  3523. Tools.BaseUrl = "";
  3524. Tools.GetExponantOfTwo = function (value, max) {
  3525. var count = 1;
  3526. do {
  3527. count *= 2;
  3528. } while (count < value);
  3529. if (count > max)
  3530. count = max;
  3531. return count;
  3532. };
  3533. // Logs
  3534. Tools._NoneLogLevel = 0;
  3535. Tools._MessageLogLevel = 1;
  3536. Tools._WarningLogLevel = 2;
  3537. Tools._ErrorLogLevel = 4;
  3538. Tools._LogCache = "";
  3539. Tools.Log = Tools._LogEnabled;
  3540. Tools.Warn = Tools._WarnEnabled;
  3541. Tools.Error = Tools._ErrorEnabled;
  3542. // Performances
  3543. Tools._PerformanceNoneLogLevel = 0;
  3544. Tools._PerformanceUserMarkLogLevel = 1;
  3545. Tools._PerformanceConsoleLogLevel = 2;
  3546. Tools._performance = window.performance;
  3547. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3548. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3549. return Tools;
  3550. })();
  3551. BABYLON.Tools = Tools;
  3552. /**
  3553. * An implementation of a loop for asynchronous functions.
  3554. */
  3555. var AsyncLoop = (function () {
  3556. /**
  3557. * Constroctor.
  3558. * @param iterations the number of iterations.
  3559. * @param _fn the function to run each iteration
  3560. * @param _successCallback the callback that will be called upon succesful execution
  3561. * @param offset starting offset.
  3562. */
  3563. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3564. if (offset === void 0) { offset = 0; }
  3565. this.iterations = iterations;
  3566. this._fn = _fn;
  3567. this._successCallback = _successCallback;
  3568. this.index = offset - 1;
  3569. this._done = false;
  3570. }
  3571. /**
  3572. * Execute the next iteration. Must be called after the last iteration was finished.
  3573. */
  3574. AsyncLoop.prototype.executeNext = function () {
  3575. if (!this._done) {
  3576. if (this.index + 1 < this.iterations) {
  3577. ++this.index;
  3578. this._fn(this);
  3579. }
  3580. else {
  3581. this.breakLoop();
  3582. }
  3583. }
  3584. };
  3585. /**
  3586. * Break the loop and run the success callback.
  3587. */
  3588. AsyncLoop.prototype.breakLoop = function () {
  3589. this._done = true;
  3590. this._successCallback();
  3591. };
  3592. /**
  3593. * Helper function
  3594. */
  3595. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3596. if (offset === void 0) { offset = 0; }
  3597. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3598. loop.executeNext();
  3599. return loop;
  3600. };
  3601. /**
  3602. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3603. * @param iterations total number of iterations
  3604. * @param syncedIterations number of synchronous iterations in each async iteration.
  3605. * @param fn the function to call each iteration.
  3606. * @param callback a success call back that will be called when iterating stops.
  3607. * @param breakFunction a break condition (optional)
  3608. * @param timeout timeout settings for the setTimeout function. default - 0.
  3609. * @constructor
  3610. */
  3611. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3612. if (timeout === void 0) { timeout = 0; }
  3613. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3614. if (breakFunction && breakFunction())
  3615. loop.breakLoop();
  3616. else {
  3617. setTimeout(function () {
  3618. for (var i = 0; i < syncedIterations; ++i) {
  3619. var iteration = (loop.index * syncedIterations) + i;
  3620. if (iteration >= iterations)
  3621. break;
  3622. fn(iteration);
  3623. if (breakFunction && breakFunction()) {
  3624. loop.breakLoop();
  3625. break;
  3626. }
  3627. }
  3628. loop.executeNext();
  3629. }, timeout);
  3630. }
  3631. }, callback);
  3632. };
  3633. return AsyncLoop;
  3634. })();
  3635. BABYLON.AsyncLoop = AsyncLoop;
  3636. })(BABYLON || (BABYLON = {}));
  3637. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3638. (function (BABYLON) {
  3639. var _DepthCullingState = (function () {
  3640. function _DepthCullingState() {
  3641. this._isDepthTestDirty = false;
  3642. this._isDepthMaskDirty = false;
  3643. this._isDepthFuncDirty = false;
  3644. this._isCullFaceDirty = false;
  3645. this._isCullDirty = false;
  3646. this._isZOffsetDirty = false;
  3647. }
  3648. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3649. get: function () {
  3650. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3651. },
  3652. enumerable: true,
  3653. configurable: true
  3654. });
  3655. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3656. get: function () {
  3657. return this._zOffset;
  3658. },
  3659. set: function (value) {
  3660. if (this._zOffset === value) {
  3661. return;
  3662. }
  3663. this._zOffset = value;
  3664. this._isZOffsetDirty = true;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3670. get: function () {
  3671. return this._cullFace;
  3672. },
  3673. set: function (value) {
  3674. if (this._cullFace === value) {
  3675. return;
  3676. }
  3677. this._cullFace = value;
  3678. this._isCullFaceDirty = true;
  3679. },
  3680. enumerable: true,
  3681. configurable: true
  3682. });
  3683. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3684. get: function () {
  3685. return this._cull;
  3686. },
  3687. set: function (value) {
  3688. if (this._cull === value) {
  3689. return;
  3690. }
  3691. this._cull = value;
  3692. this._isCullDirty = true;
  3693. },
  3694. enumerable: true,
  3695. configurable: true
  3696. });
  3697. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3698. get: function () {
  3699. return this._depthFunc;
  3700. },
  3701. set: function (value) {
  3702. if (this._depthFunc === value) {
  3703. return;
  3704. }
  3705. this._depthFunc = value;
  3706. this._isDepthFuncDirty = true;
  3707. },
  3708. enumerable: true,
  3709. configurable: true
  3710. });
  3711. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3712. get: function () {
  3713. return this._depthMask;
  3714. },
  3715. set: function (value) {
  3716. if (this._depthMask === value) {
  3717. return;
  3718. }
  3719. this._depthMask = value;
  3720. this._isDepthMaskDirty = true;
  3721. },
  3722. enumerable: true,
  3723. configurable: true
  3724. });
  3725. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3726. get: function () {
  3727. return this._depthTest;
  3728. },
  3729. set: function (value) {
  3730. if (this._depthTest === value) {
  3731. return;
  3732. }
  3733. this._depthTest = value;
  3734. this._isDepthTestDirty = true;
  3735. },
  3736. enumerable: true,
  3737. configurable: true
  3738. });
  3739. _DepthCullingState.prototype.reset = function () {
  3740. this._depthMask = true;
  3741. this._depthTest = true;
  3742. this._depthFunc = null;
  3743. this._cull = null;
  3744. this._cullFace = null;
  3745. this._zOffset = 0;
  3746. this._isDepthTestDirty = true;
  3747. this._isDepthMaskDirty = true;
  3748. this._isDepthFuncDirty = false;
  3749. this._isCullFaceDirty = false;
  3750. this._isCullDirty = false;
  3751. this._isZOffsetDirty = false;
  3752. };
  3753. _DepthCullingState.prototype.apply = function (gl) {
  3754. if (!this.isDirty) {
  3755. return;
  3756. }
  3757. // Cull
  3758. if (this._isCullDirty) {
  3759. if (this.cull) {
  3760. gl.enable(gl.CULL_FACE);
  3761. }
  3762. else {
  3763. gl.disable(gl.CULL_FACE);
  3764. }
  3765. this._isCullDirty = false;
  3766. }
  3767. // Cull face
  3768. if (this._isCullFaceDirty) {
  3769. gl.cullFace(this.cullFace);
  3770. this._isCullFaceDirty = false;
  3771. }
  3772. // Depth mask
  3773. if (this._isDepthMaskDirty) {
  3774. gl.depthMask(this.depthMask);
  3775. this._isDepthMaskDirty = false;
  3776. }
  3777. // Depth test
  3778. if (this._isDepthTestDirty) {
  3779. if (this.depthTest) {
  3780. gl.enable(gl.DEPTH_TEST);
  3781. }
  3782. else {
  3783. gl.disable(gl.DEPTH_TEST);
  3784. }
  3785. this._isDepthTestDirty = false;
  3786. }
  3787. // Depth func
  3788. if (this._isDepthFuncDirty) {
  3789. gl.depthFunc(this.depthFunc);
  3790. this._isDepthFuncDirty = false;
  3791. }
  3792. // zOffset
  3793. if (this._isZOffsetDirty) {
  3794. if (this.zOffset) {
  3795. gl.enable(gl.POLYGON_OFFSET_FILL);
  3796. gl.polygonOffset(this.zOffset, 0);
  3797. }
  3798. else {
  3799. gl.disable(gl.POLYGON_OFFSET_FILL);
  3800. }
  3801. this._isZOffsetDirty = false;
  3802. }
  3803. };
  3804. return _DepthCullingState;
  3805. })();
  3806. BABYLON._DepthCullingState = _DepthCullingState;
  3807. var _AlphaState = (function () {
  3808. function _AlphaState() {
  3809. this._isAlphaBlendDirty = false;
  3810. this._isBlendFunctionParametersDirty = false;
  3811. this._alphaBlend = false;
  3812. this._blendFunctionParameters = new Array(4);
  3813. }
  3814. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3815. get: function () {
  3816. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3822. get: function () {
  3823. return this._alphaBlend;
  3824. },
  3825. set: function (value) {
  3826. if (this._alphaBlend === value) {
  3827. return;
  3828. }
  3829. this._alphaBlend = value;
  3830. this._isAlphaBlendDirty = true;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3836. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3837. return;
  3838. }
  3839. this._blendFunctionParameters[0] = value0;
  3840. this._blendFunctionParameters[1] = value1;
  3841. this._blendFunctionParameters[2] = value2;
  3842. this._blendFunctionParameters[3] = value3;
  3843. this._isBlendFunctionParametersDirty = true;
  3844. };
  3845. _AlphaState.prototype.reset = function () {
  3846. this._alphaBlend = false;
  3847. this._blendFunctionParameters[0] = null;
  3848. this._blendFunctionParameters[1] = null;
  3849. this._blendFunctionParameters[2] = null;
  3850. this._blendFunctionParameters[3] = null;
  3851. this._isAlphaBlendDirty = true;
  3852. this._isBlendFunctionParametersDirty = false;
  3853. };
  3854. _AlphaState.prototype.apply = function (gl) {
  3855. if (!this.isDirty) {
  3856. return;
  3857. }
  3858. // Alpha blend
  3859. if (this._isAlphaBlendDirty) {
  3860. if (this._alphaBlend) {
  3861. gl.enable(gl.BLEND);
  3862. }
  3863. else {
  3864. gl.disable(gl.BLEND);
  3865. }
  3866. this._isAlphaBlendDirty = false;
  3867. }
  3868. // Alpha function
  3869. if (this._isBlendFunctionParametersDirty) {
  3870. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3871. this._isBlendFunctionParametersDirty = false;
  3872. }
  3873. };
  3874. return _AlphaState;
  3875. })();
  3876. BABYLON._AlphaState = _AlphaState;
  3877. var compileShader = function (gl, source, type, defines) {
  3878. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3879. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3880. gl.compileShader(shader);
  3881. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3882. throw new Error(gl.getShaderInfoLog(shader));
  3883. }
  3884. return shader;
  3885. };
  3886. var getWebGLTextureType = function (gl, type) {
  3887. var textureType = gl.UNSIGNED_BYTE;
  3888. if (type === Engine.TEXTURETYPE_FLOAT)
  3889. textureType = gl.FLOAT;
  3890. return textureType;
  3891. };
  3892. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3893. var magFilter = gl.NEAREST;
  3894. var minFilter = gl.NEAREST;
  3895. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3896. magFilter = gl.LINEAR;
  3897. if (generateMipMaps) {
  3898. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3899. }
  3900. else {
  3901. minFilter = gl.LINEAR;
  3902. }
  3903. }
  3904. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3905. magFilter = gl.LINEAR;
  3906. if (generateMipMaps) {
  3907. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3908. }
  3909. else {
  3910. minFilter = gl.LINEAR;
  3911. }
  3912. }
  3913. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3914. magFilter = gl.NEAREST;
  3915. if (generateMipMaps) {
  3916. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3917. }
  3918. else {
  3919. minFilter = gl.NEAREST;
  3920. }
  3921. }
  3922. return {
  3923. min: minFilter,
  3924. mag: magFilter
  3925. };
  3926. };
  3927. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3929. var engine = scene.getEngine();
  3930. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3931. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3932. gl.bindTexture(gl.TEXTURE_2D, texture);
  3933. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3934. processFunction(potWidth, potHeight);
  3935. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3938. if (!noMipmap && !isCompressed) {
  3939. gl.generateMipmap(gl.TEXTURE_2D);
  3940. }
  3941. gl.bindTexture(gl.TEXTURE_2D, null);
  3942. engine._activeTexturesCache = [];
  3943. texture._baseWidth = width;
  3944. texture._baseHeight = height;
  3945. texture._width = potWidth;
  3946. texture._height = potHeight;
  3947. texture.isReady = true;
  3948. texture.samplingMode = samplingMode;
  3949. scene._removePendingData(texture);
  3950. };
  3951. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3952. var onload = function () {
  3953. loadedImages[index] = img;
  3954. loadedImages._internalCount++;
  3955. scene._removePendingData(img);
  3956. if (loadedImages._internalCount === 6) {
  3957. onfinish(loadedImages);
  3958. }
  3959. };
  3960. var onerror = function () {
  3961. scene._removePendingData(img);
  3962. };
  3963. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3964. scene._addPendingData(img);
  3965. };
  3966. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3967. var loadedImages = [];
  3968. loadedImages._internalCount = 0;
  3969. for (var index = 0; index < 6; index++) {
  3970. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3971. }
  3972. };
  3973. var EngineCapabilities = (function () {
  3974. function EngineCapabilities() {
  3975. }
  3976. return EngineCapabilities;
  3977. })();
  3978. BABYLON.EngineCapabilities = EngineCapabilities;
  3979. /**
  3980. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3981. */
  3982. var Engine = (function () {
  3983. /**
  3984. * @constructor
  3985. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3986. * @param {boolean} [antialias] - enable antialias
  3987. * @param options - further options to be sent to the getContext function
  3988. */
  3989. function Engine(canvas, antialias, options) {
  3990. var _this = this;
  3991. // Public members
  3992. this.isFullscreen = false;
  3993. this.isPointerLock = false;
  3994. this.cullBackFaces = true;
  3995. this.renderEvenInBackground = true;
  3996. this.scenes = new Array();
  3997. this._windowIsBackground = false;
  3998. this._loadingDivBackgroundColor = "black";
  3999. this._drawCalls = 0;
  4000. this._renderingQueueLaunched = false;
  4001. this._activeRenderLoops = [];
  4002. // FPS
  4003. this.fpsRange = 60;
  4004. this.previousFramesDuration = [];
  4005. this.fps = 60;
  4006. this.deltaTime = 0;
  4007. // States
  4008. this._depthCullingState = new _DepthCullingState();
  4009. this._alphaState = new _AlphaState();
  4010. this._alphaMode = Engine.ALPHA_DISABLE;
  4011. // Cache
  4012. this._loadedTexturesCache = new Array();
  4013. this._activeTexturesCache = new Array();
  4014. this._compiledEffects = {};
  4015. this._uintIndicesCurrentlySet = false;
  4016. this._renderingCanvas = canvas;
  4017. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4018. options = options || {};
  4019. options.antialias = antialias;
  4020. try {
  4021. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4022. }
  4023. catch (e) {
  4024. throw new Error("WebGL not supported");
  4025. }
  4026. if (!this._gl) {
  4027. throw new Error("WebGL not supported");
  4028. }
  4029. this._onBlur = function () {
  4030. _this._windowIsBackground = true;
  4031. };
  4032. this._onFocus = function () {
  4033. _this._windowIsBackground = false;
  4034. };
  4035. window.addEventListener("blur", this._onBlur);
  4036. window.addEventListener("focus", this._onFocus);
  4037. // Viewport
  4038. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4039. this.resize();
  4040. // Caps
  4041. this._caps = new EngineCapabilities();
  4042. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4043. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4044. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4045. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4046. // Infos
  4047. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4048. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4049. if (rendererInfo != null) {
  4050. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4051. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4052. }
  4053. if (!this._glVendor) {
  4054. this._glVendor = "Unknown vendor";
  4055. }
  4056. if (!this._glRenderer) {
  4057. this._glRenderer = "Unknown renderer";
  4058. }
  4059. // Extensions
  4060. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4061. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4062. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4063. 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');
  4064. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4065. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4066. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4067. // Depth buffer
  4068. this.setDepthBuffer(true);
  4069. this.setDepthFunctionToLessOrEqual();
  4070. this.setDepthWrite(true);
  4071. // Fullscreen
  4072. this._onFullscreenChange = function () {
  4073. if (document.fullscreen !== undefined) {
  4074. _this.isFullscreen = document.fullscreen;
  4075. }
  4076. else if (document.mozFullScreen !== undefined) {
  4077. _this.isFullscreen = document.mozFullScreen;
  4078. }
  4079. else if (document.webkitIsFullScreen !== undefined) {
  4080. _this.isFullscreen = document.webkitIsFullScreen;
  4081. }
  4082. else if (document.msIsFullScreen !== undefined) {
  4083. _this.isFullscreen = document.msIsFullScreen;
  4084. }
  4085. // Pointer lock
  4086. if (_this.isFullscreen && _this._pointerLockRequested) {
  4087. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4088. if (canvas.requestPointerLock) {
  4089. canvas.requestPointerLock();
  4090. }
  4091. }
  4092. };
  4093. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4094. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4095. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4096. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4097. // Pointer lock
  4098. this._onPointerLockChange = function () {
  4099. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4100. };
  4101. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4102. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4103. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4104. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4105. if (!Engine.audioEngine) {
  4106. Engine.audioEngine = new BABYLON.AudioEngine();
  4107. }
  4108. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4109. }
  4110. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4111. get: function () {
  4112. return Engine._ALPHA_DISABLE;
  4113. },
  4114. enumerable: true,
  4115. configurable: true
  4116. });
  4117. Object.defineProperty(Engine, "ALPHA_ADD", {
  4118. get: function () {
  4119. return Engine._ALPHA_ADD;
  4120. },
  4121. enumerable: true,
  4122. configurable: true
  4123. });
  4124. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4125. get: function () {
  4126. return Engine._ALPHA_COMBINE;
  4127. },
  4128. enumerable: true,
  4129. configurable: true
  4130. });
  4131. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4132. get: function () {
  4133. return Engine._DELAYLOADSTATE_NONE;
  4134. },
  4135. enumerable: true,
  4136. configurable: true
  4137. });
  4138. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4139. get: function () {
  4140. return Engine._DELAYLOADSTATE_LOADED;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4146. get: function () {
  4147. return Engine._DELAYLOADSTATE_LOADING;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4153. get: function () {
  4154. return Engine._DELAYLOADSTATE_NOTLOADED;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4160. get: function () {
  4161. return Engine._TEXTUREFORMAT_ALPHA;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4167. get: function () {
  4168. return Engine._TEXTUREFORMAT_LUMINANCE;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4174. get: function () {
  4175. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4181. get: function () {
  4182. return Engine._TEXTUREFORMAT_RGB;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_RGBA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4195. get: function () {
  4196. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4202. get: function () {
  4203. return Engine._TEXTURETYPE_FLOAT;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "Version", {
  4209. get: function () {
  4210. return "2.1.0 alpha";
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Engine.prototype._prepareWorkingCanvas = function () {
  4216. if (this._workingCanvas) {
  4217. return;
  4218. }
  4219. this._workingCanvas = document.createElement("canvas");
  4220. this._workingContext = this._workingCanvas.getContext("2d");
  4221. };
  4222. Engine.prototype.getGlInfo = function () {
  4223. return {
  4224. vendor: this._glVendor,
  4225. renderer: this._glRenderer,
  4226. version: this._glVersion
  4227. };
  4228. };
  4229. Engine.prototype.getAspectRatio = function (camera) {
  4230. var viewport = camera.viewport;
  4231. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4232. };
  4233. Engine.prototype.getRenderWidth = function () {
  4234. if (this._currentRenderTarget) {
  4235. return this._currentRenderTarget._width;
  4236. }
  4237. return this._renderingCanvas.width;
  4238. };
  4239. Engine.prototype.getRenderHeight = function () {
  4240. if (this._currentRenderTarget) {
  4241. return this._currentRenderTarget._height;
  4242. }
  4243. return this._renderingCanvas.height;
  4244. };
  4245. Engine.prototype.getRenderingCanvas = function () {
  4246. return this._renderingCanvas;
  4247. };
  4248. Engine.prototype.getRenderingCanvasClientRect = function () {
  4249. return this._renderingCanvas.getBoundingClientRect();
  4250. };
  4251. Engine.prototype.setHardwareScalingLevel = function (level) {
  4252. this._hardwareScalingLevel = level;
  4253. this.resize();
  4254. };
  4255. Engine.prototype.getHardwareScalingLevel = function () {
  4256. return this._hardwareScalingLevel;
  4257. };
  4258. Engine.prototype.getLoadedTexturesCache = function () {
  4259. return this._loadedTexturesCache;
  4260. };
  4261. Engine.prototype.getCaps = function () {
  4262. return this._caps;
  4263. };
  4264. Object.defineProperty(Engine.prototype, "drawCalls", {
  4265. get: function () {
  4266. return this._drawCalls;
  4267. },
  4268. enumerable: true,
  4269. configurable: true
  4270. });
  4271. // Methods
  4272. Engine.prototype.resetDrawCalls = function () {
  4273. this._drawCalls = 0;
  4274. };
  4275. Engine.prototype.setDepthFunctionToGreater = function () {
  4276. this._depthCullingState.depthFunc = this._gl.GREATER;
  4277. };
  4278. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4279. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4280. };
  4281. Engine.prototype.setDepthFunctionToLess = function () {
  4282. this._depthCullingState.depthFunc = this._gl.LESS;
  4283. };
  4284. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4285. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4286. };
  4287. /**
  4288. * stop executing a render loop function and remove it from the execution array
  4289. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4290. */
  4291. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4292. if (!renderFunction) {
  4293. this._activeRenderLoops = [];
  4294. return;
  4295. }
  4296. var index = this._activeRenderLoops.indexOf(renderFunction);
  4297. if (index >= 0) {
  4298. this._activeRenderLoops.splice(index, 1);
  4299. }
  4300. };
  4301. Engine.prototype._renderLoop = function () {
  4302. var _this = this;
  4303. var shouldRender = true;
  4304. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4305. shouldRender = false;
  4306. }
  4307. if (shouldRender) {
  4308. // Start new frame
  4309. this.beginFrame();
  4310. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4311. var renderFunction = this._activeRenderLoops[index];
  4312. renderFunction();
  4313. }
  4314. // Present
  4315. this.endFrame();
  4316. }
  4317. if (this._activeRenderLoops.length > 0) {
  4318. // Register new frame
  4319. BABYLON.Tools.QueueNewFrame(function () {
  4320. _this._renderLoop();
  4321. });
  4322. }
  4323. else {
  4324. this._renderingQueueLaunched = false;
  4325. }
  4326. };
  4327. /**
  4328. * Register and execute a render loop. The engine can have more than one render function.
  4329. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4330. * @example
  4331. * engine.runRenderLoop(function () {
  4332. * scene.render()
  4333. * })
  4334. */
  4335. Engine.prototype.runRenderLoop = function (renderFunction) {
  4336. var _this = this;
  4337. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4338. return;
  4339. }
  4340. this._activeRenderLoops.push(renderFunction);
  4341. if (!this._renderingQueueLaunched) {
  4342. this._renderingQueueLaunched = true;
  4343. BABYLON.Tools.QueueNewFrame(function () {
  4344. _this._renderLoop();
  4345. });
  4346. }
  4347. };
  4348. /**
  4349. * Toggle full screen mode.
  4350. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4351. */
  4352. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4353. if (this.isFullscreen) {
  4354. BABYLON.Tools.ExitFullscreen();
  4355. }
  4356. else {
  4357. this._pointerLockRequested = requestPointerLock;
  4358. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4359. }
  4360. };
  4361. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4362. this.applyStates();
  4363. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4364. if (this._depthCullingState.depthMask) {
  4365. this._gl.clearDepth(1.0);
  4366. }
  4367. var mode = 0;
  4368. if (backBuffer)
  4369. mode |= this._gl.COLOR_BUFFER_BIT;
  4370. if (depthStencil && this._depthCullingState.depthMask)
  4371. mode |= this._gl.DEPTH_BUFFER_BIT;
  4372. this._gl.clear(mode);
  4373. };
  4374. /**
  4375. * Set the WebGL's viewport
  4376. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4377. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4378. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4379. */
  4380. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4381. var width = requiredWidth || this._renderingCanvas.width;
  4382. var height = requiredHeight || this._renderingCanvas.height;
  4383. var x = viewport.x || 0;
  4384. var y = viewport.y || 0;
  4385. this._cachedViewport = viewport;
  4386. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4387. };
  4388. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4389. this._cachedViewport = null;
  4390. this._gl.viewport(x, y, width, height);
  4391. };
  4392. Engine.prototype.beginFrame = function () {
  4393. this._measureFps();
  4394. };
  4395. Engine.prototype.endFrame = function () {
  4396. //this.flushFramebuffer();
  4397. };
  4398. /**
  4399. * resize the view according to the canvas' size.
  4400. * @example
  4401. * window.addEventListener("resize", function () {
  4402. * engine.resize();
  4403. * });
  4404. */
  4405. Engine.prototype.resize = function () {
  4406. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4407. };
  4408. /**
  4409. * force a specific size of the canvas
  4410. * @param {number} width - the new canvas' width
  4411. * @param {number} height - the new canvas' height
  4412. */
  4413. Engine.prototype.setSize = function (width, height) {
  4414. this._renderingCanvas.width = width;
  4415. this._renderingCanvas.height = height;
  4416. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4417. };
  4418. Engine.prototype.bindFramebuffer = function (texture) {
  4419. this._currentRenderTarget = texture;
  4420. var gl = this._gl;
  4421. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4422. this._gl.viewport(0, 0, texture._width, texture._height);
  4423. this.wipeCaches();
  4424. };
  4425. Engine.prototype.unBindFramebuffer = function (texture) {
  4426. this._currentRenderTarget = null;
  4427. if (texture.generateMipMaps) {
  4428. var gl = this._gl;
  4429. gl.bindTexture(gl.TEXTURE_2D, texture);
  4430. gl.generateMipmap(gl.TEXTURE_2D);
  4431. gl.bindTexture(gl.TEXTURE_2D, null);
  4432. }
  4433. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4434. };
  4435. Engine.prototype.flushFramebuffer = function () {
  4436. this._gl.flush();
  4437. };
  4438. Engine.prototype.restoreDefaultFramebuffer = function () {
  4439. this._currentRenderTarget = null;
  4440. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4441. this.setViewport(this._cachedViewport);
  4442. this.wipeCaches();
  4443. };
  4444. // VBOs
  4445. Engine.prototype._resetVertexBufferBinding = function () {
  4446. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4447. this._cachedVertexBuffers = null;
  4448. };
  4449. Engine.prototype.createVertexBuffer = function (vertices) {
  4450. var vbo = this._gl.createBuffer();
  4451. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4452. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4453. this._resetVertexBufferBinding();
  4454. vbo.references = 1;
  4455. return vbo;
  4456. };
  4457. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4458. var vbo = this._gl.createBuffer();
  4459. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4460. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4461. this._resetVertexBufferBinding();
  4462. vbo.references = 1;
  4463. return vbo;
  4464. };
  4465. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4466. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4467. if (offset === undefined) {
  4468. offset = 0;
  4469. }
  4470. if (vertices instanceof Float32Array) {
  4471. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4472. }
  4473. else {
  4474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4475. }
  4476. this._resetVertexBufferBinding();
  4477. };
  4478. Engine.prototype._resetIndexBufferBinding = function () {
  4479. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4480. this._cachedIndexBuffer = null;
  4481. };
  4482. Engine.prototype.createIndexBuffer = function (indices) {
  4483. var vbo = this._gl.createBuffer();
  4484. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4485. // Check for 32 bits indices
  4486. var arrayBuffer;
  4487. var need32Bits = false;
  4488. if (this._caps.uintIndices) {
  4489. for (var index = 0; index < indices.length; index++) {
  4490. if (indices[index] > 65535) {
  4491. need32Bits = true;
  4492. break;
  4493. }
  4494. }
  4495. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4496. }
  4497. else {
  4498. arrayBuffer = new Uint16Array(indices);
  4499. }
  4500. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4501. this._resetIndexBufferBinding();
  4502. vbo.references = 1;
  4503. vbo.is32Bits = need32Bits;
  4504. return vbo;
  4505. };
  4506. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4507. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4508. this._cachedVertexBuffers = vertexBuffer;
  4509. this._cachedEffectForVertexBuffers = effect;
  4510. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4511. var offset = 0;
  4512. for (var index = 0; index < vertexDeclaration.length; index++) {
  4513. var order = effect.getAttributeLocation(index);
  4514. if (order >= 0) {
  4515. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4516. }
  4517. offset += vertexDeclaration[index] * 4;
  4518. }
  4519. }
  4520. if (this._cachedIndexBuffer !== indexBuffer) {
  4521. this._cachedIndexBuffer = indexBuffer;
  4522. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4523. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4524. }
  4525. };
  4526. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4527. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4528. this._cachedVertexBuffers = vertexBuffers;
  4529. this._cachedEffectForVertexBuffers = effect;
  4530. var attributes = effect.getAttributesNames();
  4531. for (var index = 0; index < attributes.length; index++) {
  4532. var order = effect.getAttributeLocation(index);
  4533. if (order >= 0) {
  4534. var vertexBuffer = vertexBuffers[attributes[index]];
  4535. if (!vertexBuffer) {
  4536. continue;
  4537. }
  4538. var stride = vertexBuffer.getStrideSize();
  4539. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4540. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4541. }
  4542. }
  4543. }
  4544. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4545. this._cachedIndexBuffer = indexBuffer;
  4546. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4547. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4548. }
  4549. };
  4550. Engine.prototype._releaseBuffer = function (buffer) {
  4551. buffer.references--;
  4552. if (buffer.references === 0) {
  4553. this._gl.deleteBuffer(buffer);
  4554. return true;
  4555. }
  4556. return false;
  4557. };
  4558. Engine.prototype.createInstancesBuffer = function (capacity) {
  4559. var buffer = this._gl.createBuffer();
  4560. buffer.capacity = capacity;
  4561. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4562. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4563. return buffer;
  4564. };
  4565. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4566. this._gl.deleteBuffer(buffer);
  4567. };
  4568. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4569. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4570. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4571. for (var index = 0; index < 4; index++) {
  4572. var offsetLocation = offsetLocations[index];
  4573. this._gl.enableVertexAttribArray(offsetLocation);
  4574. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4575. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4576. }
  4577. };
  4578. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4579. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4580. for (var index = 0; index < 4; index++) {
  4581. var offsetLocation = offsetLocations[index];
  4582. this._gl.disableVertexAttribArray(offsetLocation);
  4583. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4584. }
  4585. };
  4586. Engine.prototype.applyStates = function () {
  4587. this._depthCullingState.apply(this._gl);
  4588. this._alphaState.apply(this._gl);
  4589. };
  4590. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4591. // Apply states
  4592. this.applyStates();
  4593. this._drawCalls++;
  4594. // Render
  4595. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4596. if (instancesCount) {
  4597. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4598. return;
  4599. }
  4600. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4601. };
  4602. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4603. // Apply states
  4604. this.applyStates();
  4605. this._drawCalls++;
  4606. if (instancesCount) {
  4607. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4608. return;
  4609. }
  4610. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4611. };
  4612. // Shaders
  4613. Engine.prototype._releaseEffect = function (effect) {
  4614. if (this._compiledEffects[effect._key]) {
  4615. delete this._compiledEffects[effect._key];
  4616. if (effect.getProgram()) {
  4617. this._gl.deleteProgram(effect.getProgram());
  4618. }
  4619. }
  4620. };
  4621. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4622. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4623. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4624. var name = vertex + "+" + fragment + "@" + defines;
  4625. if (this._compiledEffects[name]) {
  4626. return this._compiledEffects[name];
  4627. }
  4628. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4629. effect._key = name;
  4630. this._compiledEffects[name] = effect;
  4631. return effect;
  4632. };
  4633. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4634. if (uniformsNames === void 0) { uniformsNames = []; }
  4635. if (samplers === void 0) { samplers = []; }
  4636. if (defines === void 0) { defines = ""; }
  4637. return this.createEffect({
  4638. vertex: "particles",
  4639. fragmentElement: fragmentName
  4640. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4641. };
  4642. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4643. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4644. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4645. var shaderProgram = this._gl.createProgram();
  4646. this._gl.attachShader(shaderProgram, vertexShader);
  4647. this._gl.attachShader(shaderProgram, fragmentShader);
  4648. this._gl.linkProgram(shaderProgram);
  4649. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4650. if (!linked) {
  4651. var error = this._gl.getProgramInfoLog(shaderProgram);
  4652. if (error) {
  4653. throw new Error(error);
  4654. }
  4655. }
  4656. this._gl.deleteShader(vertexShader);
  4657. this._gl.deleteShader(fragmentShader);
  4658. return shaderProgram;
  4659. };
  4660. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4661. var results = [];
  4662. for (var index = 0; index < uniformsNames.length; index++) {
  4663. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4664. }
  4665. return results;
  4666. };
  4667. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4668. var results = [];
  4669. for (var index = 0; index < attributesNames.length; index++) {
  4670. try {
  4671. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4672. }
  4673. catch (e) {
  4674. results.push(-1);
  4675. }
  4676. }
  4677. return results;
  4678. };
  4679. Engine.prototype.enableEffect = function (effect) {
  4680. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4681. if (effect && effect.onBind) {
  4682. effect.onBind(effect);
  4683. }
  4684. return;
  4685. }
  4686. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4687. // Use program
  4688. this._gl.useProgram(effect.getProgram());
  4689. for (var i in this._vertexAttribArrays) {
  4690. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4691. continue;
  4692. }
  4693. this._vertexAttribArrays[i] = false;
  4694. this._gl.disableVertexAttribArray(i);
  4695. }
  4696. var attributesCount = effect.getAttributesCount();
  4697. for (var index = 0; index < attributesCount; index++) {
  4698. // Attributes
  4699. var order = effect.getAttributeLocation(index);
  4700. if (order >= 0) {
  4701. this._vertexAttribArrays[order] = true;
  4702. this._gl.enableVertexAttribArray(order);
  4703. }
  4704. }
  4705. this._currentEffect = effect;
  4706. if (effect.onBind) {
  4707. effect.onBind(effect);
  4708. }
  4709. };
  4710. Engine.prototype.setArray = function (uniform, array) {
  4711. if (!uniform)
  4712. return;
  4713. this._gl.uniform1fv(uniform, array);
  4714. };
  4715. Engine.prototype.setArray2 = function (uniform, array) {
  4716. if (!uniform || array.length % 2 !== 0)
  4717. return;
  4718. this._gl.uniform2fv(uniform, array);
  4719. };
  4720. Engine.prototype.setArray3 = function (uniform, array) {
  4721. if (!uniform || array.length % 3 !== 0)
  4722. return;
  4723. this._gl.uniform3fv(uniform, array);
  4724. };
  4725. Engine.prototype.setArray4 = function (uniform, array) {
  4726. if (!uniform || array.length % 4 !== 0)
  4727. return;
  4728. this._gl.uniform4fv(uniform, array);
  4729. };
  4730. Engine.prototype.setMatrices = function (uniform, matrices) {
  4731. if (!uniform)
  4732. return;
  4733. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4734. };
  4735. Engine.prototype.setMatrix = function (uniform, matrix) {
  4736. if (!uniform)
  4737. return;
  4738. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4739. };
  4740. Engine.prototype.setFloat = function (uniform, value) {
  4741. if (!uniform)
  4742. return;
  4743. this._gl.uniform1f(uniform, value);
  4744. };
  4745. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4746. if (!uniform)
  4747. return;
  4748. this._gl.uniform2f(uniform, x, y);
  4749. };
  4750. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4751. if (!uniform)
  4752. return;
  4753. this._gl.uniform3f(uniform, x, y, z);
  4754. };
  4755. Engine.prototype.setBool = function (uniform, bool) {
  4756. if (!uniform)
  4757. return;
  4758. this._gl.uniform1i(uniform, bool);
  4759. };
  4760. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4761. if (!uniform)
  4762. return;
  4763. this._gl.uniform4f(uniform, x, y, z, w);
  4764. };
  4765. Engine.prototype.setColor3 = function (uniform, color3) {
  4766. if (!uniform)
  4767. return;
  4768. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4769. };
  4770. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4771. if (!uniform)
  4772. return;
  4773. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4774. };
  4775. // States
  4776. Engine.prototype.setState = function (culling, zOffset, force) {
  4777. if (zOffset === void 0) { zOffset = 0; }
  4778. // Culling
  4779. if (this._depthCullingState.cull !== culling || force) {
  4780. if (culling) {
  4781. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4782. this._depthCullingState.cull = true;
  4783. }
  4784. else {
  4785. this._depthCullingState.cull = false;
  4786. }
  4787. }
  4788. // Z offset
  4789. this._depthCullingState.zOffset = zOffset;
  4790. };
  4791. Engine.prototype.setDepthBuffer = function (enable) {
  4792. this._depthCullingState.depthTest = enable;
  4793. };
  4794. Engine.prototype.getDepthWrite = function () {
  4795. return this._depthCullingState.depthMask;
  4796. };
  4797. Engine.prototype.setDepthWrite = function (enable) {
  4798. this._depthCullingState.depthMask = enable;
  4799. };
  4800. Engine.prototype.setColorWrite = function (enable) {
  4801. this._gl.colorMask(enable, enable, enable, enable);
  4802. };
  4803. Engine.prototype.setAlphaMode = function (mode) {
  4804. switch (mode) {
  4805. case Engine.ALPHA_DISABLE:
  4806. this.setDepthWrite(true);
  4807. this._alphaState.alphaBlend = false;
  4808. break;
  4809. case Engine.ALPHA_COMBINE:
  4810. this.setDepthWrite(false);
  4811. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4812. this._alphaState.alphaBlend = true;
  4813. break;
  4814. case Engine.ALPHA_ADD:
  4815. this.setDepthWrite(false);
  4816. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4817. this._alphaState.alphaBlend = true;
  4818. break;
  4819. }
  4820. this._alphaMode = mode;
  4821. };
  4822. Engine.prototype.getAlphaMode = function () {
  4823. return this._alphaMode;
  4824. };
  4825. Engine.prototype.setAlphaTesting = function (enable) {
  4826. this._alphaTest = enable;
  4827. };
  4828. Engine.prototype.getAlphaTesting = function () {
  4829. return this._alphaTest;
  4830. };
  4831. // Textures
  4832. Engine.prototype.wipeCaches = function () {
  4833. this._activeTexturesCache = [];
  4834. this._currentEffect = null;
  4835. this._depthCullingState.reset();
  4836. this._alphaState.reset();
  4837. this._cachedVertexBuffers = null;
  4838. this._cachedIndexBuffer = null;
  4839. this._cachedEffectForVertexBuffers = null;
  4840. };
  4841. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4842. var gl = this._gl;
  4843. gl.bindTexture(gl.TEXTURE_2D, texture);
  4844. var magFilter = gl.NEAREST;
  4845. var minFilter = gl.NEAREST;
  4846. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4847. magFilter = gl.LINEAR;
  4848. minFilter = gl.LINEAR;
  4849. }
  4850. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4851. magFilter = gl.LINEAR;
  4852. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4853. }
  4854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4856. gl.bindTexture(gl.TEXTURE_2D, null);
  4857. texture.samplingMode = samplingMode;
  4858. };
  4859. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4860. var _this = this;
  4861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4862. if (onLoad === void 0) { onLoad = null; }
  4863. if (onError === void 0) { onError = null; }
  4864. if (buffer === void 0) { buffer = null; }
  4865. var texture = this._gl.createTexture();
  4866. var extension;
  4867. var fromData = false;
  4868. if (url.substr(0, 5) === "data:") {
  4869. fromData = true;
  4870. }
  4871. if (!fromData)
  4872. extension = url.substr(url.length - 4, 4).toLowerCase();
  4873. else {
  4874. var oldUrl = url;
  4875. fromData = oldUrl.split(':');
  4876. url = oldUrl;
  4877. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4878. }
  4879. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4880. var isTGA = (extension === ".tga");
  4881. scene._addPendingData(texture);
  4882. texture.url = url;
  4883. texture.noMipmap = noMipmap;
  4884. texture.references = 1;
  4885. this._loadedTexturesCache.push(texture);
  4886. var onerror = function () {
  4887. scene._removePendingData(texture);
  4888. if (onError) {
  4889. onError();
  4890. }
  4891. };
  4892. if (isTGA) {
  4893. var callback = function (arrayBuffer) {
  4894. var data = new Uint8Array(arrayBuffer);
  4895. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4896. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4897. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4898. if (onLoad) {
  4899. onLoad();
  4900. }
  4901. }, samplingMode);
  4902. };
  4903. if (!(fromData instanceof Array))
  4904. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4905. callback(arrayBuffer);
  4906. }, onerror, scene.database, true);
  4907. else
  4908. callback(buffer);
  4909. }
  4910. else if (isDDS) {
  4911. callback = function (data) {
  4912. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4913. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4914. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4915. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4916. if (onLoad) {
  4917. onLoad();
  4918. }
  4919. }, samplingMode);
  4920. };
  4921. if (!(fromData instanceof Array))
  4922. BABYLON.Tools.LoadFile(url, function (data) {
  4923. callback(data);
  4924. }, onerror, scene.database, true);
  4925. else
  4926. callback(buffer);
  4927. }
  4928. else {
  4929. var onload = function (img) {
  4930. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4931. var isPot = (img.width === potWidth && img.height === potHeight);
  4932. if (!isPot) {
  4933. _this._prepareWorkingCanvas();
  4934. _this._workingCanvas.width = potWidth;
  4935. _this._workingCanvas.height = potHeight;
  4936. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4937. _this._workingContext.imageSmoothingEnabled = false;
  4938. _this._workingContext.mozImageSmoothingEnabled = false;
  4939. _this._workingContext.oImageSmoothingEnabled = false;
  4940. _this._workingContext.webkitImageSmoothingEnabled = false;
  4941. _this._workingContext.msImageSmoothingEnabled = false;
  4942. }
  4943. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4944. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4945. _this._workingContext.imageSmoothingEnabled = true;
  4946. _this._workingContext.mozImageSmoothingEnabled = true;
  4947. _this._workingContext.oImageSmoothingEnabled = true;
  4948. _this._workingContext.webkitImageSmoothingEnabled = true;
  4949. _this._workingContext.msImageSmoothingEnabled = true;
  4950. }
  4951. }
  4952. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4953. if (onLoad) {
  4954. onLoad();
  4955. }
  4956. }, samplingMode);
  4957. };
  4958. if (!(fromData instanceof Array))
  4959. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4960. else
  4961. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4962. }
  4963. return texture;
  4964. };
  4965. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4966. var texture = this._gl.createTexture();
  4967. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4968. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4969. // Format
  4970. var internalFormat = this._gl.RGBA;
  4971. switch (format) {
  4972. case Engine.TEXTUREFORMAT_ALPHA:
  4973. internalFormat = this._gl.ALPHA;
  4974. break;
  4975. case Engine.TEXTUREFORMAT_LUMINANCE:
  4976. internalFormat = this._gl.LUMINANCE;
  4977. break;
  4978. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4979. internalFormat = this._gl.LUMINANCE_ALPHA;
  4980. break;
  4981. case Engine.TEXTUREFORMAT_RGB:
  4982. internalFormat = this._gl.RGB;
  4983. break;
  4984. case Engine.TEXTUREFORMAT_RGBA:
  4985. internalFormat = this._gl.RGBA;
  4986. break;
  4987. }
  4988. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4989. if (generateMipMaps) {
  4990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4991. }
  4992. // Filters
  4993. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4996. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4997. this._activeTexturesCache = [];
  4998. texture._baseWidth = width;
  4999. texture._baseHeight = height;
  5000. texture._width = width;
  5001. texture._height = height;
  5002. texture.isReady = true;
  5003. texture.references = 1;
  5004. texture.samplingMode = samplingMode;
  5005. this._loadedTexturesCache.push(texture);
  5006. return texture;
  5007. };
  5008. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5009. var texture = this._gl.createTexture();
  5010. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5011. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5012. this._activeTexturesCache = [];
  5013. texture._baseWidth = width;
  5014. texture._baseHeight = height;
  5015. texture._width = width;
  5016. texture._height = height;
  5017. texture.isReady = false;
  5018. texture.generateMipMaps = generateMipMaps;
  5019. texture.references = 1;
  5020. texture.samplingMode = samplingMode;
  5021. this.updateTextureSamplingMode(samplingMode, texture);
  5022. this._loadedTexturesCache.push(texture);
  5023. return texture;
  5024. };
  5025. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5026. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5027. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5030. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5031. };
  5032. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5033. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5034. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5035. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5036. if (texture.generateMipMaps) {
  5037. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5038. }
  5039. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5040. this._activeTexturesCache = [];
  5041. texture.isReady = true;
  5042. };
  5043. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5044. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5045. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5046. // Scale the video if it is a NPOT using the current working canvas
  5047. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5048. if (!texture._workingCanvas) {
  5049. texture._workingCanvas = document.createElement("canvas");
  5050. texture._workingContext = texture._workingCanvas.getContext("2d");
  5051. texture._workingCanvas.width = texture._width;
  5052. texture._workingCanvas.height = texture._height;
  5053. }
  5054. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5055. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5056. }
  5057. else {
  5058. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5059. }
  5060. if (texture.generateMipMaps) {
  5061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5062. }
  5063. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5064. this._activeTexturesCache = [];
  5065. texture.isReady = true;
  5066. };
  5067. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5068. // old version had a "generateMipMaps" arg instead of options.
  5069. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5070. // in the same way, generateDepthBuffer is defaulted to true
  5071. var generateMipMaps = false;
  5072. var generateDepthBuffer = true;
  5073. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5074. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5075. if (options !== undefined) {
  5076. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5077. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5078. type = options.type === undefined ? type : options.type;
  5079. if (options.samplingMode !== undefined) {
  5080. samplingMode = options.samplingMode;
  5081. }
  5082. if (type === Engine.TEXTURETYPE_FLOAT) {
  5083. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5084. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5085. }
  5086. }
  5087. var gl = this._gl;
  5088. var texture = gl.createTexture();
  5089. gl.bindTexture(gl.TEXTURE_2D, texture);
  5090. var width = size.width || size;
  5091. var height = size.height || size;
  5092. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5093. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5094. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5095. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5096. }
  5097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5101. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5102. var depthBuffer;
  5103. // Create the depth buffer
  5104. if (generateDepthBuffer) {
  5105. depthBuffer = gl.createRenderbuffer();
  5106. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5107. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5108. }
  5109. // Create the framebuffer
  5110. var framebuffer = gl.createFramebuffer();
  5111. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5113. if (generateDepthBuffer) {
  5114. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5115. }
  5116. // Unbind
  5117. gl.bindTexture(gl.TEXTURE_2D, null);
  5118. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5119. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5120. texture._framebuffer = framebuffer;
  5121. if (generateDepthBuffer) {
  5122. texture._depthBuffer = depthBuffer;
  5123. }
  5124. texture._width = width;
  5125. texture._height = height;
  5126. texture.isReady = true;
  5127. texture.generateMipMaps = generateMipMaps;
  5128. texture.references = 1;
  5129. texture.samplingMode = samplingMode;
  5130. this._activeTexturesCache = [];
  5131. this._loadedTexturesCache.push(texture);
  5132. return texture;
  5133. };
  5134. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5135. var _this = this;
  5136. var gl = this._gl;
  5137. var texture = gl.createTexture();
  5138. texture.isCube = true;
  5139. texture.url = rootUrl;
  5140. texture.references = 1;
  5141. this._loadedTexturesCache.push(texture);
  5142. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5143. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5144. if (isDDS) {
  5145. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5146. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5147. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5148. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5150. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5151. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5152. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5153. }
  5154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5158. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5159. _this._activeTexturesCache = [];
  5160. texture._width = info.width;
  5161. texture._height = info.height;
  5162. texture.isReady = true;
  5163. }, null, null, true);
  5164. }
  5165. else {
  5166. cascadeLoad(rootUrl, scene, function (imgs) {
  5167. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5168. var height = width;
  5169. _this._prepareWorkingCanvas();
  5170. _this._workingCanvas.width = width;
  5171. _this._workingCanvas.height = height;
  5172. var faces = [
  5173. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5174. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5175. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5176. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5177. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5178. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5179. ];
  5180. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5181. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5182. for (var index = 0; index < faces.length; index++) {
  5183. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5184. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5185. }
  5186. if (!noMipmap) {
  5187. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5188. }
  5189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5193. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5194. _this._activeTexturesCache = [];
  5195. texture._width = width;
  5196. texture._height = height;
  5197. texture.isReady = true;
  5198. }, extensions);
  5199. }
  5200. return texture;
  5201. };
  5202. Engine.prototype._releaseTexture = function (texture) {
  5203. var gl = this._gl;
  5204. if (texture._framebuffer) {
  5205. gl.deleteFramebuffer(texture._framebuffer);
  5206. }
  5207. if (texture._depthBuffer) {
  5208. gl.deleteRenderbuffer(texture._depthBuffer);
  5209. }
  5210. gl.deleteTexture(texture);
  5211. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5212. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5213. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5214. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5215. this._activeTexturesCache[channel] = null;
  5216. }
  5217. var index = this._loadedTexturesCache.indexOf(texture);
  5218. if (index !== -1) {
  5219. this._loadedTexturesCache.splice(index, 1);
  5220. }
  5221. };
  5222. Engine.prototype.bindSamplers = function (effect) {
  5223. this._gl.useProgram(effect.getProgram());
  5224. var samplers = effect.getSamplers();
  5225. for (var index = 0; index < samplers.length; index++) {
  5226. var uniform = effect.getUniform(samplers[index]);
  5227. this._gl.uniform1i(uniform, index);
  5228. }
  5229. this._currentEffect = null;
  5230. };
  5231. Engine.prototype._bindTexture = function (channel, texture) {
  5232. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5233. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5234. this._activeTexturesCache[channel] = null;
  5235. };
  5236. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5237. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5238. };
  5239. Engine.prototype.setTexture = function (channel, texture) {
  5240. if (channel < 0) {
  5241. return;
  5242. }
  5243. // Not ready?
  5244. if (!texture || !texture.isReady()) {
  5245. if (this._activeTexturesCache[channel] != null) {
  5246. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5247. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5248. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5249. this._activeTexturesCache[channel] = null;
  5250. }
  5251. return;
  5252. }
  5253. // Video
  5254. if (texture instanceof BABYLON.VideoTexture) {
  5255. if (texture.update()) {
  5256. this._activeTexturesCache[channel] = null;
  5257. }
  5258. }
  5259. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5260. texture.delayLoad();
  5261. return;
  5262. }
  5263. if (this._activeTexturesCache[channel] === texture) {
  5264. return;
  5265. }
  5266. this._activeTexturesCache[channel] = texture;
  5267. var internalTexture = texture.getInternalTexture();
  5268. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5269. if (internalTexture.isCube) {
  5270. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5271. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5272. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5273. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5274. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5275. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5276. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5277. }
  5278. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5279. }
  5280. else {
  5281. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5282. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5283. internalTexture._cachedWrapU = texture.wrapU;
  5284. switch (texture.wrapU) {
  5285. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5287. break;
  5288. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5290. break;
  5291. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5292. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5293. break;
  5294. }
  5295. }
  5296. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5297. internalTexture._cachedWrapV = texture.wrapV;
  5298. switch (texture.wrapV) {
  5299. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5301. break;
  5302. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5304. break;
  5305. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5307. break;
  5308. }
  5309. }
  5310. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5311. }
  5312. };
  5313. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5314. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5315. var value = texture.anisotropicFilteringLevel;
  5316. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5317. value = 1;
  5318. }
  5319. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5320. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5321. texture._cachedAnisotropicFilteringLevel = value;
  5322. }
  5323. };
  5324. Engine.prototype.readPixels = function (x, y, width, height) {
  5325. var data = new Uint8Array(height * width * 4);
  5326. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5327. return data;
  5328. };
  5329. // Dispose
  5330. Engine.prototype.dispose = function () {
  5331. this.hideLoadingUI();
  5332. this.stopRenderLoop();
  5333. while (this.scenes.length) {
  5334. this.scenes[0].dispose();
  5335. }
  5336. // Release audio engine
  5337. Engine.audioEngine.dispose();
  5338. for (var name in this._compiledEffects) {
  5339. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5340. }
  5341. for (var i in this._vertexAttribArrays) {
  5342. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5343. continue;
  5344. }
  5345. this._gl.disableVertexAttribArray(i);
  5346. }
  5347. // Events
  5348. window.removeEventListener("blur", this._onBlur);
  5349. window.removeEventListener("focus", this._onFocus);
  5350. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5351. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5352. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5353. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5354. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5355. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5356. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5357. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5358. };
  5359. // Loading screen
  5360. Engine.prototype.displayLoadingUI = function () {
  5361. var _this = this;
  5362. this._loadingDiv = document.createElement("div");
  5363. this._loadingDiv.style.opacity = "0";
  5364. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5365. // Loading text
  5366. this._loadingTextDiv = document.createElement("div");
  5367. this._loadingTextDiv.style.position = "absolute";
  5368. this._loadingTextDiv.style.left = "0";
  5369. this._loadingTextDiv.style.top = "50%";
  5370. this._loadingTextDiv.style.marginTop = "80px";
  5371. this._loadingTextDiv.style.width = "100%";
  5372. this._loadingTextDiv.style.height = "20px";
  5373. this._loadingTextDiv.style.fontFamily = "Arial";
  5374. this._loadingTextDiv.style.fontSize = "14px";
  5375. this._loadingTextDiv.style.color = "white";
  5376. this._loadingTextDiv.style.textAlign = "center";
  5377. this._loadingTextDiv.innerHTML = "Loading";
  5378. this._loadingDiv.appendChild(this._loadingTextDiv);
  5379. // Loading img
  5380. var imgBack = new Image();
  5381. 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==";
  5382. imgBack.style.position = "absolute";
  5383. imgBack.style.left = "50%";
  5384. imgBack.style.top = "50%";
  5385. imgBack.style.marginLeft = "-50px";
  5386. imgBack.style.marginTop = "-50px";
  5387. imgBack.style.transition = "transform 1.0s ease";
  5388. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5389. var deg = 360;
  5390. var onTransitionEnd = function () {
  5391. deg += 360;
  5392. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5393. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5394. };
  5395. imgBack.addEventListener("transitionend", onTransitionEnd);
  5396. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5397. this._loadingDiv.appendChild(imgBack);
  5398. // front image
  5399. var imgFront = new Image();
  5400. 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=";
  5401. imgFront.style.position = "absolute";
  5402. imgFront.style.left = "50%";
  5403. imgFront.style.top = "50%";
  5404. imgFront.style.marginLeft = "-50px";
  5405. imgFront.style.marginTop = "-50px";
  5406. this._loadingDiv.appendChild(imgFront);
  5407. // Resize
  5408. this._resizeLoadingUI = function () {
  5409. var canvasRect = _this.getRenderingCanvasClientRect();
  5410. _this._loadingDiv.style.position = "absolute";
  5411. _this._loadingDiv.style.left = canvasRect.left + "px";
  5412. _this._loadingDiv.style.top = canvasRect.top + "px";
  5413. _this._loadingDiv.style.width = canvasRect.width + "px";
  5414. _this._loadingDiv.style.height = canvasRect.height + "px";
  5415. };
  5416. this._resizeLoadingUI();
  5417. window.addEventListener("resize", this._resizeLoadingUI);
  5418. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5419. document.body.appendChild(this._loadingDiv);
  5420. setTimeout(function () {
  5421. _this._loadingDiv.style.opacity = "1";
  5422. imgBack.style.transform = "rotateZ(360deg)";
  5423. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5424. }, 0);
  5425. };
  5426. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5427. set: function (text) {
  5428. if (!this._loadingDiv) {
  5429. return;
  5430. }
  5431. this._loadingTextDiv.innerHTML = text;
  5432. },
  5433. enumerable: true,
  5434. configurable: true
  5435. });
  5436. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5437. get: function () {
  5438. return this._loadingDivBackgroundColor;
  5439. },
  5440. set: function (color) {
  5441. this._loadingDivBackgroundColor = color;
  5442. if (!this._loadingDiv) {
  5443. return;
  5444. }
  5445. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5446. },
  5447. enumerable: true,
  5448. configurable: true
  5449. });
  5450. Engine.prototype.hideLoadingUI = function () {
  5451. var _this = this;
  5452. if (!this._loadingDiv) {
  5453. return;
  5454. }
  5455. var onTransitionEnd = function () {
  5456. if (!_this._loadingDiv) {
  5457. return;
  5458. }
  5459. document.body.removeChild(_this._loadingDiv);
  5460. window.removeEventListener("resize", _this._resizeLoadingUI);
  5461. _this._loadingDiv = null;
  5462. };
  5463. this._loadingDiv.style.opacity = "0";
  5464. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5465. };
  5466. // FPS
  5467. Engine.prototype.getFps = function () {
  5468. return this.fps;
  5469. };
  5470. Engine.prototype.getDeltaTime = function () {
  5471. return this.deltaTime;
  5472. };
  5473. Engine.prototype._measureFps = function () {
  5474. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5475. var length = this.previousFramesDuration.length;
  5476. if (length >= 2) {
  5477. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5478. }
  5479. if (length >= this.fpsRange) {
  5480. if (length > this.fpsRange) {
  5481. this.previousFramesDuration.splice(0, 1);
  5482. length = this.previousFramesDuration.length;
  5483. }
  5484. var sum = 0;
  5485. for (var id = 0; id < length - 1; id++) {
  5486. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5487. }
  5488. this.fps = 1000.0 / (sum / (length - 1));
  5489. }
  5490. };
  5491. // Statics
  5492. Engine.isSupported = function () {
  5493. try {
  5494. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5495. if (navigator.isCocoonJS) {
  5496. return true;
  5497. }
  5498. var tempcanvas = document.createElement("canvas");
  5499. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5500. return gl != null && !!window.WebGLRenderingContext;
  5501. }
  5502. catch (e) {
  5503. return false;
  5504. }
  5505. };
  5506. // Const statics
  5507. Engine._ALPHA_DISABLE = 0;
  5508. Engine._ALPHA_ADD = 1;
  5509. Engine._ALPHA_COMBINE = 2;
  5510. Engine._DELAYLOADSTATE_NONE = 0;
  5511. Engine._DELAYLOADSTATE_LOADED = 1;
  5512. Engine._DELAYLOADSTATE_LOADING = 2;
  5513. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5514. Engine._TEXTUREFORMAT_ALPHA = 0;
  5515. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5516. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5517. Engine._TEXTUREFORMAT_RGB = 4;
  5518. Engine._TEXTUREFORMAT_RGBA = 4;
  5519. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5520. Engine._TEXTURETYPE_FLOAT = 1;
  5521. // Updatable statics so stick with vars here
  5522. Engine.Epsilon = 0.001;
  5523. Engine.CollisionsEpsilon = 0.001;
  5524. Engine.ShadersRepository = "Babylon/Shaders/";
  5525. return Engine;
  5526. })();
  5527. BABYLON.Engine = Engine;
  5528. })(BABYLON || (BABYLON = {}));
  5529. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5530. (function (BABYLON) {
  5531. /**
  5532. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5533. */
  5534. var Node = (function () {
  5535. /**
  5536. * @constructor
  5537. * @param {string} name - the name and id to be given to this node
  5538. * @param {BABYLON.Scene} the scene this node will be added to
  5539. */
  5540. function Node(name, scene) {
  5541. this.state = "";
  5542. this.animations = new Array();
  5543. this._childrenFlag = -1;
  5544. this._isEnabled = true;
  5545. this._isReady = true;
  5546. this._currentRenderId = -1;
  5547. this._parentRenderId = -1;
  5548. this.name = name;
  5549. this.id = name;
  5550. this._scene = scene;
  5551. this._initCache();
  5552. }
  5553. Node.prototype.getScene = function () {
  5554. return this._scene;
  5555. };
  5556. Node.prototype.getEngine = function () {
  5557. return this._scene.getEngine();
  5558. };
  5559. // override it in derived class
  5560. Node.prototype.getWorldMatrix = function () {
  5561. return BABYLON.Matrix.Identity();
  5562. };
  5563. // override it in derived class if you add new variables to the cache
  5564. // and call the parent class method
  5565. Node.prototype._initCache = function () {
  5566. this._cache = {};
  5567. this._cache.parent = undefined;
  5568. };
  5569. Node.prototype.updateCache = function (force) {
  5570. if (!force && this.isSynchronized())
  5571. return;
  5572. this._cache.parent = this.parent;
  5573. this._updateCache();
  5574. };
  5575. // override it in derived class if you add new variables to the cache
  5576. // and call the parent class method if !ignoreParentClass
  5577. Node.prototype._updateCache = function (ignoreParentClass) {
  5578. };
  5579. // override it in derived class if you add new variables to the cache
  5580. Node.prototype._isSynchronized = function () {
  5581. return true;
  5582. };
  5583. Node.prototype.isSynchronizedWithParent = function () {
  5584. if (!this.parent) {
  5585. return true;
  5586. }
  5587. if (this._parentRenderId !== this.parent._currentRenderId) {
  5588. return false;
  5589. }
  5590. this._parentRenderId = this.parent._currentRenderId;
  5591. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5592. };
  5593. Node.prototype.isSynchronized = function (updateCache) {
  5594. var check = this.hasNewParent();
  5595. check = check || !this.isSynchronizedWithParent();
  5596. check = check || !this._isSynchronized();
  5597. if (updateCache)
  5598. this.updateCache(true);
  5599. return !check;
  5600. };
  5601. Node.prototype.hasNewParent = function (update) {
  5602. if (this._cache.parent === this.parent)
  5603. return false;
  5604. if (update)
  5605. this._cache.parent = this.parent;
  5606. return true;
  5607. };
  5608. /**
  5609. * Is this node ready to be used/rendered
  5610. * @return {boolean} is it ready
  5611. */
  5612. Node.prototype.isReady = function () {
  5613. return this._isReady;
  5614. };
  5615. /**
  5616. * Is this node enabled.
  5617. * If the node has a parent and is enabled, the parent will be inspected as well.
  5618. * @return {boolean} whether this node (and its parent) is enabled.
  5619. * @see setEnabled
  5620. */
  5621. Node.prototype.isEnabled = function () {
  5622. if (!this._isEnabled) {
  5623. return false;
  5624. }
  5625. if (this.parent) {
  5626. return this.parent.isEnabled();
  5627. }
  5628. return true;
  5629. };
  5630. /**
  5631. * Set the enabled state of this node.
  5632. * @param {boolean} value - the new enabled state
  5633. * @see isEnabled
  5634. */
  5635. Node.prototype.setEnabled = function (value) {
  5636. this._isEnabled = value;
  5637. };
  5638. /**
  5639. * Is this node a descendant of the given node.
  5640. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5641. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5642. * @see parent
  5643. */
  5644. Node.prototype.isDescendantOf = function (ancestor) {
  5645. if (this.parent) {
  5646. if (this.parent === ancestor) {
  5647. return true;
  5648. }
  5649. return this.parent.isDescendantOf(ancestor);
  5650. }
  5651. return false;
  5652. };
  5653. Node.prototype._getDescendants = function (list, results) {
  5654. for (var index = 0; index < list.length; index++) {
  5655. var item = list[index];
  5656. if (item.isDescendantOf(this)) {
  5657. results.push(item);
  5658. }
  5659. }
  5660. };
  5661. /**
  5662. * Will return all nodes that have this node as parent.
  5663. * @return {BABYLON.Node[]} all children nodes of all types.
  5664. */
  5665. Node.prototype.getDescendants = function () {
  5666. var results = [];
  5667. this._getDescendants(this._scene.meshes, results);
  5668. this._getDescendants(this._scene.lights, results);
  5669. this._getDescendants(this._scene.cameras, results);
  5670. return results;
  5671. };
  5672. Node.prototype._setReady = function (state) {
  5673. if (state == this._isReady) {
  5674. return;
  5675. }
  5676. if (!state) {
  5677. this._isReady = false;
  5678. return;
  5679. }
  5680. this._isReady = true;
  5681. if (this.onReady) {
  5682. this.onReady(this);
  5683. }
  5684. };
  5685. return Node;
  5686. })();
  5687. BABYLON.Node = Node;
  5688. })(BABYLON || (BABYLON = {}));
  5689. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5690. (function (BABYLON) {
  5691. var BoundingSphere = (function () {
  5692. function BoundingSphere(minimum, maximum) {
  5693. this.minimum = minimum;
  5694. this.maximum = maximum;
  5695. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5696. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5697. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5698. this.radius = distance * 0.5;
  5699. this.centerWorld = BABYLON.Vector3.Zero();
  5700. this._update(BABYLON.Matrix.Identity());
  5701. }
  5702. // Methods
  5703. BoundingSphere.prototype._update = function (world) {
  5704. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5705. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5706. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5707. };
  5708. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5709. for (var i = 0; i < 6; i++) {
  5710. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5711. return false;
  5712. }
  5713. return true;
  5714. };
  5715. BoundingSphere.prototype.intersectsPoint = function (point) {
  5716. var x = this.centerWorld.x - point.x;
  5717. var y = this.centerWorld.y - point.y;
  5718. var z = this.centerWorld.z - point.z;
  5719. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5720. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5721. return false;
  5722. return true;
  5723. };
  5724. // Statics
  5725. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5726. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5727. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5728. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5729. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5730. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5731. return false;
  5732. return true;
  5733. };
  5734. return BoundingSphere;
  5735. })();
  5736. BABYLON.BoundingSphere = BoundingSphere;
  5737. })(BABYLON || (BABYLON = {}));
  5738. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5739. (function (BABYLON) {
  5740. var BoundingBox = (function () {
  5741. function BoundingBox(minimum, maximum) {
  5742. this.minimum = minimum;
  5743. this.maximum = maximum;
  5744. this.vectors = new Array();
  5745. this.vectorsWorld = new Array();
  5746. // Bounding vectors
  5747. this.vectors.push(this.minimum.clone());
  5748. this.vectors.push(this.maximum.clone());
  5749. this.vectors.push(this.minimum.clone());
  5750. this.vectors[2].x = this.maximum.x;
  5751. this.vectors.push(this.minimum.clone());
  5752. this.vectors[3].y = this.maximum.y;
  5753. this.vectors.push(this.minimum.clone());
  5754. this.vectors[4].z = this.maximum.z;
  5755. this.vectors.push(this.maximum.clone());
  5756. this.vectors[5].z = this.minimum.z;
  5757. this.vectors.push(this.maximum.clone());
  5758. this.vectors[6].x = this.minimum.x;
  5759. this.vectors.push(this.maximum.clone());
  5760. this.vectors[7].y = this.minimum.y;
  5761. // OBB
  5762. this.center = this.maximum.add(this.minimum).scale(0.5);
  5763. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5764. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5765. for (var index = 0; index < this.vectors.length; index++) {
  5766. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5767. }
  5768. this.minimumWorld = BABYLON.Vector3.Zero();
  5769. this.maximumWorld = BABYLON.Vector3.Zero();
  5770. this._update(BABYLON.Matrix.Identity());
  5771. }
  5772. // Methods
  5773. BoundingBox.prototype.getWorldMatrix = function () {
  5774. return this._worldMatrix;
  5775. };
  5776. BoundingBox.prototype._update = function (world) {
  5777. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5778. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5779. for (var index = 0; index < this.vectors.length; index++) {
  5780. var v = this.vectorsWorld[index];
  5781. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5782. if (v.x < this.minimumWorld.x)
  5783. this.minimumWorld.x = v.x;
  5784. if (v.y < this.minimumWorld.y)
  5785. this.minimumWorld.y = v.y;
  5786. if (v.z < this.minimumWorld.z)
  5787. this.minimumWorld.z = v.z;
  5788. if (v.x > this.maximumWorld.x)
  5789. this.maximumWorld.x = v.x;
  5790. if (v.y > this.maximumWorld.y)
  5791. this.maximumWorld.y = v.y;
  5792. if (v.z > this.maximumWorld.z)
  5793. this.maximumWorld.z = v.z;
  5794. }
  5795. // OBB
  5796. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5797. this.center.scaleInPlace(0.5);
  5798. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5799. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5800. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5801. this._worldMatrix = world;
  5802. };
  5803. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5804. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5805. };
  5806. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5807. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5808. };
  5809. BoundingBox.prototype.intersectsPoint = function (point) {
  5810. var delta = BABYLON.Engine.Epsilon;
  5811. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5812. return false;
  5813. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5814. return false;
  5815. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5816. return false;
  5817. return true;
  5818. };
  5819. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5820. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5821. };
  5822. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5823. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5824. return false;
  5825. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5826. return false;
  5827. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5828. return false;
  5829. return true;
  5830. };
  5831. // Statics
  5832. BoundingBox.Intersects = function (box0, box1) {
  5833. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5834. return false;
  5835. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5836. return false;
  5837. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5838. return false;
  5839. return true;
  5840. };
  5841. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5842. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5843. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5844. return (num <= (sphereRadius * sphereRadius));
  5845. };
  5846. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5847. for (var p = 0; p < 6; p++) {
  5848. for (var i = 0; i < 8; i++) {
  5849. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5850. return false;
  5851. }
  5852. }
  5853. }
  5854. return true;
  5855. };
  5856. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5857. for (var p = 0; p < 6; p++) {
  5858. var inCount = 8;
  5859. for (var i = 0; i < 8; i++) {
  5860. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5861. --inCount;
  5862. }
  5863. else {
  5864. break;
  5865. }
  5866. }
  5867. if (inCount === 0)
  5868. return false;
  5869. }
  5870. return true;
  5871. };
  5872. return BoundingBox;
  5873. })();
  5874. BABYLON.BoundingBox = BoundingBox;
  5875. })(BABYLON || (BABYLON = {}));
  5876. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5877. (function (BABYLON) {
  5878. var computeBoxExtents = function (axis, box) {
  5879. var p = BABYLON.Vector3.Dot(box.center, axis);
  5880. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5881. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5882. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5883. var r = r0 + r1 + r2;
  5884. return {
  5885. min: p - r,
  5886. max: p + r
  5887. };
  5888. };
  5889. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5890. var axisOverlap = function (axis, box0, box1) {
  5891. var result0 = computeBoxExtents(axis, box0);
  5892. var result1 = computeBoxExtents(axis, box1);
  5893. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5894. };
  5895. var BoundingInfo = (function () {
  5896. function BoundingInfo(minimum, maximum) {
  5897. this.minimum = minimum;
  5898. this.maximum = maximum;
  5899. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5900. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5901. }
  5902. // Methods
  5903. BoundingInfo.prototype._update = function (world) {
  5904. this.boundingBox._update(world);
  5905. this.boundingSphere._update(world);
  5906. };
  5907. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5908. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5909. return false;
  5910. return this.boundingBox.isInFrustum(frustumPlanes);
  5911. };
  5912. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5913. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5914. };
  5915. BoundingInfo.prototype._checkCollision = function (collider) {
  5916. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5917. };
  5918. BoundingInfo.prototype.intersectsPoint = function (point) {
  5919. if (!this.boundingSphere.centerWorld) {
  5920. return false;
  5921. }
  5922. if (!this.boundingSphere.intersectsPoint(point)) {
  5923. return false;
  5924. }
  5925. if (!this.boundingBox.intersectsPoint(point)) {
  5926. return false;
  5927. }
  5928. return true;
  5929. };
  5930. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5931. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5932. return false;
  5933. }
  5934. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5935. return false;
  5936. }
  5937. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5938. return false;
  5939. }
  5940. if (!precise) {
  5941. return true;
  5942. }
  5943. var box0 = this.boundingBox;
  5944. var box1 = boundingInfo.boundingBox;
  5945. if (!axisOverlap(box0.directions[0], box0, box1))
  5946. return false;
  5947. if (!axisOverlap(box0.directions[1], box0, box1))
  5948. return false;
  5949. if (!axisOverlap(box0.directions[2], box0, box1))
  5950. return false;
  5951. if (!axisOverlap(box1.directions[0], box0, box1))
  5952. return false;
  5953. if (!axisOverlap(box1.directions[1], box0, box1))
  5954. return false;
  5955. if (!axisOverlap(box1.directions[2], box0, box1))
  5956. return false;
  5957. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5958. return false;
  5959. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5960. return false;
  5961. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5962. return false;
  5963. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5964. return false;
  5965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5966. return false;
  5967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5968. return false;
  5969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5970. return false;
  5971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5972. return false;
  5973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5974. return false;
  5975. return true;
  5976. };
  5977. return BoundingInfo;
  5978. })();
  5979. BABYLON.BoundingInfo = BoundingInfo;
  5980. })(BABYLON || (BABYLON = {}));
  5981. //# sourceMappingURL=babylon.boundingInfo.js.map
  5982. var BABYLON;
  5983. (function (BABYLON) {
  5984. var Light = (function (_super) {
  5985. __extends(Light, _super);
  5986. function Light(name, scene) {
  5987. _super.call(this, name, scene);
  5988. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5989. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5990. this.intensity = 1.0;
  5991. this.range = Number.MAX_VALUE;
  5992. this.includeOnlyWithLayerMask = 0;
  5993. this.includedOnlyMeshes = new Array();
  5994. this.excludedMeshes = new Array();
  5995. this._excludedMeshesIds = new Array();
  5996. this._includedOnlyMeshesIds = new Array();
  5997. scene.addLight(this);
  5998. }
  5999. Light.prototype.getShadowGenerator = function () {
  6000. return this._shadowGenerator;
  6001. };
  6002. Light.prototype.getAbsolutePosition = function () {
  6003. return BABYLON.Vector3.Zero();
  6004. };
  6005. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6006. };
  6007. Light.prototype._getWorldMatrix = function () {
  6008. return BABYLON.Matrix.Identity();
  6009. };
  6010. Light.prototype.canAffectMesh = function (mesh) {
  6011. if (!mesh) {
  6012. return true;
  6013. }
  6014. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6015. return false;
  6016. }
  6017. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6018. return false;
  6019. }
  6020. if (this.includeOnlyWithLayerMask !== 0 && this.includeOnlyWithLayerMask !== mesh.layerMask) {
  6021. return false;
  6022. }
  6023. return true;
  6024. };
  6025. Light.prototype.getWorldMatrix = function () {
  6026. this._currentRenderId = this.getScene().getRenderId();
  6027. var worldMatrix = this._getWorldMatrix();
  6028. if (this.parent && this.parent.getWorldMatrix) {
  6029. if (!this._parentedWorldMatrix) {
  6030. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6031. }
  6032. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6033. return this._parentedWorldMatrix;
  6034. }
  6035. return worldMatrix;
  6036. };
  6037. Light.prototype.dispose = function () {
  6038. if (this._shadowGenerator) {
  6039. this._shadowGenerator.dispose();
  6040. this._shadowGenerator = null;
  6041. }
  6042. // Remove from scene
  6043. this.getScene().removeLight(this);
  6044. };
  6045. return Light;
  6046. })(BABYLON.Node);
  6047. BABYLON.Light = Light;
  6048. })(BABYLON || (BABYLON = {}));
  6049. //# sourceMappingURL=babylon.light.js.map
  6050. var BABYLON;
  6051. (function (BABYLON) {
  6052. var PointLight = (function (_super) {
  6053. __extends(PointLight, _super);
  6054. function PointLight(name, position, scene) {
  6055. _super.call(this, name, scene);
  6056. this.position = position;
  6057. }
  6058. PointLight.prototype.getAbsolutePosition = function () {
  6059. return this._transformedPosition ? this._transformedPosition : this.position;
  6060. };
  6061. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6062. if (this.parent && this.parent.getWorldMatrix) {
  6063. if (!this._transformedPosition) {
  6064. this._transformedPosition = BABYLON.Vector3.Zero();
  6065. }
  6066. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6067. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6068. return;
  6069. }
  6070. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6071. };
  6072. PointLight.prototype.getShadowGenerator = function () {
  6073. return null;
  6074. };
  6075. PointLight.prototype._getWorldMatrix = function () {
  6076. if (!this._worldMatrix) {
  6077. this._worldMatrix = BABYLON.Matrix.Identity();
  6078. }
  6079. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6080. return this._worldMatrix;
  6081. };
  6082. return PointLight;
  6083. })(BABYLON.Light);
  6084. BABYLON.PointLight = PointLight;
  6085. })(BABYLON || (BABYLON = {}));
  6086. //# sourceMappingURL=babylon.pointLight.js.map
  6087. var BABYLON;
  6088. (function (BABYLON) {
  6089. var SpotLight = (function (_super) {
  6090. __extends(SpotLight, _super);
  6091. function SpotLight(name, position, direction, angle, exponent, scene) {
  6092. _super.call(this, name, scene);
  6093. this.position = position;
  6094. this.direction = direction;
  6095. this.angle = angle;
  6096. this.exponent = exponent;
  6097. }
  6098. SpotLight.prototype.getAbsolutePosition = function () {
  6099. return this.transformedPosition ? this.transformedPosition : this.position;
  6100. };
  6101. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6102. var activeCamera = this.getScene().activeCamera;
  6103. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6104. };
  6105. SpotLight.prototype.supportsVSM = function () {
  6106. return true;
  6107. };
  6108. SpotLight.prototype.needRefreshPerFrame = function () {
  6109. return false;
  6110. };
  6111. SpotLight.prototype.setDirectionToTarget = function (target) {
  6112. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6113. return this.direction;
  6114. };
  6115. SpotLight.prototype.computeTransformedPosition = function () {
  6116. if (this.parent && this.parent.getWorldMatrix) {
  6117. if (!this.transformedPosition) {
  6118. this.transformedPosition = BABYLON.Vector3.Zero();
  6119. }
  6120. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6121. return true;
  6122. }
  6123. return false;
  6124. };
  6125. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6126. var normalizeDirection;
  6127. if (this.parent && this.parent.getWorldMatrix) {
  6128. if (!this._transformedDirection) {
  6129. this._transformedDirection = BABYLON.Vector3.Zero();
  6130. }
  6131. this.computeTransformedPosition();
  6132. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6133. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6134. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6135. }
  6136. else {
  6137. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6138. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6139. }
  6140. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6141. };
  6142. SpotLight.prototype._getWorldMatrix = function () {
  6143. if (!this._worldMatrix) {
  6144. this._worldMatrix = BABYLON.Matrix.Identity();
  6145. }
  6146. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6147. return this._worldMatrix;
  6148. };
  6149. return SpotLight;
  6150. })(BABYLON.Light);
  6151. BABYLON.SpotLight = SpotLight;
  6152. })(BABYLON || (BABYLON = {}));
  6153. //# sourceMappingURL=babylon.spotLight.js.map
  6154. var BABYLON;
  6155. (function (BABYLON) {
  6156. var DirectionalLight = (function (_super) {
  6157. __extends(DirectionalLight, _super);
  6158. function DirectionalLight(name, direction, scene) {
  6159. _super.call(this, name, scene);
  6160. this.direction = direction;
  6161. this.shadowOrthoScale = 0.5;
  6162. this.position = direction.scale(-1);
  6163. }
  6164. DirectionalLight.prototype.getAbsolutePosition = function () {
  6165. return this.transformedPosition ? this.transformedPosition : this.position;
  6166. };
  6167. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6168. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6169. return this.direction;
  6170. };
  6171. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6172. var orthoLeft = Number.MAX_VALUE;
  6173. var orthoRight = Number.MIN_VALUE;
  6174. var orthoTop = Number.MIN_VALUE;
  6175. var orthoBottom = Number.MAX_VALUE;
  6176. var tempVector3 = BABYLON.Vector3.Zero();
  6177. var activeCamera = this.getScene().activeCamera;
  6178. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6179. var mesh = renderList[meshIndex];
  6180. if (!mesh) {
  6181. continue;
  6182. }
  6183. var boundingInfo = mesh.getBoundingInfo();
  6184. if (!boundingInfo) {
  6185. continue;
  6186. }
  6187. var boundingBox = boundingInfo.boundingBox;
  6188. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6189. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6190. if (tempVector3.x < orthoLeft)
  6191. orthoLeft = tempVector3.x;
  6192. if (tempVector3.y < orthoBottom)
  6193. orthoBottom = tempVector3.y;
  6194. if (tempVector3.x > orthoRight)
  6195. orthoRight = tempVector3.x;
  6196. if (tempVector3.y > orthoTop)
  6197. orthoTop = tempVector3.y;
  6198. }
  6199. }
  6200. var xOffset = orthoRight - orthoLeft;
  6201. var yOffset = orthoTop - orthoBottom;
  6202. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6203. };
  6204. DirectionalLight.prototype.supportsVSM = function () {
  6205. return true;
  6206. };
  6207. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6208. return true;
  6209. };
  6210. DirectionalLight.prototype.computeTransformedPosition = function () {
  6211. if (this.parent && this.parent.getWorldMatrix) {
  6212. if (!this.transformedPosition) {
  6213. this.transformedPosition = BABYLON.Vector3.Zero();
  6214. }
  6215. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6216. return true;
  6217. }
  6218. return false;
  6219. };
  6220. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6221. if (this.parent && this.parent.getWorldMatrix) {
  6222. if (!this._transformedDirection) {
  6223. this._transformedDirection = BABYLON.Vector3.Zero();
  6224. }
  6225. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6226. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6227. return;
  6228. }
  6229. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6230. };
  6231. DirectionalLight.prototype._getWorldMatrix = function () {
  6232. if (!this._worldMatrix) {
  6233. this._worldMatrix = BABYLON.Matrix.Identity();
  6234. }
  6235. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6236. return this._worldMatrix;
  6237. };
  6238. return DirectionalLight;
  6239. })(BABYLON.Light);
  6240. BABYLON.DirectionalLight = DirectionalLight;
  6241. })(BABYLON || (BABYLON = {}));
  6242. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6243. (function (BABYLON) {
  6244. var ShadowGenerator = (function () {
  6245. function ShadowGenerator(mapSize, light) {
  6246. var _this = this;
  6247. // Members
  6248. this._filter = ShadowGenerator.FILTER_NONE;
  6249. this.blurScale = 2;
  6250. this._blurBoxOffset = 0;
  6251. this._bias = 0.00005;
  6252. this._darkness = 0;
  6253. this._transparencyShadow = false;
  6254. this._viewMatrix = BABYLON.Matrix.Zero();
  6255. this._projectionMatrix = BABYLON.Matrix.Zero();
  6256. this._transformMatrix = BABYLON.Matrix.Zero();
  6257. this._worldViewProjection = BABYLON.Matrix.Zero();
  6258. this._light = light;
  6259. this._scene = light.getScene();
  6260. this._mapSize = mapSize;
  6261. light._shadowGenerator = this;
  6262. // Render target
  6263. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6264. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6265. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6266. this._shadowMap.anisotropicFilteringLevel = 1;
  6267. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6268. this._shadowMap.renderParticles = false;
  6269. this._shadowMap.onAfterUnbind = function () {
  6270. if (!_this.useBlurVarianceShadowMap) {
  6271. return;
  6272. }
  6273. if (!_this._shadowMap2) {
  6274. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6275. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6276. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6277. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6278. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6279. _this._downSamplePostprocess.onApply = function (effect) {
  6280. effect.setTexture("textureSampler", _this._shadowMap);
  6281. };
  6282. _this.blurBoxOffset = 1;
  6283. }
  6284. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6285. };
  6286. // Custom render function
  6287. var renderSubMesh = function (subMesh) {
  6288. var mesh = subMesh.getRenderingMesh();
  6289. var scene = _this._scene;
  6290. var engine = scene.getEngine();
  6291. // Culling
  6292. engine.setState(subMesh.getMaterial().backFaceCulling);
  6293. // Managing instances
  6294. var batch = mesh._getInstancesRenderList(subMesh._id);
  6295. if (batch.mustReturn) {
  6296. return;
  6297. }
  6298. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6299. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6300. engine.enableEffect(_this._effect);
  6301. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6302. var material = subMesh.getMaterial();
  6303. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6304. // Alpha test
  6305. if (material && material.needAlphaTesting()) {
  6306. var alphaTexture = material.getAlphaTestTexture();
  6307. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6308. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6309. }
  6310. // Bones
  6311. if (mesh.useBones) {
  6312. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6313. }
  6314. // Draw
  6315. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6316. }
  6317. else {
  6318. // Need to reset refresh rate of the shadowMap
  6319. _this._shadowMap.resetRefreshCounter();
  6320. }
  6321. };
  6322. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6323. var index;
  6324. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6325. renderSubMesh(opaqueSubMeshes.data[index]);
  6326. }
  6327. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6328. renderSubMesh(alphaTestSubMeshes.data[index]);
  6329. }
  6330. if (_this._transparencyShadow) {
  6331. for (index = 0; index < transparentSubMeshes.length; index++) {
  6332. renderSubMesh(transparentSubMeshes.data[index]);
  6333. }
  6334. }
  6335. };
  6336. this._shadowMap.onClear = function (engine) {
  6337. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6338. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6339. }
  6340. else {
  6341. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6342. }
  6343. };
  6344. }
  6345. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6346. // Static
  6347. get: function () {
  6348. return ShadowGenerator._FILTER_NONE;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6354. get: function () {
  6355. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6361. get: function () {
  6362. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6363. },
  6364. enumerable: true,
  6365. configurable: true
  6366. });
  6367. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6368. get: function () {
  6369. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6370. },
  6371. enumerable: true,
  6372. configurable: true
  6373. });
  6374. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6375. get: function () {
  6376. return this._bias;
  6377. },
  6378. set: function (bias) {
  6379. this._bias = bias;
  6380. },
  6381. enumerable: true,
  6382. configurable: true
  6383. });
  6384. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6385. get: function () {
  6386. return this._blurBoxOffset;
  6387. },
  6388. set: function (value) {
  6389. var _this = this;
  6390. if (this._blurBoxOffset === value) {
  6391. return;
  6392. }
  6393. this._blurBoxOffset = value;
  6394. if (this._boxBlurPostprocess) {
  6395. this._boxBlurPostprocess.dispose();
  6396. }
  6397. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6398. this._boxBlurPostprocess.onApply = function (effect) {
  6399. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6400. };
  6401. },
  6402. enumerable: true,
  6403. configurable: true
  6404. });
  6405. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6406. get: function () {
  6407. return this._filter;
  6408. },
  6409. set: function (value) {
  6410. if (this._filter === value) {
  6411. return;
  6412. }
  6413. this._filter = value;
  6414. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6415. this._shadowMap.anisotropicFilteringLevel = 16;
  6416. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6417. }
  6418. else {
  6419. this._shadowMap.anisotropicFilteringLevel = 1;
  6420. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6421. }
  6422. },
  6423. enumerable: true,
  6424. configurable: true
  6425. });
  6426. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6427. get: function () {
  6428. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6429. },
  6430. set: function (value) {
  6431. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6432. },
  6433. enumerable: true,
  6434. configurable: true
  6435. });
  6436. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6437. get: function () {
  6438. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6439. },
  6440. set: function (value) {
  6441. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6442. },
  6443. enumerable: true,
  6444. configurable: true
  6445. });
  6446. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6447. get: function () {
  6448. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6449. },
  6450. set: function (value) {
  6451. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6452. },
  6453. enumerable: true,
  6454. configurable: true
  6455. });
  6456. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6457. var defines = [];
  6458. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6459. defines.push("#define VSM");
  6460. }
  6461. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6462. var mesh = subMesh.getMesh();
  6463. var material = subMesh.getMaterial();
  6464. // Alpha test
  6465. if (material && material.needAlphaTesting()) {
  6466. defines.push("#define ALPHATEST");
  6467. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6468. attribs.push(BABYLON.VertexBuffer.UVKind);
  6469. defines.push("#define UV1");
  6470. }
  6471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6473. defines.push("#define UV2");
  6474. }
  6475. }
  6476. // Bones
  6477. if (mesh.useBones) {
  6478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6480. defines.push("#define BONES");
  6481. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6482. }
  6483. // Instances
  6484. if (useInstances) {
  6485. defines.push("#define INSTANCES");
  6486. attribs.push("world0");
  6487. attribs.push("world1");
  6488. attribs.push("world2");
  6489. attribs.push("world3");
  6490. }
  6491. // Get correct effect
  6492. var join = defines.join("\n");
  6493. if (this._cachedDefines !== join) {
  6494. this._cachedDefines = join;
  6495. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6496. }
  6497. return this._effect.isReady();
  6498. };
  6499. ShadowGenerator.prototype.getShadowMap = function () {
  6500. return this._shadowMap;
  6501. };
  6502. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6503. if (this._shadowMap2) {
  6504. return this._shadowMap2;
  6505. }
  6506. return this._shadowMap;
  6507. };
  6508. ShadowGenerator.prototype.getLight = function () {
  6509. return this._light;
  6510. };
  6511. // Methods
  6512. ShadowGenerator.prototype.getTransformMatrix = function () {
  6513. var scene = this._scene;
  6514. if (this._currentRenderID === scene.getRenderId()) {
  6515. return this._transformMatrix;
  6516. }
  6517. this._currentRenderID = scene.getRenderId();
  6518. var lightPosition = this._light.position;
  6519. var lightDirection = this._light.direction;
  6520. if (this._light.computeTransformedPosition()) {
  6521. lightPosition = this._light.transformedPosition;
  6522. }
  6523. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6524. this._cachedPosition = lightPosition.clone();
  6525. this._cachedDirection = lightDirection.clone();
  6526. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6527. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6528. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6529. }
  6530. return this._transformMatrix;
  6531. };
  6532. ShadowGenerator.prototype.getDarkness = function () {
  6533. return this._darkness;
  6534. };
  6535. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6536. if (darkness >= 1.0)
  6537. this._darkness = 1.0;
  6538. else if (darkness <= 0.0)
  6539. this._darkness = 0.0;
  6540. else
  6541. this._darkness = darkness;
  6542. };
  6543. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6544. this._transparencyShadow = hasShadow;
  6545. };
  6546. ShadowGenerator.prototype._packHalf = function (depth) {
  6547. var scale = depth * 255.0;
  6548. var fract = scale - Math.floor(scale);
  6549. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6550. };
  6551. ShadowGenerator.prototype.dispose = function () {
  6552. this._shadowMap.dispose();
  6553. if (this._shadowMap2) {
  6554. this._shadowMap2.dispose();
  6555. }
  6556. if (this._downSamplePostprocess) {
  6557. this._downSamplePostprocess.dispose();
  6558. }
  6559. if (this._boxBlurPostprocess) {
  6560. this._boxBlurPostprocess.dispose();
  6561. }
  6562. };
  6563. ShadowGenerator._FILTER_NONE = 0;
  6564. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6565. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6566. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6567. return ShadowGenerator;
  6568. })();
  6569. BABYLON.ShadowGenerator = ShadowGenerator;
  6570. })(BABYLON || (BABYLON = {}));
  6571. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6572. var BABYLON;
  6573. (function (BABYLON) {
  6574. var HemisphericLight = (function (_super) {
  6575. __extends(HemisphericLight, _super);
  6576. function HemisphericLight(name, direction, scene) {
  6577. _super.call(this, name, scene);
  6578. this.direction = direction;
  6579. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6580. }
  6581. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6582. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6583. return this.direction;
  6584. };
  6585. HemisphericLight.prototype.getShadowGenerator = function () {
  6586. return null;
  6587. };
  6588. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6589. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6590. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6591. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6592. };
  6593. HemisphericLight.prototype._getWorldMatrix = function () {
  6594. if (!this._worldMatrix) {
  6595. this._worldMatrix = BABYLON.Matrix.Identity();
  6596. }
  6597. return this._worldMatrix;
  6598. };
  6599. return HemisphericLight;
  6600. })(BABYLON.Light);
  6601. BABYLON.HemisphericLight = HemisphericLight;
  6602. })(BABYLON || (BABYLON = {}));
  6603. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6604. (function (BABYLON) {
  6605. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6606. if (boxMin.x > sphereCenter.x + sphereRadius)
  6607. return false;
  6608. if (sphereCenter.x - sphereRadius > boxMax.x)
  6609. return false;
  6610. if (boxMin.y > sphereCenter.y + sphereRadius)
  6611. return false;
  6612. if (sphereCenter.y - sphereRadius > boxMax.y)
  6613. return false;
  6614. if (boxMin.z > sphereCenter.z + sphereRadius)
  6615. return false;
  6616. if (sphereCenter.z - sphereRadius > boxMax.z)
  6617. return false;
  6618. return true;
  6619. };
  6620. var getLowestRoot = function (a, b, c, maxR) {
  6621. var determinant = b * b - 4.0 * a * c;
  6622. var result = { root: 0, found: false };
  6623. if (determinant < 0)
  6624. return result;
  6625. var sqrtD = Math.sqrt(determinant);
  6626. var r1 = (-b - sqrtD) / (2.0 * a);
  6627. var r2 = (-b + sqrtD) / (2.0 * a);
  6628. if (r1 > r2) {
  6629. var temp = r2;
  6630. r2 = r1;
  6631. r1 = temp;
  6632. }
  6633. if (r1 > 0 && r1 < maxR) {
  6634. result.root = r1;
  6635. result.found = true;
  6636. return result;
  6637. }
  6638. if (r2 > 0 && r2 < maxR) {
  6639. result.root = r2;
  6640. result.found = true;
  6641. return result;
  6642. }
  6643. return result;
  6644. };
  6645. var Collider = (function () {
  6646. function Collider() {
  6647. this.radius = new BABYLON.Vector3(1, 1, 1);
  6648. this.retry = 0;
  6649. this.basePointWorld = BABYLON.Vector3.Zero();
  6650. this.velocityWorld = BABYLON.Vector3.Zero();
  6651. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6652. this._collisionPoint = BABYLON.Vector3.Zero();
  6653. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6654. this._tempVector = BABYLON.Vector3.Zero();
  6655. this._tempVector2 = BABYLON.Vector3.Zero();
  6656. this._tempVector3 = BABYLON.Vector3.Zero();
  6657. this._tempVector4 = BABYLON.Vector3.Zero();
  6658. this._edge = BABYLON.Vector3.Zero();
  6659. this._baseToVertex = BABYLON.Vector3.Zero();
  6660. this._destinationPoint = BABYLON.Vector3.Zero();
  6661. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6662. this._displacementVector = BABYLON.Vector3.Zero();
  6663. }
  6664. // Methods
  6665. Collider.prototype._initialize = function (source, dir, e) {
  6666. this.velocity = dir;
  6667. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6668. this.basePoint = source;
  6669. source.multiplyToRef(this.radius, this.basePointWorld);
  6670. dir.multiplyToRef(this.radius, this.velocityWorld);
  6671. this.velocityWorldLength = this.velocityWorld.length();
  6672. this.epsilon = e;
  6673. this.collisionFound = false;
  6674. };
  6675. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6676. pa.subtractToRef(point, this._tempVector);
  6677. pb.subtractToRef(point, this._tempVector2);
  6678. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6679. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6680. if (d < 0)
  6681. return false;
  6682. pc.subtractToRef(point, this._tempVector3);
  6683. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6684. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6685. if (d < 0)
  6686. return false;
  6687. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6688. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6689. return d >= 0;
  6690. };
  6691. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6692. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6693. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6694. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6695. return false;
  6696. }
  6697. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6698. return false;
  6699. return true;
  6700. };
  6701. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6702. var t0;
  6703. var embeddedInPlane = false;
  6704. if (!subMesh._trianglePlanes) {
  6705. subMesh._trianglePlanes = [];
  6706. }
  6707. if (!subMesh._trianglePlanes[faceIndex]) {
  6708. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6709. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6710. }
  6711. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6712. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6713. return;
  6714. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6715. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6716. if (normalDotVelocity == 0) {
  6717. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6718. return;
  6719. embeddedInPlane = true;
  6720. t0 = 0;
  6721. }
  6722. else {
  6723. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6724. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6725. if (t0 > t1) {
  6726. var temp = t1;
  6727. t1 = t0;
  6728. t0 = temp;
  6729. }
  6730. if (t0 > 1.0 || t1 < 0.0)
  6731. return;
  6732. if (t0 < 0)
  6733. t0 = 0;
  6734. if (t0 > 1.0)
  6735. t0 = 1.0;
  6736. }
  6737. this._collisionPoint.copyFromFloats(0, 0, 0);
  6738. var found = false;
  6739. var t = 1.0;
  6740. if (!embeddedInPlane) {
  6741. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6742. this.velocity.scaleToRef(t0, this._tempVector);
  6743. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6744. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6745. found = true;
  6746. t = t0;
  6747. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6748. }
  6749. }
  6750. if (!found) {
  6751. var velocitySquaredLength = this.velocity.lengthSquared();
  6752. var a = velocitySquaredLength;
  6753. this.basePoint.subtractToRef(p1, this._tempVector);
  6754. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6755. var c = this._tempVector.lengthSquared() - 1.0;
  6756. var lowestRoot = getLowestRoot(a, b, c, t);
  6757. if (lowestRoot.found) {
  6758. t = lowestRoot.root;
  6759. found = true;
  6760. this._collisionPoint.copyFrom(p1);
  6761. }
  6762. this.basePoint.subtractToRef(p2, this._tempVector);
  6763. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6764. c = this._tempVector.lengthSquared() - 1.0;
  6765. lowestRoot = getLowestRoot(a, b, c, t);
  6766. if (lowestRoot.found) {
  6767. t = lowestRoot.root;
  6768. found = true;
  6769. this._collisionPoint.copyFrom(p2);
  6770. }
  6771. this.basePoint.subtractToRef(p3, this._tempVector);
  6772. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6773. c = this._tempVector.lengthSquared() - 1.0;
  6774. lowestRoot = getLowestRoot(a, b, c, t);
  6775. if (lowestRoot.found) {
  6776. t = lowestRoot.root;
  6777. found = true;
  6778. this._collisionPoint.copyFrom(p3);
  6779. }
  6780. p2.subtractToRef(p1, this._edge);
  6781. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6782. var edgeSquaredLength = this._edge.lengthSquared();
  6783. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6784. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6785. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6786. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6787. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6788. lowestRoot = getLowestRoot(a, b, c, t);
  6789. if (lowestRoot.found) {
  6790. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6791. if (f >= 0.0 && f <= 1.0) {
  6792. t = lowestRoot.root;
  6793. found = true;
  6794. this._edge.scaleInPlace(f);
  6795. p1.addToRef(this._edge, this._collisionPoint);
  6796. }
  6797. }
  6798. p3.subtractToRef(p2, this._edge);
  6799. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6800. edgeSquaredLength = this._edge.lengthSquared();
  6801. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6802. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6803. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6804. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6805. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6806. lowestRoot = getLowestRoot(a, b, c, t);
  6807. if (lowestRoot.found) {
  6808. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6809. if (f >= 0.0 && f <= 1.0) {
  6810. t = lowestRoot.root;
  6811. found = true;
  6812. this._edge.scaleInPlace(f);
  6813. p2.addToRef(this._edge, this._collisionPoint);
  6814. }
  6815. }
  6816. p1.subtractToRef(p3, this._edge);
  6817. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6818. edgeSquaredLength = this._edge.lengthSquared();
  6819. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6820. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6821. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6822. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6823. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6824. lowestRoot = getLowestRoot(a, b, c, t);
  6825. if (lowestRoot.found) {
  6826. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6827. if (f >= 0.0 && f <= 1.0) {
  6828. t = lowestRoot.root;
  6829. found = true;
  6830. this._edge.scaleInPlace(f);
  6831. p3.addToRef(this._edge, this._collisionPoint);
  6832. }
  6833. }
  6834. }
  6835. if (found) {
  6836. var distToCollision = t * this.velocity.length();
  6837. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6838. if (!this.intersectionPoint) {
  6839. this.intersectionPoint = this._collisionPoint.clone();
  6840. }
  6841. else {
  6842. this.intersectionPoint.copyFrom(this._collisionPoint);
  6843. }
  6844. this.nearestDistance = distToCollision;
  6845. this.collisionFound = true;
  6846. this.collidedMesh = subMesh.getMesh();
  6847. }
  6848. }
  6849. };
  6850. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6851. for (var i = indexStart; i < indexEnd; i += 3) {
  6852. var p1 = pts[indices[i] - decal];
  6853. var p2 = pts[indices[i + 1] - decal];
  6854. var p3 = pts[indices[i + 2] - decal];
  6855. this._testTriangle(i, subMesh, p3, p2, p1);
  6856. }
  6857. };
  6858. Collider.prototype._getResponse = function (pos, vel) {
  6859. pos.addToRef(vel, this._destinationPoint);
  6860. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6861. this.basePoint.addToRef(vel, pos);
  6862. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6863. this._slidePlaneNormal.normalize();
  6864. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6865. pos.addInPlace(this._displacementVector);
  6866. this.intersectionPoint.addInPlace(this._displacementVector);
  6867. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6868. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6869. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6870. };
  6871. return Collider;
  6872. })();
  6873. BABYLON.Collider = Collider;
  6874. })(BABYLON || (BABYLON = {}));
  6875. //# sourceMappingURL=babylon.collider.js.map
  6876. var BABYLON;
  6877. (function (BABYLON) {
  6878. var Camera = (function (_super) {
  6879. __extends(Camera, _super);
  6880. function Camera(name, position, scene) {
  6881. _super.call(this, name, scene);
  6882. this.position = position;
  6883. // Members
  6884. this.upVector = BABYLON.Vector3.Up();
  6885. this.orthoLeft = null;
  6886. this.orthoRight = null;
  6887. this.orthoBottom = null;
  6888. this.orthoTop = null;
  6889. this.fov = 0.8;
  6890. this.minZ = 1.0;
  6891. this.maxZ = 10000.0;
  6892. this.inertia = 0.9;
  6893. this.mode = Camera.PERSPECTIVE_CAMERA;
  6894. this.isIntermediate = false;
  6895. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6896. this.subCameras = [];
  6897. this.layerMask = 0xFFFFFFFF;
  6898. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6899. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6900. this._projectionMatrix = new BABYLON.Matrix();
  6901. this._postProcesses = new Array();
  6902. this._postProcessesTakenIndices = [];
  6903. this._activeMeshes = new BABYLON.SmartArray(256);
  6904. this._globalPosition = BABYLON.Vector3.Zero();
  6905. scene.addCamera(this);
  6906. if (!scene.activeCamera) {
  6907. scene.activeCamera = this;
  6908. }
  6909. }
  6910. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6911. get: function () {
  6912. return Camera._PERSPECTIVE_CAMERA;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6918. get: function () {
  6919. return Camera._ORTHOGRAPHIC_CAMERA;
  6920. },
  6921. enumerable: true,
  6922. configurable: true
  6923. });
  6924. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6925. get: function () {
  6926. return Camera._FOVMODE_VERTICAL_FIXED;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6932. get: function () {
  6933. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(Camera.prototype, "globalPosition", {
  6939. get: function () {
  6940. return this._globalPosition;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Camera.prototype.getActiveMeshes = function () {
  6946. return this._activeMeshes;
  6947. };
  6948. Camera.prototype.isActiveMesh = function (mesh) {
  6949. return (this._activeMeshes.indexOf(mesh) !== -1);
  6950. };
  6951. //Cache
  6952. Camera.prototype._initCache = function () {
  6953. _super.prototype._initCache.call(this);
  6954. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6955. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6956. this._cache.mode = undefined;
  6957. this._cache.minZ = undefined;
  6958. this._cache.maxZ = undefined;
  6959. this._cache.fov = undefined;
  6960. this._cache.aspectRatio = undefined;
  6961. this._cache.orthoLeft = undefined;
  6962. this._cache.orthoRight = undefined;
  6963. this._cache.orthoBottom = undefined;
  6964. this._cache.orthoTop = undefined;
  6965. this._cache.renderWidth = undefined;
  6966. this._cache.renderHeight = undefined;
  6967. };
  6968. Camera.prototype._updateCache = function (ignoreParentClass) {
  6969. if (!ignoreParentClass) {
  6970. _super.prototype._updateCache.call(this);
  6971. }
  6972. var engine = this.getEngine();
  6973. this._cache.position.copyFrom(this.position);
  6974. this._cache.upVector.copyFrom(this.upVector);
  6975. this._cache.mode = this.mode;
  6976. this._cache.minZ = this.minZ;
  6977. this._cache.maxZ = this.maxZ;
  6978. this._cache.fov = this.fov;
  6979. this._cache.aspectRatio = engine.getAspectRatio(this);
  6980. this._cache.orthoLeft = this.orthoLeft;
  6981. this._cache.orthoRight = this.orthoRight;
  6982. this._cache.orthoBottom = this.orthoBottom;
  6983. this._cache.orthoTop = this.orthoTop;
  6984. this._cache.renderWidth = engine.getRenderWidth();
  6985. this._cache.renderHeight = engine.getRenderHeight();
  6986. };
  6987. Camera.prototype._updateFromScene = function () {
  6988. this.updateCache();
  6989. this._update();
  6990. };
  6991. // Synchronized
  6992. Camera.prototype._isSynchronized = function () {
  6993. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6994. };
  6995. Camera.prototype._isSynchronizedViewMatrix = function () {
  6996. if (!_super.prototype._isSynchronized.call(this))
  6997. return false;
  6998. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6999. };
  7000. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7001. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7002. if (!check) {
  7003. return false;
  7004. }
  7005. var engine = this.getEngine();
  7006. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7007. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7008. }
  7009. else {
  7010. 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();
  7011. }
  7012. return check;
  7013. };
  7014. // Controls
  7015. Camera.prototype.attachControl = function (element) {
  7016. };
  7017. Camera.prototype.detachControl = function (element) {
  7018. };
  7019. Camera.prototype._update = function () {
  7020. };
  7021. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7022. if (insertAt === void 0) { insertAt = null; }
  7023. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7024. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7025. return 0;
  7026. }
  7027. if (insertAt == null || insertAt < 0) {
  7028. this._postProcesses.push(postProcess);
  7029. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7030. return this._postProcesses.length - 1;
  7031. }
  7032. var add = 0;
  7033. if (this._postProcesses[insertAt]) {
  7034. var start = this._postProcesses.length - 1;
  7035. for (var i = start; i >= insertAt + 1; --i) {
  7036. this._postProcesses[i + 1] = this._postProcesses[i];
  7037. }
  7038. add = 1;
  7039. }
  7040. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7041. if (this._postProcessesTakenIndices[i] < insertAt) {
  7042. continue;
  7043. }
  7044. start = this._postProcessesTakenIndices.length - 1;
  7045. for (var j = start; j >= i; --j) {
  7046. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7047. }
  7048. this._postProcessesTakenIndices[i] = insertAt;
  7049. break;
  7050. }
  7051. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7052. this._postProcessesTakenIndices.push(insertAt);
  7053. }
  7054. var result = insertAt + add;
  7055. this._postProcesses[result] = postProcess;
  7056. return result;
  7057. };
  7058. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7059. if (atIndices === void 0) { atIndices = null; }
  7060. var result = [];
  7061. if (!atIndices) {
  7062. var length = this._postProcesses.length;
  7063. for (var i = 0; i < length; i++) {
  7064. if (this._postProcesses[i] !== postProcess) {
  7065. continue;
  7066. }
  7067. delete this._postProcesses[i];
  7068. var index = this._postProcessesTakenIndices.indexOf(i);
  7069. this._postProcessesTakenIndices.splice(index, 1);
  7070. }
  7071. }
  7072. else {
  7073. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7074. for (i = 0; i < atIndices.length; i++) {
  7075. var foundPostProcess = this._postProcesses[atIndices[i]];
  7076. if (foundPostProcess !== postProcess) {
  7077. result.push(i);
  7078. continue;
  7079. }
  7080. delete this._postProcesses[atIndices[i]];
  7081. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7082. this._postProcessesTakenIndices.splice(index, 1);
  7083. }
  7084. }
  7085. return result;
  7086. };
  7087. Camera.prototype.getWorldMatrix = function () {
  7088. if (!this._worldMatrix) {
  7089. this._worldMatrix = BABYLON.Matrix.Identity();
  7090. }
  7091. var viewMatrix = this.getViewMatrix();
  7092. viewMatrix.invertToRef(this._worldMatrix);
  7093. return this._worldMatrix;
  7094. };
  7095. Camera.prototype._getViewMatrix = function () {
  7096. return BABYLON.Matrix.Identity();
  7097. };
  7098. Camera.prototype.getViewMatrix = function () {
  7099. this._computedViewMatrix = this._computeViewMatrix();
  7100. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7101. this._globalPosition.copyFrom(this.position);
  7102. return this._computedViewMatrix;
  7103. }
  7104. if (!this._worldMatrix) {
  7105. this._worldMatrix = BABYLON.Matrix.Identity();
  7106. }
  7107. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7108. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7109. this._computedViewMatrix.invert();
  7110. this._currentRenderId = this.getScene().getRenderId();
  7111. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7112. return this._computedViewMatrix;
  7113. };
  7114. Camera.prototype._computeViewMatrix = function (force) {
  7115. if (!force && this._isSynchronizedViewMatrix()) {
  7116. return this._computedViewMatrix;
  7117. }
  7118. this._computedViewMatrix = this._getViewMatrix();
  7119. if (!this.parent || !this.parent.getWorldMatrix) {
  7120. this._currentRenderId = this.getScene().getRenderId();
  7121. }
  7122. return this._computedViewMatrix;
  7123. };
  7124. Camera.prototype.getProjectionMatrix = function (force) {
  7125. if (!force && this._isSynchronizedProjectionMatrix()) {
  7126. return this._projectionMatrix;
  7127. }
  7128. var engine = this.getEngine();
  7129. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7130. if (this.minZ <= 0) {
  7131. this.minZ = 0.1;
  7132. }
  7133. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7134. return this._projectionMatrix;
  7135. }
  7136. var halfWidth = engine.getRenderWidth() / 2.0;
  7137. var halfHeight = engine.getRenderHeight() / 2.0;
  7138. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7139. return this._projectionMatrix;
  7140. };
  7141. Camera.prototype.dispose = function () {
  7142. // Remove from scene
  7143. this.getScene().removeCamera(this);
  7144. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7145. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7146. }
  7147. };
  7148. // Statics
  7149. Camera._PERSPECTIVE_CAMERA = 0;
  7150. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7151. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7152. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7153. return Camera;
  7154. })(BABYLON.Node);
  7155. BABYLON.Camera = Camera;
  7156. })(BABYLON || (BABYLON = {}));
  7157. //# sourceMappingURL=babylon.camera.js.map
  7158. var BABYLON;
  7159. (function (BABYLON) {
  7160. var TargetCamera = (function (_super) {
  7161. __extends(TargetCamera, _super);
  7162. function TargetCamera(name, position, scene) {
  7163. _super.call(this, name, position, scene);
  7164. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7165. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7166. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7167. this.speed = 2.0;
  7168. this.noRotationConstraint = false;
  7169. this.lockedTarget = null;
  7170. this._currentTarget = BABYLON.Vector3.Zero();
  7171. this._viewMatrix = BABYLON.Matrix.Zero();
  7172. this._camMatrix = BABYLON.Matrix.Zero();
  7173. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7174. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7175. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7176. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7177. this._lookAtTemp = BABYLON.Matrix.Zero();
  7178. this._tempMatrix = BABYLON.Matrix.Zero();
  7179. }
  7180. TargetCamera.prototype._getLockedTargetPosition = function () {
  7181. if (!this.lockedTarget) {
  7182. return null;
  7183. }
  7184. return this.lockedTarget.position || this.lockedTarget;
  7185. };
  7186. // Cache
  7187. TargetCamera.prototype._initCache = function () {
  7188. _super.prototype._initCache.call(this);
  7189. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7190. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7191. };
  7192. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7193. if (!ignoreParentClass) {
  7194. _super.prototype._updateCache.call(this);
  7195. }
  7196. var lockedTargetPosition = this._getLockedTargetPosition();
  7197. if (!lockedTargetPosition) {
  7198. this._cache.lockedTarget = null;
  7199. }
  7200. else {
  7201. if (!this._cache.lockedTarget) {
  7202. this._cache.lockedTarget = lockedTargetPosition.clone();
  7203. }
  7204. else {
  7205. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7206. }
  7207. }
  7208. this._cache.rotation.copyFrom(this.rotation);
  7209. };
  7210. // Synchronized
  7211. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7212. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7213. return false;
  7214. }
  7215. var lockedTargetPosition = this._getLockedTargetPosition();
  7216. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7217. };
  7218. // Methods
  7219. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7220. var engine = this.getEngine();
  7221. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7222. };
  7223. // Target
  7224. TargetCamera.prototype.setTarget = function (target) {
  7225. this.upVector.normalize();
  7226. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7227. this._camMatrix.invert();
  7228. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7229. var vDir = target.subtract(this.position);
  7230. if (vDir.x >= 0.0) {
  7231. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7232. }
  7233. else {
  7234. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7235. }
  7236. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7237. if (isNaN(this.rotation.x)) {
  7238. this.rotation.x = 0;
  7239. }
  7240. if (isNaN(this.rotation.y)) {
  7241. this.rotation.y = 0;
  7242. }
  7243. if (isNaN(this.rotation.z)) {
  7244. this.rotation.z = 0;
  7245. }
  7246. };
  7247. TargetCamera.prototype.getTarget = function () {
  7248. return this._currentTarget;
  7249. };
  7250. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7251. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7252. };
  7253. TargetCamera.prototype._updatePosition = function () {
  7254. this.position.addInPlace(this.cameraDirection);
  7255. };
  7256. TargetCamera.prototype._update = function () {
  7257. var needToMove = this._decideIfNeedsToMove();
  7258. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7259. // Move
  7260. if (needToMove) {
  7261. this._updatePosition();
  7262. }
  7263. // Rotate
  7264. if (needToRotate) {
  7265. this.rotation.x += this.cameraRotation.x;
  7266. this.rotation.y += this.cameraRotation.y;
  7267. if (!this.noRotationConstraint) {
  7268. var limit = (Math.PI / 2) * 0.95;
  7269. if (this.rotation.x > limit)
  7270. this.rotation.x = limit;
  7271. if (this.rotation.x < -limit)
  7272. this.rotation.x = -limit;
  7273. }
  7274. }
  7275. // Inertia
  7276. if (needToMove) {
  7277. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7278. this.cameraDirection.x = 0;
  7279. }
  7280. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7281. this.cameraDirection.y = 0;
  7282. }
  7283. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7284. this.cameraDirection.z = 0;
  7285. }
  7286. this.cameraDirection.scaleInPlace(this.inertia);
  7287. }
  7288. if (needToRotate) {
  7289. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7290. this.cameraRotation.x = 0;
  7291. }
  7292. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7293. this.cameraRotation.y = 0;
  7294. }
  7295. this.cameraRotation.scaleInPlace(this.inertia);
  7296. }
  7297. };
  7298. TargetCamera.prototype._getViewMatrix = function () {
  7299. if (!this.lockedTarget) {
  7300. // Compute
  7301. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7302. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7303. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7304. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7305. this._lookAtTemp.invert();
  7306. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7307. }
  7308. else {
  7309. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7310. }
  7311. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7312. // Computing target and final matrix
  7313. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7314. }
  7315. else {
  7316. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7317. }
  7318. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7319. return this._viewMatrix;
  7320. };
  7321. return TargetCamera;
  7322. })(BABYLON.Camera);
  7323. BABYLON.TargetCamera = TargetCamera;
  7324. })(BABYLON || (BABYLON = {}));
  7325. //# sourceMappingURL=babylon.targetCamera.js.map
  7326. var BABYLON;
  7327. (function (BABYLON) {
  7328. var FollowCamera = (function (_super) {
  7329. __extends(FollowCamera, _super);
  7330. function FollowCamera(name, position, scene) {
  7331. _super.call(this, name, position, scene);
  7332. this.radius = 12;
  7333. this.rotationOffset = 0;
  7334. this.heightOffset = 4;
  7335. this.cameraAcceleration = 0.05;
  7336. this.maxCameraSpeed = 20;
  7337. }
  7338. FollowCamera.prototype.getRadians = function (degrees) {
  7339. return degrees * Math.PI / 180;
  7340. };
  7341. FollowCamera.prototype.follow = function (cameraTarget) {
  7342. if (!cameraTarget)
  7343. return;
  7344. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7345. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7346. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7347. var dx = targetX - this.position.x;
  7348. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7349. var dz = (targetZ) - this.position.z;
  7350. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7351. var vy = dy * this.cameraAcceleration;
  7352. var vz = dz * this.cameraAcceleration * 2;
  7353. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7354. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7355. }
  7356. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7357. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7358. }
  7359. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7360. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7361. }
  7362. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7363. this.setTarget(cameraTarget.position);
  7364. };
  7365. FollowCamera.prototype._update = function () {
  7366. _super.prototype._update.call(this);
  7367. this.follow(this.target);
  7368. };
  7369. return FollowCamera;
  7370. })(BABYLON.TargetCamera);
  7371. BABYLON.FollowCamera = FollowCamera;
  7372. })(BABYLON || (BABYLON = {}));
  7373. //# sourceMappingURL=babylon.followCamera.js.map
  7374. var BABYLON;
  7375. (function (BABYLON) {
  7376. var FreeCamera = (function (_super) {
  7377. __extends(FreeCamera, _super);
  7378. function FreeCamera(name, position, scene) {
  7379. _super.call(this, name, position, scene);
  7380. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7381. this.keysUp = [38];
  7382. this.keysDown = [40];
  7383. this.keysLeft = [37];
  7384. this.keysRight = [39];
  7385. this.checkCollisions = false;
  7386. this.applyGravity = false;
  7387. this.angularSensibility = 2000.0;
  7388. this._keys = [];
  7389. this._collider = new BABYLON.Collider();
  7390. this._needMoveForGravity = true;
  7391. this._oldPosition = BABYLON.Vector3.Zero();
  7392. this._diffPosition = BABYLON.Vector3.Zero();
  7393. this._newPosition = BABYLON.Vector3.Zero();
  7394. }
  7395. // Controls
  7396. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7397. var _this = this;
  7398. var previousPosition;
  7399. var engine = this.getEngine();
  7400. if (this._attachedElement) {
  7401. return;
  7402. }
  7403. this._attachedElement = element;
  7404. if (this._onMouseDown === undefined) {
  7405. this._onMouseDown = function (evt) {
  7406. previousPosition = {
  7407. x: evt.clientX,
  7408. y: evt.clientY
  7409. };
  7410. if (!noPreventDefault) {
  7411. evt.preventDefault();
  7412. }
  7413. };
  7414. this._onMouseUp = function (evt) {
  7415. previousPosition = null;
  7416. if (!noPreventDefault) {
  7417. evt.preventDefault();
  7418. }
  7419. };
  7420. this._onMouseOut = function (evt) {
  7421. previousPosition = null;
  7422. _this._keys = [];
  7423. if (!noPreventDefault) {
  7424. evt.preventDefault();
  7425. }
  7426. };
  7427. this._onMouseMove = function (evt) {
  7428. if (!previousPosition && !engine.isPointerLock) {
  7429. return;
  7430. }
  7431. var offsetX;
  7432. var offsetY;
  7433. if (!engine.isPointerLock) {
  7434. offsetX = evt.clientX - previousPosition.x;
  7435. offsetY = evt.clientY - previousPosition.y;
  7436. }
  7437. else {
  7438. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7439. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7440. }
  7441. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7442. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7443. previousPosition = {
  7444. x: evt.clientX,
  7445. y: evt.clientY
  7446. };
  7447. if (!noPreventDefault) {
  7448. evt.preventDefault();
  7449. }
  7450. };
  7451. this._onKeyDown = function (evt) {
  7452. 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) {
  7453. var index = _this._keys.indexOf(evt.keyCode);
  7454. if (index === -1) {
  7455. _this._keys.push(evt.keyCode);
  7456. }
  7457. if (!noPreventDefault) {
  7458. evt.preventDefault();
  7459. }
  7460. }
  7461. };
  7462. this._onKeyUp = function (evt) {
  7463. 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) {
  7464. var index = _this._keys.indexOf(evt.keyCode);
  7465. if (index >= 0) {
  7466. _this._keys.splice(index, 1);
  7467. }
  7468. if (!noPreventDefault) {
  7469. evt.preventDefault();
  7470. }
  7471. }
  7472. };
  7473. this._onLostFocus = function () {
  7474. _this._keys = [];
  7475. };
  7476. this._reset = function () {
  7477. _this._keys = [];
  7478. previousPosition = null;
  7479. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7480. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7481. };
  7482. }
  7483. element.addEventListener("mousedown", this._onMouseDown, false);
  7484. element.addEventListener("mouseup", this._onMouseUp, false);
  7485. element.addEventListener("mouseout", this._onMouseOut, false);
  7486. element.addEventListener("mousemove", this._onMouseMove, false);
  7487. BABYLON.Tools.RegisterTopRootEvents([
  7488. { name: "keydown", handler: this._onKeyDown },
  7489. { name: "keyup", handler: this._onKeyUp },
  7490. { name: "blur", handler: this._onLostFocus }
  7491. ]);
  7492. };
  7493. FreeCamera.prototype.detachControl = function (element) {
  7494. if (this._attachedElement != element) {
  7495. return;
  7496. }
  7497. element.removeEventListener("mousedown", this._onMouseDown);
  7498. element.removeEventListener("mouseup", this._onMouseUp);
  7499. element.removeEventListener("mouseout", this._onMouseOut);
  7500. element.removeEventListener("mousemove", this._onMouseMove);
  7501. BABYLON.Tools.UnregisterTopRootEvents([
  7502. { name: "keydown", handler: this._onKeyDown },
  7503. { name: "keyup", handler: this._onKeyUp },
  7504. { name: "blur", handler: this._onLostFocus }
  7505. ]);
  7506. this._attachedElement = null;
  7507. if (this._reset) {
  7508. this._reset();
  7509. }
  7510. };
  7511. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7512. var globalPosition;
  7513. if (this.parent) {
  7514. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7515. }
  7516. else {
  7517. globalPosition = this.position;
  7518. }
  7519. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7520. this._collider.radius = this.ellipsoid;
  7521. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7522. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7523. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7524. this.position.addInPlace(this._diffPosition);
  7525. if (this.onCollide) {
  7526. this.onCollide(this._collider.collidedMesh);
  7527. }
  7528. }
  7529. };
  7530. FreeCamera.prototype._checkInputs = function () {
  7531. if (!this._localDirection) {
  7532. this._localDirection = BABYLON.Vector3.Zero();
  7533. this._transformedDirection = BABYLON.Vector3.Zero();
  7534. }
  7535. for (var index = 0; index < this._keys.length; index++) {
  7536. var keyCode = this._keys[index];
  7537. var speed = this._computeLocalCameraSpeed();
  7538. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7539. this._localDirection.copyFromFloats(-speed, 0, 0);
  7540. }
  7541. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7542. this._localDirection.copyFromFloats(0, 0, speed);
  7543. }
  7544. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7545. this._localDirection.copyFromFloats(speed, 0, 0);
  7546. }
  7547. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7548. this._localDirection.copyFromFloats(0, 0, -speed);
  7549. }
  7550. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7551. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7552. this.cameraDirection.addInPlace(this._transformedDirection);
  7553. }
  7554. };
  7555. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7556. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7557. };
  7558. FreeCamera.prototype._updatePosition = function () {
  7559. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7560. this._collideWithWorld(this.cameraDirection);
  7561. if (this.applyGravity) {
  7562. var oldPosition = this.position;
  7563. this._collideWithWorld(this.getScene().gravity);
  7564. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7565. }
  7566. }
  7567. else {
  7568. this.position.addInPlace(this.cameraDirection);
  7569. }
  7570. };
  7571. FreeCamera.prototype._update = function () {
  7572. this._checkInputs();
  7573. _super.prototype._update.call(this);
  7574. };
  7575. return FreeCamera;
  7576. })(BABYLON.TargetCamera);
  7577. BABYLON.FreeCamera = FreeCamera;
  7578. })(BABYLON || (BABYLON = {}));
  7579. //# sourceMappingURL=babylon.freeCamera.js.map
  7580. var BABYLON;
  7581. (function (BABYLON) {
  7582. // We're mainly based on the logic defined into the FreeCamera code
  7583. var TouchCamera = (function (_super) {
  7584. __extends(TouchCamera, _super);
  7585. function TouchCamera(name, position, scene) {
  7586. _super.call(this, name, position, scene);
  7587. this._offsetX = null;
  7588. this._offsetY = null;
  7589. this._pointerCount = 0;
  7590. this._pointerPressed = [];
  7591. this.angularSensibility = 200000.0;
  7592. this.moveSensibility = 500.0;
  7593. }
  7594. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7595. var _this = this;
  7596. var previousPosition;
  7597. if (this._attachedCanvas) {
  7598. return;
  7599. }
  7600. this._attachedCanvas = canvas;
  7601. if (this._onPointerDown === undefined) {
  7602. this._onPointerDown = function (evt) {
  7603. if (!noPreventDefault) {
  7604. evt.preventDefault();
  7605. }
  7606. _this._pointerPressed.push(evt.pointerId);
  7607. if (_this._pointerPressed.length !== 1) {
  7608. return;
  7609. }
  7610. previousPosition = {
  7611. x: evt.clientX,
  7612. y: evt.clientY
  7613. };
  7614. };
  7615. this._onPointerUp = function (evt) {
  7616. if (!noPreventDefault) {
  7617. evt.preventDefault();
  7618. }
  7619. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7620. if (index === -1) {
  7621. return;
  7622. }
  7623. _this._pointerPressed.splice(index, 1);
  7624. if (index != 0) {
  7625. return;
  7626. }
  7627. previousPosition = null;
  7628. _this._offsetX = null;
  7629. _this._offsetY = null;
  7630. };
  7631. this._onPointerMove = function (evt) {
  7632. if (!noPreventDefault) {
  7633. evt.preventDefault();
  7634. }
  7635. if (!previousPosition) {
  7636. return;
  7637. }
  7638. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7639. if (index != 0) {
  7640. return;
  7641. }
  7642. _this._offsetX = evt.clientX - previousPosition.x;
  7643. _this._offsetY = -(evt.clientY - previousPosition.y);
  7644. };
  7645. this._onLostFocus = function () {
  7646. _this._offsetX = null;
  7647. _this._offsetY = null;
  7648. };
  7649. }
  7650. canvas.addEventListener("pointerdown", this._onPointerDown);
  7651. canvas.addEventListener("pointerup", this._onPointerUp);
  7652. canvas.addEventListener("pointerout", this._onPointerUp);
  7653. canvas.addEventListener("pointermove", this._onPointerMove);
  7654. BABYLON.Tools.RegisterTopRootEvents([
  7655. { name: "blur", handler: this._onLostFocus }
  7656. ]);
  7657. };
  7658. TouchCamera.prototype.detachControl = function (canvas) {
  7659. if (this._attachedCanvas != canvas) {
  7660. return;
  7661. }
  7662. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7663. canvas.removeEventListener("pointerup", this._onPointerUp);
  7664. canvas.removeEventListener("pointerout", this._onPointerUp);
  7665. canvas.removeEventListener("pointermove", this._onPointerMove);
  7666. BABYLON.Tools.UnregisterTopRootEvents([
  7667. { name: "blur", handler: this._onLostFocus }
  7668. ]);
  7669. this._attachedCanvas = null;
  7670. };
  7671. TouchCamera.prototype._checkInputs = function () {
  7672. if (!this._offsetX) {
  7673. return;
  7674. }
  7675. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7676. if (this._pointerPressed.length > 1) {
  7677. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7678. }
  7679. else {
  7680. var speed = this._computeLocalCameraSpeed();
  7681. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7682. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7683. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7684. }
  7685. };
  7686. return TouchCamera;
  7687. })(BABYLON.FreeCamera);
  7688. BABYLON.TouchCamera = TouchCamera;
  7689. })(BABYLON || (BABYLON = {}));
  7690. //# sourceMappingURL=babylon.touchCamera.js.map
  7691. var BABYLON;
  7692. (function (BABYLON) {
  7693. // We're mainly based on the logic defined into the FreeCamera code
  7694. var DeviceOrientationCamera = (function (_super) {
  7695. __extends(DeviceOrientationCamera, _super);
  7696. function DeviceOrientationCamera(name, position, scene) {
  7697. var _this = this;
  7698. _super.call(this, name, position, scene);
  7699. this._offsetX = null;
  7700. this._offsetY = null;
  7701. this._orientationGamma = 0;
  7702. this._orientationBeta = 0;
  7703. this._initialOrientationGamma = 0;
  7704. this._initialOrientationBeta = 0;
  7705. this.angularSensibility = 10000.0;
  7706. this.moveSensibility = 50.0;
  7707. window.addEventListener("resize", function () {
  7708. _this._initialOrientationGamma = null;
  7709. }, false);
  7710. }
  7711. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7712. var _this = this;
  7713. if (this._attachedCanvas) {
  7714. return;
  7715. }
  7716. this._attachedCanvas = canvas;
  7717. if (!this._orientationChanged) {
  7718. this._orientationChanged = function (evt) {
  7719. if (!_this._initialOrientationGamma) {
  7720. _this._initialOrientationGamma = evt.gamma;
  7721. _this._initialOrientationBeta = evt.beta;
  7722. }
  7723. _this._orientationGamma = evt.gamma;
  7724. _this._orientationBeta = evt.beta;
  7725. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7726. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7727. };
  7728. }
  7729. window.addEventListener("deviceorientation", this._orientationChanged);
  7730. };
  7731. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7732. if (this._attachedCanvas != canvas) {
  7733. return;
  7734. }
  7735. window.removeEventListener("deviceorientation", this._orientationChanged);
  7736. this._attachedCanvas = null;
  7737. this._orientationGamma = 0;
  7738. this._orientationBeta = 0;
  7739. this._initialOrientationGamma = 0;
  7740. this._initialOrientationBeta = 0;
  7741. };
  7742. DeviceOrientationCamera.prototype._checkInputs = function () {
  7743. if (!this._offsetX) {
  7744. return;
  7745. }
  7746. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7747. var speed = this._computeLocalCameraSpeed();
  7748. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7749. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7750. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7751. };
  7752. return DeviceOrientationCamera;
  7753. })(BABYLON.FreeCamera);
  7754. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7755. })(BABYLON || (BABYLON = {}));
  7756. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7757. var BABYLON;
  7758. (function (BABYLON) {
  7759. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7760. var ArcRotateCamera = (function (_super) {
  7761. __extends(ArcRotateCamera, _super);
  7762. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7763. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7764. this.alpha = alpha;
  7765. this.beta = beta;
  7766. this.radius = radius;
  7767. this.target = target;
  7768. this.inertialAlphaOffset = 0;
  7769. this.inertialBetaOffset = 0;
  7770. this.inertialRadiusOffset = 0;
  7771. this.lowerAlphaLimit = null;
  7772. this.upperAlphaLimit = null;
  7773. this.lowerBetaLimit = 0.01;
  7774. this.upperBetaLimit = Math.PI;
  7775. this.lowerRadiusLimit = null;
  7776. this.upperRadiusLimit = null;
  7777. this.angularSensibility = 1000.0;
  7778. this.wheelPrecision = 3.0;
  7779. this.pinchPrecision = 2.0;
  7780. this.keysUp = [38];
  7781. this.keysDown = [40];
  7782. this.keysLeft = [37];
  7783. this.keysRight = [39];
  7784. this.zoomOnFactor = 1;
  7785. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7786. this._keys = [];
  7787. this._viewMatrix = new BABYLON.Matrix();
  7788. this.checkCollisions = false;
  7789. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7790. this._collider = new BABYLON.Collider();
  7791. this._previousPosition = BABYLON.Vector3.Zero();
  7792. this._collisionVelocity = BABYLON.Vector3.Zero();
  7793. this._newPosition = BABYLON.Vector3.Zero();
  7794. if (!this.target) {
  7795. this.target = BABYLON.Vector3.Zero();
  7796. }
  7797. this.getViewMatrix();
  7798. }
  7799. ArcRotateCamera.prototype._getTargetPosition = function () {
  7800. return this.target.position || this.target;
  7801. };
  7802. // Cache
  7803. ArcRotateCamera.prototype._initCache = function () {
  7804. _super.prototype._initCache.call(this);
  7805. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7806. this._cache.alpha = undefined;
  7807. this._cache.beta = undefined;
  7808. this._cache.radius = undefined;
  7809. this._cache.targetScreenOffset = undefined;
  7810. };
  7811. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7812. if (!ignoreParentClass) {
  7813. _super.prototype._updateCache.call(this);
  7814. }
  7815. this._cache.target.copyFrom(this._getTargetPosition());
  7816. this._cache.alpha = this.alpha;
  7817. this._cache.beta = this.beta;
  7818. this._cache.radius = this.radius;
  7819. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7820. };
  7821. // Synchronized
  7822. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7823. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7824. return false;
  7825. 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);
  7826. };
  7827. // Methods
  7828. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7829. var _this = this;
  7830. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7831. var previousPinchDistance = 0;
  7832. var pointers = new BABYLON.SmartCollection();
  7833. if (this._attachedElement) {
  7834. return;
  7835. }
  7836. this._attachedElement = element;
  7837. var engine = this.getEngine();
  7838. if (this._onPointerDown === undefined) {
  7839. this._onPointerDown = function (evt) {
  7840. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7841. cacheSoloPointer = pointers.item(evt.pointerId);
  7842. if (!noPreventDefault) {
  7843. evt.preventDefault();
  7844. }
  7845. };
  7846. this._onPointerUp = function (evt) {
  7847. cacheSoloPointer = null;
  7848. previousPinchDistance = 0;
  7849. pointers.remove(evt.pointerId);
  7850. if (!noPreventDefault) {
  7851. evt.preventDefault();
  7852. }
  7853. };
  7854. this._onPointerMove = function (evt) {
  7855. if (!noPreventDefault) {
  7856. evt.preventDefault();
  7857. }
  7858. switch (pointers.count) {
  7859. case 1:
  7860. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7861. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7862. var offsetX = evt.clientX - cacheSoloPointer.x;
  7863. var offsetY = evt.clientY - cacheSoloPointer.y;
  7864. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7865. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7866. //pointers.item(evt.pointerId).x = evt.clientX;
  7867. //pointers.item(evt.pointerId).y = evt.clientY;
  7868. cacheSoloPointer.x = evt.clientX;
  7869. cacheSoloPointer.y = evt.clientY;
  7870. break;
  7871. case 2:
  7872. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7873. pointers.item(evt.pointerId).x = evt.clientX;
  7874. pointers.item(evt.pointerId).y = evt.clientY;
  7875. var direction = 1;
  7876. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7877. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7878. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7879. if (previousPinchDistance === 0) {
  7880. previousPinchDistance = pinchSquaredDistance;
  7881. return;
  7882. }
  7883. if (pinchSquaredDistance !== previousPinchDistance) {
  7884. if (pinchSquaredDistance > previousPinchDistance) {
  7885. direction = -1;
  7886. }
  7887. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7888. previousPinchDistance = pinchSquaredDistance;
  7889. }
  7890. break;
  7891. default:
  7892. if (pointers.item(evt.pointerId)) {
  7893. pointers.item(evt.pointerId).x = evt.clientX;
  7894. pointers.item(evt.pointerId).y = evt.clientY;
  7895. }
  7896. }
  7897. };
  7898. this._onMouseMove = function (evt) {
  7899. if (!engine.isPointerLock) {
  7900. return;
  7901. }
  7902. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7903. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7904. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7905. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7906. if (!noPreventDefault) {
  7907. evt.preventDefault();
  7908. }
  7909. };
  7910. this._wheel = function (event) {
  7911. var delta = 0;
  7912. if (event.wheelDelta) {
  7913. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7914. }
  7915. else if (event.detail) {
  7916. delta = -event.detail / _this.wheelPrecision;
  7917. }
  7918. if (delta)
  7919. _this.inertialRadiusOffset += delta;
  7920. if (event.preventDefault) {
  7921. if (!noPreventDefault) {
  7922. event.preventDefault();
  7923. }
  7924. }
  7925. };
  7926. this._onKeyDown = function (evt) {
  7927. 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) {
  7928. var index = _this._keys.indexOf(evt.keyCode);
  7929. if (index === -1) {
  7930. _this._keys.push(evt.keyCode);
  7931. }
  7932. if (evt.preventDefault) {
  7933. if (!noPreventDefault) {
  7934. evt.preventDefault();
  7935. }
  7936. }
  7937. }
  7938. };
  7939. this._onKeyUp = function (evt) {
  7940. 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) {
  7941. var index = _this._keys.indexOf(evt.keyCode);
  7942. if (index >= 0) {
  7943. _this._keys.splice(index, 1);
  7944. }
  7945. if (evt.preventDefault) {
  7946. if (!noPreventDefault) {
  7947. evt.preventDefault();
  7948. }
  7949. }
  7950. }
  7951. };
  7952. this._onLostFocus = function () {
  7953. _this._keys = [];
  7954. pointers.empty();
  7955. previousPinchDistance = 0;
  7956. cacheSoloPointer = null;
  7957. };
  7958. this._onGestureStart = function (e) {
  7959. if (window.MSGesture === undefined) {
  7960. return;
  7961. }
  7962. if (!_this._MSGestureHandler) {
  7963. _this._MSGestureHandler = new MSGesture();
  7964. _this._MSGestureHandler.target = element;
  7965. }
  7966. _this._MSGestureHandler.addPointer(e.pointerId);
  7967. };
  7968. this._onGesture = function (e) {
  7969. _this.radius *= e.scale;
  7970. if (e.preventDefault) {
  7971. if (!noPreventDefault) {
  7972. e.stopPropagation();
  7973. e.preventDefault();
  7974. }
  7975. }
  7976. };
  7977. this._reset = function () {
  7978. _this._keys = [];
  7979. _this.inertialAlphaOffset = 0;
  7980. _this.inertialBetaOffset = 0;
  7981. _this.inertialRadiusOffset = 0;
  7982. pointers.empty();
  7983. previousPinchDistance = 0;
  7984. cacheSoloPointer = null;
  7985. };
  7986. }
  7987. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7988. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7989. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7990. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7991. element.addEventListener("mousemove", this._onMouseMove, false);
  7992. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7993. element.addEventListener("MSGestureChange", this._onGesture, false);
  7994. element.addEventListener('mousewheel', this._wheel, false);
  7995. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7996. BABYLON.Tools.RegisterTopRootEvents([
  7997. { name: "keydown", handler: this._onKeyDown },
  7998. { name: "keyup", handler: this._onKeyUp },
  7999. { name: "blur", handler: this._onLostFocus }
  8000. ]);
  8001. };
  8002. ArcRotateCamera.prototype.detachControl = function (element) {
  8003. if (this._attachedElement !== element) {
  8004. return;
  8005. }
  8006. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8007. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8008. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8009. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8010. element.removeEventListener("mousemove", this._onMouseMove);
  8011. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8012. element.removeEventListener("MSGestureChange", this._onGesture);
  8013. element.removeEventListener('mousewheel', this._wheel);
  8014. element.removeEventListener('DOMMouseScroll', this._wheel);
  8015. BABYLON.Tools.UnregisterTopRootEvents([
  8016. { name: "keydown", handler: this._onKeyDown },
  8017. { name: "keyup", handler: this._onKeyUp },
  8018. { name: "blur", handler: this._onLostFocus }
  8019. ]);
  8020. this._MSGestureHandler = null;
  8021. this._attachedElement = null;
  8022. if (this._reset) {
  8023. this._reset();
  8024. }
  8025. };
  8026. ArcRotateCamera.prototype._update = function () {
  8027. for (var index = 0; index < this._keys.length; index++) {
  8028. var keyCode = this._keys[index];
  8029. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8030. this.inertialAlphaOffset -= 0.01;
  8031. }
  8032. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8033. this.inertialBetaOffset -= 0.01;
  8034. }
  8035. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8036. this.inertialAlphaOffset += 0.01;
  8037. }
  8038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8039. this.inertialBetaOffset += 0.01;
  8040. }
  8041. }
  8042. // Inertia
  8043. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8044. this.alpha += this.inertialAlphaOffset;
  8045. this.beta += this.inertialBetaOffset;
  8046. this.radius -= this.inertialRadiusOffset;
  8047. this.inertialAlphaOffset *= this.inertia;
  8048. this.inertialBetaOffset *= this.inertia;
  8049. this.inertialRadiusOffset *= this.inertia;
  8050. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8051. this.inertialAlphaOffset = 0;
  8052. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8053. this.inertialBetaOffset = 0;
  8054. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8055. this.inertialRadiusOffset = 0;
  8056. }
  8057. // Limits
  8058. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8059. this.alpha = this.lowerAlphaLimit;
  8060. }
  8061. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8062. this.alpha = this.upperAlphaLimit;
  8063. }
  8064. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8065. this.beta = this.lowerBetaLimit;
  8066. }
  8067. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8068. this.beta = this.upperBetaLimit;
  8069. }
  8070. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8071. this.radius = this.lowerRadiusLimit;
  8072. }
  8073. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8074. this.radius = this.upperRadiusLimit;
  8075. }
  8076. };
  8077. ArcRotateCamera.prototype.setPosition = function (position) {
  8078. var radiusv3 = position.subtract(this._getTargetPosition());
  8079. this.radius = radiusv3.length();
  8080. // Alpha
  8081. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8082. if (radiusv3.z < 0) {
  8083. this.alpha = 2 * Math.PI - this.alpha;
  8084. }
  8085. // Beta
  8086. this.beta = Math.acos(radiusv3.y / this.radius);
  8087. };
  8088. ArcRotateCamera.prototype._getViewMatrix = function () {
  8089. // Compute
  8090. var cosa = Math.cos(this.alpha);
  8091. var sina = Math.sin(this.alpha);
  8092. var cosb = Math.cos(this.beta);
  8093. var sinb = Math.sin(this.beta);
  8094. var target = this._getTargetPosition();
  8095. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8096. if (this.checkCollisions) {
  8097. this._collider.radius = this.collisionRadius;
  8098. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8099. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8100. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8101. this.position.copyFrom(this._previousPosition);
  8102. this.alpha = this._previousAlpha;
  8103. this.beta = this._previousBeta;
  8104. this.radius = this._previousRadius;
  8105. if (this.onCollide) {
  8106. this.onCollide(this._collider.collidedMesh);
  8107. }
  8108. }
  8109. }
  8110. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8111. this._previousAlpha = this.alpha;
  8112. this._previousBeta = this.beta;
  8113. this._previousRadius = this.radius;
  8114. this._previousPosition.copyFrom(this.position);
  8115. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8116. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8117. return this._viewMatrix;
  8118. };
  8119. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8120. meshes = meshes || this.getScene().meshes;
  8121. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8122. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8123. this.radius = distance * this.zoomOnFactor;
  8124. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8125. };
  8126. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8127. var meshesOrMinMaxVector;
  8128. var distance;
  8129. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8130. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8131. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8132. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8133. }
  8134. else {
  8135. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8136. distance = meshesOrMinMaxVectorAndDistance.distance;
  8137. }
  8138. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8139. this.maxZ = distance * 2;
  8140. };
  8141. return ArcRotateCamera;
  8142. })(BABYLON.Camera);
  8143. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8144. })(BABYLON || (BABYLON = {}));
  8145. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8146. (function (BABYLON) {
  8147. /**
  8148. * Represents a scene to be rendered by the engine.
  8149. * @see http://doc.babylonjs.com/page.php?p=21911
  8150. */
  8151. var Scene = (function () {
  8152. /**
  8153. * @constructor
  8154. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8155. */
  8156. function Scene(engine) {
  8157. // Members
  8158. this.autoClear = true;
  8159. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8160. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8161. this.forceWireframe = false;
  8162. this.forcePointsCloud = false;
  8163. this.forceShowBoundingBoxes = false;
  8164. this.animationsEnabled = true;
  8165. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  8166. // Fog
  8167. /**
  8168. * is fog enabled on this scene.
  8169. * @type {boolean}
  8170. */
  8171. this.fogEnabled = true;
  8172. this.fogMode = Scene.FOGMODE_NONE;
  8173. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8174. this.fogDensity = 0.1;
  8175. this.fogStart = 0;
  8176. this.fogEnd = 1000.0;
  8177. // Lights
  8178. /**
  8179. * is shadow enabled on this scene.
  8180. * @type {boolean}
  8181. */
  8182. this.shadowsEnabled = true;
  8183. /**
  8184. * is light enabled on this scene.
  8185. * @type {boolean}
  8186. */
  8187. this.lightsEnabled = true;
  8188. /**
  8189. * All of the lights added to this scene.
  8190. * @see BABYLON.Light
  8191. * @type {BABYLON.Light[]}
  8192. */
  8193. this.lights = new Array();
  8194. // Cameras
  8195. /**
  8196. * All of the cameras added to this scene.
  8197. * @see BABYLON.Camera
  8198. * @type {BABYLON.Camera[]}
  8199. */
  8200. this.cameras = new Array();
  8201. this.activeCameras = new Array();
  8202. // Meshes
  8203. /**
  8204. * All of the (abstract) meshes added to this scene.
  8205. * @see BABYLON.AbstractMesh
  8206. * @type {BABYLON.AbstractMesh[]}
  8207. */
  8208. this.meshes = new Array();
  8209. // Geometries
  8210. this._geometries = new Array();
  8211. this.materials = new Array();
  8212. this.multiMaterials = new Array();
  8213. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8214. // Textures
  8215. this.texturesEnabled = true;
  8216. this.textures = new Array();
  8217. // Particles
  8218. this.particlesEnabled = true;
  8219. this.particleSystems = new Array();
  8220. // Sprites
  8221. this.spritesEnabled = true;
  8222. this.spriteManagers = new Array();
  8223. // Layers
  8224. this.layers = new Array();
  8225. // Skeletons
  8226. this.skeletonsEnabled = true;
  8227. this.skeletons = new Array();
  8228. // Lens flares
  8229. this.lensFlaresEnabled = true;
  8230. this.lensFlareSystems = new Array();
  8231. // Collisions
  8232. this.collisionsEnabled = true;
  8233. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8234. // Postprocesses
  8235. this.postProcessesEnabled = true;
  8236. // Customs render targets
  8237. this.renderTargetsEnabled = true;
  8238. this.dumpNextRenderTargets = false;
  8239. this.customRenderTargets = new Array();
  8240. // Imported meshes
  8241. this.importedMeshesFiles = new Array();
  8242. this._actionManagers = new Array();
  8243. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8244. // Procedural textures
  8245. this.proceduralTexturesEnabled = true;
  8246. this._proceduralTextures = new Array();
  8247. this.soundTracks = new Array();
  8248. this._audioEnabled = true;
  8249. this._headphone = false;
  8250. this._totalVertices = 0;
  8251. this._activeVertices = 0;
  8252. this._activeParticles = 0;
  8253. this._lastFrameDuration = 0;
  8254. this._evaluateActiveMeshesDuration = 0;
  8255. this._renderTargetsDuration = 0;
  8256. this._particlesDuration = 0;
  8257. this._renderDuration = 0;
  8258. this._spritesDuration = 0;
  8259. this._animationRatio = 0;
  8260. this._renderId = 0;
  8261. this._executeWhenReadyTimeoutId = -1;
  8262. this._toBeDisposed = new BABYLON.SmartArray(256);
  8263. this._onReadyCallbacks = new Array();
  8264. this._pendingData = []; //ANY
  8265. this._onBeforeRenderCallbacks = new Array();
  8266. this._onAfterRenderCallbacks = new Array();
  8267. this._activeMeshes = new BABYLON.SmartArray(256);
  8268. this._processedMaterials = new BABYLON.SmartArray(256);
  8269. this._renderTargets = new BABYLON.SmartArray(256);
  8270. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8271. this._activeSkeletons = new BABYLON.SmartArray(32);
  8272. this._activeBones = 0;
  8273. this._activeAnimatables = new Array();
  8274. this._transformMatrix = BABYLON.Matrix.Zero();
  8275. this._scaledPosition = BABYLON.Vector3.Zero();
  8276. this._scaledVelocity = BABYLON.Vector3.Zero();
  8277. this._uniqueIdCounter = 0;
  8278. this._engine = engine;
  8279. engine.scenes.push(this);
  8280. this._renderingManager = new BABYLON.RenderingManager(this);
  8281. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8282. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8283. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8284. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8285. this.attachControl();
  8286. this._debugLayer = new BABYLON.DebugLayer(this);
  8287. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8288. //simplification queue
  8289. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8290. }
  8291. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8292. get: function () {
  8293. return Scene._FOGMODE_NONE;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8299. get: function () {
  8300. return Scene._FOGMODE_EXP;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8306. get: function () {
  8307. return Scene._FOGMODE_EXP2;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8313. get: function () {
  8314. return Scene._FOGMODE_LINEAR;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. Object.defineProperty(Scene.prototype, "debugLayer", {
  8320. // Properties
  8321. get: function () {
  8322. return this._debugLayer;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8328. /**
  8329. * The mesh that is currently under the pointer.
  8330. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8331. */
  8332. get: function () {
  8333. return this._meshUnderPointer;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Scene.prototype, "pointerX", {
  8339. /**
  8340. * Current on-screen X position of the pointer
  8341. * @return {number} X position of the pointer
  8342. */
  8343. get: function () {
  8344. return this._pointerX;
  8345. },
  8346. enumerable: true,
  8347. configurable: true
  8348. });
  8349. Object.defineProperty(Scene.prototype, "pointerY", {
  8350. /**
  8351. * Current on-screen Y position of the pointer
  8352. * @return {number} Y position of the pointer
  8353. */
  8354. get: function () {
  8355. return this._pointerY;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Scene.prototype.getCachedMaterial = function () {
  8361. return this._cachedMaterial;
  8362. };
  8363. Scene.prototype.getBoundingBoxRenderer = function () {
  8364. return this._boundingBoxRenderer;
  8365. };
  8366. Scene.prototype.getOutlineRenderer = function () {
  8367. return this._outlineRenderer;
  8368. };
  8369. Scene.prototype.getEngine = function () {
  8370. return this._engine;
  8371. };
  8372. Scene.prototype.getTotalVertices = function () {
  8373. return this._totalVertices;
  8374. };
  8375. Scene.prototype.getActiveVertices = function () {
  8376. return this._activeVertices;
  8377. };
  8378. Scene.prototype.getActiveParticles = function () {
  8379. return this._activeParticles;
  8380. };
  8381. Scene.prototype.getActiveBones = function () {
  8382. return this._activeBones;
  8383. };
  8384. // Stats
  8385. Scene.prototype.getLastFrameDuration = function () {
  8386. return this._lastFrameDuration;
  8387. };
  8388. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8389. return this._evaluateActiveMeshesDuration;
  8390. };
  8391. Scene.prototype.getActiveMeshes = function () {
  8392. return this._activeMeshes;
  8393. };
  8394. Scene.prototype.getRenderTargetsDuration = function () {
  8395. return this._renderTargetsDuration;
  8396. };
  8397. Scene.prototype.getRenderDuration = function () {
  8398. return this._renderDuration;
  8399. };
  8400. Scene.prototype.getParticlesDuration = function () {
  8401. return this._particlesDuration;
  8402. };
  8403. Scene.prototype.getSpritesDuration = function () {
  8404. return this._spritesDuration;
  8405. };
  8406. Scene.prototype.getAnimationRatio = function () {
  8407. return this._animationRatio;
  8408. };
  8409. Scene.prototype.getRenderId = function () {
  8410. return this._renderId;
  8411. };
  8412. Scene.prototype.incrementRenderId = function () {
  8413. this._renderId++;
  8414. };
  8415. Scene.prototype._updatePointerPosition = function (evt) {
  8416. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8417. this._pointerX = evt.clientX - canvasRect.left;
  8418. this._pointerY = evt.clientY - canvasRect.top;
  8419. if (this.cameraToUseForPointers) {
  8420. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8421. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8422. }
  8423. };
  8424. // Pointers handling
  8425. Scene.prototype.attachControl = function () {
  8426. var _this = this;
  8427. this._onPointerMove = function (evt) {
  8428. var canvas = _this._engine.getRenderingCanvas();
  8429. _this._updatePointerPosition(evt);
  8430. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  8431. if (pickResult.hit) {
  8432. _this._meshUnderPointer = pickResult.pickedMesh;
  8433. _this.setPointerOverMesh(pickResult.pickedMesh);
  8434. canvas.style.cursor = "pointer";
  8435. }
  8436. else {
  8437. _this.setPointerOverMesh(null);
  8438. canvas.style.cursor = "";
  8439. _this._meshUnderPointer = null;
  8440. }
  8441. };
  8442. this._onPointerDown = function (evt) {
  8443. var predicate = null;
  8444. if (!_this.onPointerDown) {
  8445. predicate = function (mesh) {
  8446. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8447. };
  8448. }
  8449. _this._updatePointerPosition(evt);
  8450. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8451. if (pickResult.hit) {
  8452. if (pickResult.pickedMesh.actionManager) {
  8453. switch (evt.button) {
  8454. case 0:
  8455. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8456. break;
  8457. case 1:
  8458. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8459. break;
  8460. case 2:
  8461. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8462. break;
  8463. }
  8464. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8465. }
  8466. }
  8467. if (_this.onPointerDown) {
  8468. _this.onPointerDown(evt, pickResult);
  8469. }
  8470. };
  8471. this._onKeyDown = function (evt) {
  8472. if (_this.actionManager) {
  8473. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8474. }
  8475. };
  8476. this._onKeyUp = function (evt) {
  8477. if (_this.actionManager) {
  8478. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8479. }
  8480. };
  8481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8482. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8483. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8484. BABYLON.Tools.RegisterTopRootEvents([
  8485. { name: "keydown", handler: this._onKeyDown },
  8486. { name: "keyup", handler: this._onKeyUp }
  8487. ]);
  8488. };
  8489. Scene.prototype.detachControl = function () {
  8490. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8491. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8492. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8493. BABYLON.Tools.UnregisterTopRootEvents([
  8494. { name: "keydown", handler: this._onKeyDown },
  8495. { name: "keyup", handler: this._onKeyUp }
  8496. ]);
  8497. };
  8498. // Ready
  8499. Scene.prototype.isReady = function () {
  8500. if (this._pendingData.length > 0) {
  8501. return false;
  8502. }
  8503. for (var index = 0; index < this._geometries.length; index++) {
  8504. var geometry = this._geometries[index];
  8505. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8506. return false;
  8507. }
  8508. }
  8509. for (index = 0; index < this.meshes.length; index++) {
  8510. var mesh = this.meshes[index];
  8511. if (!mesh.isReady()) {
  8512. return false;
  8513. }
  8514. var mat = mesh.material;
  8515. if (mat) {
  8516. if (!mat.isReady(mesh)) {
  8517. return false;
  8518. }
  8519. }
  8520. }
  8521. return true;
  8522. };
  8523. Scene.prototype.resetCachedMaterial = function () {
  8524. this._cachedMaterial = null;
  8525. };
  8526. Scene.prototype.registerBeforeRender = function (func) {
  8527. this._onBeforeRenderCallbacks.push(func);
  8528. };
  8529. Scene.prototype.unregisterBeforeRender = function (func) {
  8530. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8531. if (index > -1) {
  8532. this._onBeforeRenderCallbacks.splice(index, 1);
  8533. }
  8534. };
  8535. Scene.prototype.registerAfterRender = function (func) {
  8536. this._onAfterRenderCallbacks.push(func);
  8537. };
  8538. Scene.prototype.unregisterAfterRender = function (func) {
  8539. var index = this._onAfterRenderCallbacks.indexOf(func);
  8540. if (index > -1) {
  8541. this._onAfterRenderCallbacks.splice(index, 1);
  8542. }
  8543. };
  8544. Scene.prototype._addPendingData = function (data) {
  8545. this._pendingData.push(data);
  8546. };
  8547. Scene.prototype._removePendingData = function (data) {
  8548. var index = this._pendingData.indexOf(data);
  8549. if (index !== -1) {
  8550. this._pendingData.splice(index, 1);
  8551. }
  8552. };
  8553. Scene.prototype.getWaitingItemsCount = function () {
  8554. return this._pendingData.length;
  8555. };
  8556. /**
  8557. * Registers a function to be executed when the scene is ready.
  8558. * @param {Function} func - the function to be executed.
  8559. */
  8560. Scene.prototype.executeWhenReady = function (func) {
  8561. var _this = this;
  8562. this._onReadyCallbacks.push(func);
  8563. if (this._executeWhenReadyTimeoutId !== -1) {
  8564. return;
  8565. }
  8566. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8567. _this._checkIsReady();
  8568. }, 150);
  8569. };
  8570. Scene.prototype._checkIsReady = function () {
  8571. var _this = this;
  8572. if (this.isReady()) {
  8573. this._onReadyCallbacks.forEach(function (func) {
  8574. func();
  8575. });
  8576. this._onReadyCallbacks = [];
  8577. this._executeWhenReadyTimeoutId = -1;
  8578. return;
  8579. }
  8580. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8581. _this._checkIsReady();
  8582. }, 150);
  8583. };
  8584. // Animations
  8585. /**
  8586. * Will start the animation sequence of a given target
  8587. * @param target - the target
  8588. * @param {number} from - from which frame should animation start
  8589. * @param {number} to - till which frame should animation run.
  8590. * @param {boolean} [loop] - should the animation loop
  8591. * @param {number} [speedRatio] - the speed in which to run the animation
  8592. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8593. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8594. * @return {BABYLON.Animatable} the animatable object created for this animation
  8595. * @see BABYLON.Animatable
  8596. * @see http://doc.babylonjs.com/page.php?p=22081
  8597. */
  8598. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8599. if (speedRatio === undefined) {
  8600. speedRatio = 1.0;
  8601. }
  8602. this.stopAnimation(target);
  8603. if (!animatable) {
  8604. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8605. }
  8606. // Local animations
  8607. if (target.animations) {
  8608. animatable.appendAnimations(target, target.animations);
  8609. }
  8610. // Children animations
  8611. if (target.getAnimatables) {
  8612. var animatables = target.getAnimatables();
  8613. for (var index = 0; index < animatables.length; index++) {
  8614. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8615. }
  8616. }
  8617. return animatable;
  8618. };
  8619. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8620. if (speedRatio === undefined) {
  8621. speedRatio = 1.0;
  8622. }
  8623. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8624. return animatable;
  8625. };
  8626. Scene.prototype.getAnimatableByTarget = function (target) {
  8627. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8628. if (this._activeAnimatables[index].target === target) {
  8629. return this._activeAnimatables[index];
  8630. }
  8631. }
  8632. return null;
  8633. };
  8634. /**
  8635. * Will stop the animation of the given target
  8636. * @param target - the target
  8637. * @see beginAnimation
  8638. */
  8639. Scene.prototype.stopAnimation = function (target) {
  8640. var animatable = this.getAnimatableByTarget(target);
  8641. if (animatable) {
  8642. animatable.stop();
  8643. }
  8644. };
  8645. Scene.prototype._animate = function () {
  8646. if (!this.animationsEnabled) {
  8647. return;
  8648. }
  8649. if (!this._animationStartDate) {
  8650. this._animationStartDate = BABYLON.Tools.Now;
  8651. }
  8652. // Getting time
  8653. var now = BABYLON.Tools.Now;
  8654. var delay = now - this._animationStartDate;
  8655. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8656. this._activeAnimatables[index]._animate(delay);
  8657. }
  8658. };
  8659. // Matrix
  8660. Scene.prototype.getViewMatrix = function () {
  8661. return this._viewMatrix;
  8662. };
  8663. Scene.prototype.getProjectionMatrix = function () {
  8664. return this._projectionMatrix;
  8665. };
  8666. Scene.prototype.getTransformMatrix = function () {
  8667. return this._transformMatrix;
  8668. };
  8669. Scene.prototype.setTransformMatrix = function (view, projection) {
  8670. this._viewMatrix = view;
  8671. this._projectionMatrix = projection;
  8672. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8673. };
  8674. // Methods
  8675. Scene.prototype.addMesh = function (newMesh) {
  8676. newMesh.uniqueId = this._uniqueIdCounter++;
  8677. var position = this.meshes.push(newMesh);
  8678. if (this.onNewMeshAdded) {
  8679. this.onNewMeshAdded(newMesh, position, this);
  8680. }
  8681. };
  8682. Scene.prototype.removeMesh = function (toRemove) {
  8683. var index = this.meshes.indexOf(toRemove);
  8684. if (index !== -1) {
  8685. // Remove from the scene if mesh found
  8686. this.meshes.splice(index, 1);
  8687. }
  8688. if (this.onMeshRemoved) {
  8689. this.onMeshRemoved(toRemove);
  8690. }
  8691. return index;
  8692. };
  8693. Scene.prototype.removeLight = function (toRemove) {
  8694. var index = this.lights.indexOf(toRemove);
  8695. if (index !== -1) {
  8696. // Remove from the scene if mesh found
  8697. this.lights.splice(index, 1);
  8698. }
  8699. if (this.onLightRemoved) {
  8700. this.onLightRemoved(toRemove);
  8701. }
  8702. return index;
  8703. };
  8704. Scene.prototype.removeCamera = function (toRemove) {
  8705. var index = this.cameras.indexOf(toRemove);
  8706. if (index !== -1) {
  8707. // Remove from the scene if mesh found
  8708. this.cameras.splice(index, 1);
  8709. }
  8710. if (this.onCameraRemoved) {
  8711. this.onCameraRemoved(toRemove);
  8712. }
  8713. return index;
  8714. };
  8715. Scene.prototype.addLight = function (newLight) {
  8716. newLight.uniqueId = this._uniqueIdCounter++;
  8717. var position = this.lights.push(newLight);
  8718. if (this.onNewLightAdded) {
  8719. this.onNewLightAdded(newLight, position, this);
  8720. }
  8721. };
  8722. Scene.prototype.addCamera = function (newCamera) {
  8723. newCamera.uniqueId = this._uniqueIdCounter++;
  8724. var position = this.cameras.push(newCamera);
  8725. if (this.onNewCameraAdded) {
  8726. this.onNewCameraAdded(newCamera, position, this);
  8727. }
  8728. };
  8729. /**
  8730. * sets the active camera of the scene using its ID
  8731. * @param {string} id - the camera's ID
  8732. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8733. * @see activeCamera
  8734. */
  8735. Scene.prototype.setActiveCameraByID = function (id) {
  8736. var camera = this.getCameraByID(id);
  8737. if (camera) {
  8738. this.activeCamera = camera;
  8739. return camera;
  8740. }
  8741. return null;
  8742. };
  8743. /**
  8744. * sets the active camera of the scene using its name
  8745. * @param {string} name - the camera's name
  8746. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8747. * @see activeCamera
  8748. */
  8749. Scene.prototype.setActiveCameraByName = function (name) {
  8750. var camera = this.getCameraByName(name);
  8751. if (camera) {
  8752. this.activeCamera = camera;
  8753. return camera;
  8754. }
  8755. return null;
  8756. };
  8757. /**
  8758. * get a material using its id
  8759. * @param {string} the material's ID
  8760. * @return {BABYLON.Material|null} the material or null if none found.
  8761. */
  8762. Scene.prototype.getMaterialByID = function (id) {
  8763. for (var index = 0; index < this.materials.length; index++) {
  8764. if (this.materials[index].id === id) {
  8765. return this.materials[index];
  8766. }
  8767. }
  8768. return null;
  8769. };
  8770. /**
  8771. * get a material using its name
  8772. * @param {string} the material's name
  8773. * @return {BABYLON.Material|null} the material or null if none found.
  8774. */
  8775. Scene.prototype.getMaterialByName = function (name) {
  8776. for (var index = 0; index < this.materials.length; index++) {
  8777. if (this.materials[index].name === name) {
  8778. return this.materials[index];
  8779. }
  8780. }
  8781. return null;
  8782. };
  8783. Scene.prototype.getCameraByID = function (id) {
  8784. for (var index = 0; index < this.cameras.length; index++) {
  8785. if (this.cameras[index].id === id) {
  8786. return this.cameras[index];
  8787. }
  8788. }
  8789. return null;
  8790. };
  8791. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8792. for (var index = 0; index < this.cameras.length; index++) {
  8793. if (this.cameras[index].uniqueId === uniqueId) {
  8794. return this.cameras[index];
  8795. }
  8796. }
  8797. return null;
  8798. };
  8799. /**
  8800. * get a camera using its name
  8801. * @param {string} the camera's name
  8802. * @return {BABYLON.Camera|null} the camera or null if none found.
  8803. */
  8804. Scene.prototype.getCameraByName = function (name) {
  8805. for (var index = 0; index < this.cameras.length; index++) {
  8806. if (this.cameras[index].name === name) {
  8807. return this.cameras[index];
  8808. }
  8809. }
  8810. return null;
  8811. };
  8812. /**
  8813. * get a light node using its name
  8814. * @param {string} the light's name
  8815. * @return {BABYLON.Light|null} the light or null if none found.
  8816. */
  8817. Scene.prototype.getLightByName = function (name) {
  8818. for (var index = 0; index < this.lights.length; index++) {
  8819. if (this.lights[index].name === name) {
  8820. return this.lights[index];
  8821. }
  8822. }
  8823. return null;
  8824. };
  8825. /**
  8826. * get a light node using its ID
  8827. * @param {string} the light's id
  8828. * @return {BABYLON.Light|null} the light or null if none found.
  8829. */
  8830. Scene.prototype.getLightByID = function (id) {
  8831. for (var index = 0; index < this.lights.length; index++) {
  8832. if (this.lights[index].id === id) {
  8833. return this.lights[index];
  8834. }
  8835. }
  8836. return null;
  8837. };
  8838. /**
  8839. * get a light node using its scene-generated unique ID
  8840. * @param {number} the light's unique id
  8841. * @return {BABYLON.Light|null} the light or null if none found.
  8842. */
  8843. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8844. for (var index = 0; index < this.lights.length; index++) {
  8845. if (this.lights[index].uniqueId === uniqueId) {
  8846. return this.lights[index];
  8847. }
  8848. }
  8849. return null;
  8850. };
  8851. /**
  8852. * get a geometry using its ID
  8853. * @param {string} the geometry's id
  8854. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8855. */
  8856. Scene.prototype.getGeometryByID = function (id) {
  8857. for (var index = 0; index < this._geometries.length; index++) {
  8858. if (this._geometries[index].id === id) {
  8859. return this._geometries[index];
  8860. }
  8861. }
  8862. return null;
  8863. };
  8864. /**
  8865. * add a new geometry to this scene.
  8866. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8867. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8868. * @return {boolean} was the geometry added or not
  8869. */
  8870. Scene.prototype.pushGeometry = function (geometry, force) {
  8871. if (!force && this.getGeometryByID(geometry.id)) {
  8872. return false;
  8873. }
  8874. this._geometries.push(geometry);
  8875. return true;
  8876. };
  8877. Scene.prototype.getGeometries = function () {
  8878. return this._geometries;
  8879. };
  8880. /**
  8881. * Get the first added mesh found of a given ID
  8882. * @param {string} id - the id to search for
  8883. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8884. */
  8885. Scene.prototype.getMeshByID = function (id) {
  8886. for (var index = 0; index < this.meshes.length; index++) {
  8887. if (this.meshes[index].id === id) {
  8888. return this.meshes[index];
  8889. }
  8890. }
  8891. return null;
  8892. };
  8893. /**
  8894. * Get a mesh with its auto-generated unique id
  8895. * @param {number} uniqueId - the unique id to search for
  8896. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8897. */
  8898. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8899. for (var index = 0; index < this.meshes.length; index++) {
  8900. if (this.meshes[index].uniqueId === uniqueId) {
  8901. return this.meshes[index];
  8902. }
  8903. }
  8904. return null;
  8905. };
  8906. /**
  8907. * Get a the last added mesh found of a given ID
  8908. * @param {string} id - the id to search for
  8909. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8910. */
  8911. Scene.prototype.getLastMeshByID = function (id) {
  8912. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8913. if (this.meshes[index].id === id) {
  8914. return this.meshes[index];
  8915. }
  8916. }
  8917. return null;
  8918. };
  8919. /**
  8920. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8921. * @param {string} id - the id to search for
  8922. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8923. */
  8924. Scene.prototype.getLastEntryByID = function (id) {
  8925. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8926. if (this.meshes[index].id === id) {
  8927. return this.meshes[index];
  8928. }
  8929. }
  8930. for (index = this.cameras.length - 1; index >= 0; index--) {
  8931. if (this.cameras[index].id === id) {
  8932. return this.cameras[index];
  8933. }
  8934. }
  8935. for (index = this.lights.length - 1; index >= 0; index--) {
  8936. if (this.lights[index].id === id) {
  8937. return this.lights[index];
  8938. }
  8939. }
  8940. return null;
  8941. };
  8942. Scene.prototype.getNodeByName = function (name) {
  8943. var mesh = this.getMeshByName(name);
  8944. if (mesh) {
  8945. return mesh;
  8946. }
  8947. var light = this.getLightByName(name);
  8948. if (light) {
  8949. return light;
  8950. }
  8951. return this.getCameraByName(name);
  8952. };
  8953. Scene.prototype.getMeshByName = function (name) {
  8954. for (var index = 0; index < this.meshes.length; index++) {
  8955. if (this.meshes[index].name === name) {
  8956. return this.meshes[index];
  8957. }
  8958. }
  8959. return null;
  8960. };
  8961. Scene.prototype.getSoundByName = function (name) {
  8962. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8963. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8964. return this.mainSoundTrack.soundCollection[index];
  8965. }
  8966. }
  8967. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8968. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8969. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8970. return this.soundTracks[sdIndex].soundCollection[index];
  8971. }
  8972. }
  8973. }
  8974. return null;
  8975. };
  8976. Scene.prototype.getLastSkeletonByID = function (id) {
  8977. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8978. if (this.skeletons[index].id === id) {
  8979. return this.skeletons[index];
  8980. }
  8981. }
  8982. return null;
  8983. };
  8984. Scene.prototype.getSkeletonById = function (id) {
  8985. for (var index = 0; index < this.skeletons.length; index++) {
  8986. if (this.skeletons[index].id === id) {
  8987. return this.skeletons[index];
  8988. }
  8989. }
  8990. return null;
  8991. };
  8992. Scene.prototype.getSkeletonByName = function (name) {
  8993. for (var index = 0; index < this.skeletons.length; index++) {
  8994. if (this.skeletons[index].name === name) {
  8995. return this.skeletons[index];
  8996. }
  8997. }
  8998. return null;
  8999. };
  9000. Scene.prototype.isActiveMesh = function (mesh) {
  9001. return (this._activeMeshes.indexOf(mesh) !== -1);
  9002. };
  9003. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9004. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9005. var material = subMesh.getMaterial();
  9006. if (mesh.showSubMeshesBoundingBox) {
  9007. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9008. }
  9009. if (material) {
  9010. // Render targets
  9011. if (material.getRenderTargetTextures) {
  9012. if (this._processedMaterials.indexOf(material) === -1) {
  9013. this._processedMaterials.push(material);
  9014. this._renderTargets.concat(material.getRenderTargetTextures());
  9015. }
  9016. }
  9017. // Dispatch
  9018. this._activeVertices += subMesh.indexCount;
  9019. this._renderingManager.dispatch(subMesh);
  9020. }
  9021. }
  9022. };
  9023. Scene.prototype._evaluateActiveMeshes = function () {
  9024. this.activeCamera._activeMeshes.reset();
  9025. this._activeMeshes.reset();
  9026. this._renderingManager.reset();
  9027. this._processedMaterials.reset();
  9028. this._activeParticleSystems.reset();
  9029. this._activeSkeletons.reset();
  9030. this._boundingBoxRenderer.reset();
  9031. if (!this._frustumPlanes) {
  9032. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9033. }
  9034. else {
  9035. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9036. }
  9037. // Meshes
  9038. var meshes;
  9039. var len;
  9040. if (this._selectionOctree) {
  9041. var selection = this._selectionOctree.select(this._frustumPlanes);
  9042. meshes = selection.data;
  9043. len = selection.length;
  9044. }
  9045. else {
  9046. len = this.meshes.length;
  9047. meshes = this.meshes;
  9048. }
  9049. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9050. var mesh = meshes[meshIndex];
  9051. if (mesh.isBlocked) {
  9052. continue;
  9053. }
  9054. this._totalVertices += mesh.getTotalVertices();
  9055. if (!mesh.isReady()) {
  9056. continue;
  9057. }
  9058. mesh.computeWorldMatrix();
  9059. // Intersections
  9060. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9061. this._meshesForIntersections.pushNoDuplicate(mesh);
  9062. }
  9063. // Switch to current LOD
  9064. var meshLOD = mesh.getLOD(this.activeCamera);
  9065. if (!meshLOD) {
  9066. continue;
  9067. }
  9068. mesh._preActivate();
  9069. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9070. this._activeMeshes.push(mesh);
  9071. this.activeCamera._activeMeshes.push(mesh);
  9072. mesh._activate(this._renderId);
  9073. this._activeMesh(meshLOD);
  9074. }
  9075. }
  9076. // Particle systems
  9077. var beforeParticlesDate = BABYLON.Tools.Now;
  9078. if (this.particlesEnabled) {
  9079. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9080. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9081. var particleSystem = this.particleSystems[particleIndex];
  9082. if (!particleSystem.isStarted()) {
  9083. continue;
  9084. }
  9085. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9086. this._activeParticleSystems.push(particleSystem);
  9087. particleSystem.animate();
  9088. }
  9089. }
  9090. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9091. }
  9092. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9093. };
  9094. Scene.prototype._activeMesh = function (mesh) {
  9095. if (mesh.skeleton && this.skeletonsEnabled) {
  9096. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9097. }
  9098. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9099. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9100. }
  9101. if (mesh && mesh.subMeshes) {
  9102. // Submeshes Octrees
  9103. var len;
  9104. var subMeshes;
  9105. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9106. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9107. len = intersections.length;
  9108. subMeshes = intersections.data;
  9109. }
  9110. else {
  9111. subMeshes = mesh.subMeshes;
  9112. len = subMeshes.length;
  9113. }
  9114. for (var subIndex = 0; subIndex < len; subIndex++) {
  9115. var subMesh = subMeshes[subIndex];
  9116. this._evaluateSubMesh(subMesh, mesh);
  9117. }
  9118. }
  9119. };
  9120. Scene.prototype.updateTransformMatrix = function (force) {
  9121. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9122. };
  9123. Scene.prototype._renderForCamera = function (camera) {
  9124. var engine = this._engine;
  9125. this.activeCamera = camera;
  9126. if (!this.activeCamera)
  9127. throw new Error("Active camera not set");
  9128. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9129. // Viewport
  9130. engine.setViewport(this.activeCamera.viewport);
  9131. // Camera
  9132. this._renderId++;
  9133. this.updateTransformMatrix();
  9134. if (this.beforeCameraRender) {
  9135. this.beforeCameraRender(this.activeCamera);
  9136. }
  9137. // Meshes
  9138. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9139. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9140. this._evaluateActiveMeshes();
  9141. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9142. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9143. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9144. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9145. skeleton.prepare();
  9146. }
  9147. // Render targets
  9148. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9149. if (this.renderTargetsEnabled) {
  9150. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9151. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9152. var renderTarget = this._renderTargets.data[renderIndex];
  9153. if (renderTarget._shouldRender()) {
  9154. this._renderId++;
  9155. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9156. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9157. }
  9158. }
  9159. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9160. this._renderId++;
  9161. }
  9162. if (this._renderTargets.length > 0) {
  9163. engine.restoreDefaultFramebuffer();
  9164. }
  9165. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9166. // Prepare Frame
  9167. this.postProcessManager._prepareFrame();
  9168. var beforeRenderDate = BABYLON.Tools.Now;
  9169. // Backgrounds
  9170. if (this.layers.length) {
  9171. engine.setDepthBuffer(false);
  9172. var layerIndex;
  9173. var layer;
  9174. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9175. layer = this.layers[layerIndex];
  9176. if (layer.isBackground) {
  9177. layer.render();
  9178. }
  9179. }
  9180. engine.setDepthBuffer(true);
  9181. }
  9182. // Render
  9183. BABYLON.Tools.StartPerformanceCounter("Main render");
  9184. this._renderingManager.render(null, null, true, true);
  9185. BABYLON.Tools.EndPerformanceCounter("Main render");
  9186. // Bounding boxes
  9187. this._boundingBoxRenderer.render();
  9188. // Lens flares
  9189. if (this.lensFlaresEnabled) {
  9190. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9191. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9192. this.lensFlareSystems[lensFlareSystemIndex].render();
  9193. }
  9194. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9195. }
  9196. // Foregrounds
  9197. if (this.layers.length) {
  9198. engine.setDepthBuffer(false);
  9199. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9200. layer = this.layers[layerIndex];
  9201. if (!layer.isBackground) {
  9202. layer.render();
  9203. }
  9204. }
  9205. engine.setDepthBuffer(true);
  9206. }
  9207. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9208. // Finalize frame
  9209. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9210. // Update camera
  9211. this.activeCamera._updateFromScene();
  9212. // Reset some special arrays
  9213. this._renderTargets.reset();
  9214. if (this.afterCameraRender) {
  9215. this.afterCameraRender(this.activeCamera);
  9216. }
  9217. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9218. };
  9219. Scene.prototype._processSubCameras = function (camera) {
  9220. if (camera.subCameras.length === 0) {
  9221. this._renderForCamera(camera);
  9222. return;
  9223. }
  9224. for (var index = 0; index < camera.subCameras.length; index++) {
  9225. this._renderForCamera(camera.subCameras[index]);
  9226. }
  9227. this.activeCamera = camera;
  9228. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9229. // Update camera
  9230. this.activeCamera._updateFromScene();
  9231. };
  9232. Scene.prototype._checkIntersections = function () {
  9233. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9234. var sourceMesh = this._meshesForIntersections.data[index];
  9235. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9236. var action = sourceMesh.actionManager.actions[actionIndex];
  9237. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9238. var parameters = action.getTriggerParameter();
  9239. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9240. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9241. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9242. if (areIntersecting && currentIntersectionInProgress === -1) {
  9243. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9244. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9245. sourceMesh._intersectionsInProgress.push(otherMesh);
  9246. }
  9247. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9248. sourceMesh._intersectionsInProgress.push(otherMesh);
  9249. }
  9250. }
  9251. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9252. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9253. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9254. if (indexOfOther > -1) {
  9255. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9256. }
  9257. }
  9258. }
  9259. }
  9260. }
  9261. };
  9262. Scene.prototype.render = function () {
  9263. var startDate = BABYLON.Tools.Now;
  9264. this._particlesDuration = 0;
  9265. this._spritesDuration = 0;
  9266. this._activeParticles = 0;
  9267. this._renderDuration = 0;
  9268. this._renderTargetsDuration = 0;
  9269. this._evaluateActiveMeshesDuration = 0;
  9270. this._totalVertices = 0;
  9271. this._activeVertices = 0;
  9272. this._activeBones = 0;
  9273. this.getEngine().resetDrawCalls();
  9274. this._meshesForIntersections.reset();
  9275. this.resetCachedMaterial();
  9276. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9277. // Actions
  9278. if (this.actionManager) {
  9279. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9280. }
  9281. //Simplification Queue
  9282. if (!this.simplificationQueue.running) {
  9283. this.simplificationQueue.executeNext();
  9284. }
  9285. // Before render
  9286. if (this.beforeRender) {
  9287. this.beforeRender();
  9288. }
  9289. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9290. this._onBeforeRenderCallbacks[callbackIndex]();
  9291. }
  9292. // Animations
  9293. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9294. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9295. this._animate();
  9296. // Physics
  9297. if (this._physicsEngine) {
  9298. BABYLON.Tools.StartPerformanceCounter("Physics");
  9299. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9300. BABYLON.Tools.EndPerformanceCounter("Physics");
  9301. }
  9302. // Customs render targets
  9303. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9304. var engine = this.getEngine();
  9305. var currentActiveCamera = this.activeCamera;
  9306. if (this.renderTargetsEnabled) {
  9307. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9308. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9309. var renderTarget = this.customRenderTargets[customIndex];
  9310. if (renderTarget._shouldRender()) {
  9311. this._renderId++;
  9312. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9313. if (!this.activeCamera)
  9314. throw new Error("Active camera not set");
  9315. // Viewport
  9316. engine.setViewport(this.activeCamera.viewport);
  9317. // Camera
  9318. this.updateTransformMatrix();
  9319. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9320. }
  9321. }
  9322. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9323. this._renderId++;
  9324. }
  9325. if (this.customRenderTargets.length > 0) {
  9326. engine.restoreDefaultFramebuffer();
  9327. }
  9328. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9329. this.activeCamera = currentActiveCamera;
  9330. // Procedural textures
  9331. if (this.proceduralTexturesEnabled) {
  9332. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9333. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9334. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9335. if (proceduralTexture._shouldRender()) {
  9336. proceduralTexture.render();
  9337. }
  9338. }
  9339. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9340. }
  9341. // Clear
  9342. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9343. // Shadows
  9344. if (this.shadowsEnabled) {
  9345. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9346. var light = this.lights[lightIndex];
  9347. var shadowGenerator = light.getShadowGenerator();
  9348. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9349. this._renderTargets.push(shadowGenerator.getShadowMap());
  9350. }
  9351. }
  9352. }
  9353. // Depth renderer
  9354. if (this._depthRenderer) {
  9355. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9356. }
  9357. // RenderPipeline
  9358. this.postProcessRenderPipelineManager.update();
  9359. // Multi-cameras?
  9360. if (this.activeCameras.length > 0) {
  9361. var currentRenderId = this._renderId;
  9362. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9363. this._renderId = currentRenderId;
  9364. this._processSubCameras(this.activeCameras[cameraIndex]);
  9365. }
  9366. }
  9367. else {
  9368. if (!this.activeCamera) {
  9369. throw new Error("No camera defined");
  9370. }
  9371. this._processSubCameras(this.activeCamera);
  9372. }
  9373. // Intersection checks
  9374. this._checkIntersections();
  9375. // Update the audio listener attached to the camera
  9376. this._updateAudioParameters();
  9377. // After render
  9378. if (this.afterRender) {
  9379. this.afterRender();
  9380. }
  9381. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9382. this._onAfterRenderCallbacks[callbackIndex]();
  9383. }
  9384. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9385. this._toBeDisposed.data[index].dispose();
  9386. this._toBeDisposed[index] = null;
  9387. }
  9388. this._toBeDisposed.reset();
  9389. if (this.dumpNextRenderTargets) {
  9390. this.dumpNextRenderTargets = false;
  9391. }
  9392. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9393. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9394. };
  9395. Scene.prototype._updateAudioParameters = function () {
  9396. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9397. return;
  9398. }
  9399. var listeningCamera;
  9400. var audioEngine = BABYLON.Engine.audioEngine;
  9401. if (this.activeCameras.length > 0) {
  9402. listeningCamera = this.activeCameras[0];
  9403. }
  9404. else {
  9405. listeningCamera = this.activeCamera;
  9406. }
  9407. if (listeningCamera && audioEngine.canUseWebAudio) {
  9408. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9409. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9410. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9411. cameraDirection.normalize();
  9412. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9413. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9414. var sound = this.mainSoundTrack.soundCollection[i];
  9415. if (sound.useCustomAttenuation) {
  9416. sound.updateDistanceFromListener();
  9417. }
  9418. }
  9419. for (i = 0; i < this.soundTracks.length; i++) {
  9420. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9421. sound = this.soundTracks[i].soundCollection[j];
  9422. if (sound.useCustomAttenuation) {
  9423. sound.updateDistanceFromListener();
  9424. }
  9425. }
  9426. }
  9427. }
  9428. };
  9429. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9430. // Audio
  9431. get: function () {
  9432. return this._audioEnabled;
  9433. },
  9434. set: function (value) {
  9435. this._audioEnabled = value;
  9436. if (this._audioEnabled) {
  9437. this._enableAudio();
  9438. }
  9439. else {
  9440. this._disableAudio();
  9441. }
  9442. },
  9443. enumerable: true,
  9444. configurable: true
  9445. });
  9446. Scene.prototype._disableAudio = function () {
  9447. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9448. this.mainSoundTrack.soundCollection[i].pause();
  9449. }
  9450. for (i = 0; i < this.soundTracks.length; i++) {
  9451. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9452. this.soundTracks[i].soundCollection[j].pause();
  9453. }
  9454. }
  9455. };
  9456. Scene.prototype._enableAudio = function () {
  9457. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9458. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9459. this.mainSoundTrack.soundCollection[i].play();
  9460. }
  9461. }
  9462. for (i = 0; i < this.soundTracks.length; i++) {
  9463. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9464. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9465. this.soundTracks[i].soundCollection[j].play();
  9466. }
  9467. }
  9468. }
  9469. };
  9470. Object.defineProperty(Scene.prototype, "headphone", {
  9471. get: function () {
  9472. return this._headphone;
  9473. },
  9474. set: function (value) {
  9475. this._headphone = value;
  9476. if (this._headphone) {
  9477. this._switchAudioModeForHeadphones();
  9478. }
  9479. else {
  9480. this._switchAudioModeForNormalSpeakers();
  9481. }
  9482. },
  9483. enumerable: true,
  9484. configurable: true
  9485. });
  9486. Scene.prototype._switchAudioModeForHeadphones = function () {
  9487. this.mainSoundTrack.switchPanningModelToHRTF();
  9488. for (var i = 0; i < this.soundTracks.length; i++) {
  9489. this.soundTracks[i].switchPanningModelToHRTF();
  9490. }
  9491. };
  9492. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9493. this.mainSoundTrack.switchPanningModelToEqualPower();
  9494. for (var i = 0; i < this.soundTracks.length; i++) {
  9495. this.soundTracks[i].switchPanningModelToEqualPower();
  9496. }
  9497. };
  9498. Scene.prototype.enableDepthRenderer = function () {
  9499. if (this._depthRenderer) {
  9500. return this._depthRenderer;
  9501. }
  9502. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9503. return this._depthRenderer;
  9504. };
  9505. Scene.prototype.disableDepthRenderer = function () {
  9506. if (!this._depthRenderer) {
  9507. return;
  9508. }
  9509. this._depthRenderer.dispose();
  9510. this._depthRenderer = null;
  9511. };
  9512. Scene.prototype.dispose = function () {
  9513. this.beforeRender = null;
  9514. this.afterRender = null;
  9515. this.skeletons = [];
  9516. this._boundingBoxRenderer.dispose();
  9517. if (this._depthRenderer) {
  9518. this._depthRenderer.dispose();
  9519. }
  9520. // Debug layer
  9521. this.debugLayer.hide();
  9522. // Events
  9523. if (this.onDispose) {
  9524. this.onDispose();
  9525. }
  9526. this._onBeforeRenderCallbacks = [];
  9527. this._onAfterRenderCallbacks = [];
  9528. this.detachControl();
  9529. // Release sounds & sounds tracks
  9530. this.disposeSounds();
  9531. // Detach cameras
  9532. var canvas = this._engine.getRenderingCanvas();
  9533. var index;
  9534. for (index = 0; index < this.cameras.length; index++) {
  9535. this.cameras[index].detachControl(canvas);
  9536. }
  9537. while (this.lights.length) {
  9538. this.lights[0].dispose();
  9539. }
  9540. while (this.meshes.length) {
  9541. this.meshes[0].dispose(true);
  9542. }
  9543. while (this.cameras.length) {
  9544. this.cameras[0].dispose();
  9545. }
  9546. while (this.materials.length) {
  9547. this.materials[0].dispose();
  9548. }
  9549. while (this.particleSystems.length) {
  9550. this.particleSystems[0].dispose();
  9551. }
  9552. while (this.spriteManagers.length) {
  9553. this.spriteManagers[0].dispose();
  9554. }
  9555. while (this.layers.length) {
  9556. this.layers[0].dispose();
  9557. }
  9558. while (this.textures.length) {
  9559. this.textures[0].dispose();
  9560. }
  9561. // Post-processes
  9562. this.postProcessManager.dispose();
  9563. // Physics
  9564. if (this._physicsEngine) {
  9565. this.disablePhysicsEngine();
  9566. }
  9567. // Remove from engine
  9568. index = this._engine.scenes.indexOf(this);
  9569. if (index > -1) {
  9570. this._engine.scenes.splice(index, 1);
  9571. }
  9572. this._engine.wipeCaches();
  9573. };
  9574. // Release sounds & sounds tracks
  9575. Scene.prototype.disposeSounds = function () {
  9576. this.mainSoundTrack.dispose();
  9577. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9578. this.soundTracks[scIndex].dispose();
  9579. }
  9580. };
  9581. // Collisions
  9582. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9583. if (excludedMesh === void 0) { excludedMesh = null; }
  9584. position.divideToRef(collider.radius, this._scaledPosition);
  9585. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9586. collider.retry = 0;
  9587. collider.initialVelocity = this._scaledVelocity;
  9588. collider.initialPosition = this._scaledPosition;
  9589. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9590. finalPosition.multiplyInPlace(collider.radius);
  9591. };
  9592. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9593. if (excludedMesh === void 0) { excludedMesh = null; }
  9594. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9595. if (collider.retry >= maximumRetry) {
  9596. finalPosition.copyFrom(position);
  9597. return;
  9598. }
  9599. collider._initialize(position, velocity, closeDistance);
  9600. for (var index = 0; index < this.meshes.length; index++) {
  9601. var mesh = this.meshes[index];
  9602. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9603. mesh._checkCollision(collider);
  9604. }
  9605. }
  9606. if (!collider.collisionFound) {
  9607. position.addToRef(velocity, finalPosition);
  9608. return;
  9609. }
  9610. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9611. collider._getResponse(position, velocity);
  9612. }
  9613. if (velocity.length() <= closeDistance) {
  9614. finalPosition.copyFrom(position);
  9615. return;
  9616. }
  9617. collider.retry++;
  9618. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9619. };
  9620. // Octrees
  9621. Scene.prototype.getWorldExtends = function () {
  9622. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9623. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9624. for (var index = 0; index < this.meshes.length; index++) {
  9625. var mesh = this.meshes[index];
  9626. mesh.computeWorldMatrix(true);
  9627. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9628. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9629. BABYLON.Tools.CheckExtends(minBox, min, max);
  9630. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9631. }
  9632. return {
  9633. min: min,
  9634. max: max
  9635. };
  9636. };
  9637. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9638. if (maxCapacity === void 0) { maxCapacity = 64; }
  9639. if (maxDepth === void 0) { maxDepth = 2; }
  9640. if (!this._selectionOctree) {
  9641. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9642. }
  9643. var worldExtends = this.getWorldExtends();
  9644. // Update octree
  9645. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9646. return this._selectionOctree;
  9647. };
  9648. // Picking
  9649. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9650. var engine = this._engine;
  9651. if (!camera) {
  9652. if (!this.activeCamera)
  9653. throw new Error("Active camera not set");
  9654. camera = this.activeCamera;
  9655. }
  9656. var cameraViewport = camera.viewport;
  9657. var viewport = cameraViewport.toGlobal(engine);
  9658. // Moving coordinates to local viewport world
  9659. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9660. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9661. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9662. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9663. };
  9664. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9665. var pickingInfo = null;
  9666. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9667. var mesh = this.meshes[meshIndex];
  9668. if (predicate) {
  9669. if (!predicate(mesh)) {
  9670. continue;
  9671. }
  9672. }
  9673. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9674. continue;
  9675. }
  9676. var world = mesh.getWorldMatrix();
  9677. var ray = rayFunction(world);
  9678. var result = mesh.intersects(ray, fastCheck);
  9679. if (!result || !result.hit)
  9680. continue;
  9681. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9682. continue;
  9683. pickingInfo = result;
  9684. if (fastCheck) {
  9685. break;
  9686. }
  9687. }
  9688. return pickingInfo || new BABYLON.PickingInfo();
  9689. };
  9690. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9691. var _this = this;
  9692. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9693. /// <param name="x">X position on screen</param>
  9694. /// <param name="y">Y position on screen</param>
  9695. /// <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>
  9696. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9697. /// <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>
  9698. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9699. };
  9700. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9701. var _this = this;
  9702. return this._internalPick(function (world) {
  9703. if (!_this._pickWithRayInverseMatrix) {
  9704. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9705. }
  9706. world.invertToRef(_this._pickWithRayInverseMatrix);
  9707. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9708. }, predicate, fastCheck);
  9709. };
  9710. Scene.prototype.setPointerOverMesh = function (mesh) {
  9711. if (this._pointerOverMesh === mesh) {
  9712. return;
  9713. }
  9714. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9715. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9716. }
  9717. this._pointerOverMesh = mesh;
  9718. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9719. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9720. }
  9721. };
  9722. Scene.prototype.getPointerOverMesh = function () {
  9723. return this._pointerOverMesh;
  9724. };
  9725. // Physics
  9726. Scene.prototype.getPhysicsEngine = function () {
  9727. return this._physicsEngine;
  9728. };
  9729. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9730. if (this._physicsEngine) {
  9731. return true;
  9732. }
  9733. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9734. if (!this._physicsEngine.isSupported()) {
  9735. this._physicsEngine = null;
  9736. return false;
  9737. }
  9738. this._physicsEngine._initialize(gravity);
  9739. return true;
  9740. };
  9741. Scene.prototype.disablePhysicsEngine = function () {
  9742. if (!this._physicsEngine) {
  9743. return;
  9744. }
  9745. this._physicsEngine.dispose();
  9746. this._physicsEngine = undefined;
  9747. };
  9748. Scene.prototype.isPhysicsEnabled = function () {
  9749. return this._physicsEngine !== undefined;
  9750. };
  9751. Scene.prototype.setGravity = function (gravity) {
  9752. if (!this._physicsEngine) {
  9753. return;
  9754. }
  9755. this._physicsEngine._setGravity(gravity);
  9756. };
  9757. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9758. if (parts.parts) {
  9759. options = parts;
  9760. parts = parts.parts;
  9761. }
  9762. if (!this._physicsEngine) {
  9763. return null;
  9764. }
  9765. for (var index = 0; index < parts.length; index++) {
  9766. var mesh = parts[index].mesh;
  9767. mesh._physicImpostor = parts[index].impostor;
  9768. mesh._physicsMass = options.mass / parts.length;
  9769. mesh._physicsFriction = options.friction;
  9770. mesh._physicRestitution = options.restitution;
  9771. }
  9772. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9773. };
  9774. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9775. for (var index = 0; index < compound.parts.length; index++) {
  9776. var mesh = compound.parts[index].mesh;
  9777. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9778. this._physicsEngine._unregisterMesh(mesh);
  9779. }
  9780. };
  9781. // Misc.
  9782. Scene.prototype.createDefaultCameraOrLight = function () {
  9783. // Light
  9784. if (this.lights.length === 0) {
  9785. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9786. }
  9787. // Camera
  9788. if (!this.activeCamera) {
  9789. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9790. // Compute position
  9791. var worldExtends = this.getWorldExtends();
  9792. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9793. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9794. camera.setTarget(worldCenter);
  9795. this.activeCamera = camera;
  9796. }
  9797. };
  9798. // Tags
  9799. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9800. if (tagsQuery === undefined) {
  9801. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9802. return list;
  9803. }
  9804. var listByTags = [];
  9805. forEach = forEach || (function (item) {
  9806. return;
  9807. });
  9808. for (var i in list) {
  9809. var item = list[i];
  9810. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9811. listByTags.push(item);
  9812. forEach(item);
  9813. }
  9814. }
  9815. return listByTags;
  9816. };
  9817. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9818. return this._getByTags(this.meshes, tagsQuery, forEach);
  9819. };
  9820. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9821. return this._getByTags(this.cameras, tagsQuery, forEach);
  9822. };
  9823. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9824. return this._getByTags(this.lights, tagsQuery, forEach);
  9825. };
  9826. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9827. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9828. };
  9829. // Statics
  9830. Scene._FOGMODE_NONE = 0;
  9831. Scene._FOGMODE_EXP = 1;
  9832. Scene._FOGMODE_EXP2 = 2;
  9833. Scene._FOGMODE_LINEAR = 3;
  9834. Scene.MinDeltaTime = 1.0;
  9835. Scene.MaxDeltaTime = 1000.0;
  9836. return Scene;
  9837. })();
  9838. BABYLON.Scene = Scene;
  9839. })(BABYLON || (BABYLON = {}));
  9840. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9841. (function (BABYLON) {
  9842. var VertexBuffer = (function () {
  9843. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9844. if (engine instanceof BABYLON.Mesh) {
  9845. this._engine = engine.getScene().getEngine();
  9846. }
  9847. else {
  9848. this._engine = engine;
  9849. }
  9850. this._updatable = updatable;
  9851. this._data = data;
  9852. if (!postponeInternalCreation) {
  9853. this.create();
  9854. }
  9855. this._kind = kind;
  9856. if (stride) {
  9857. this._strideSize = stride;
  9858. return;
  9859. }
  9860. switch (kind) {
  9861. case VertexBuffer.PositionKind:
  9862. this._strideSize = 3;
  9863. break;
  9864. case VertexBuffer.NormalKind:
  9865. this._strideSize = 3;
  9866. break;
  9867. case VertexBuffer.UVKind:
  9868. this._strideSize = 2;
  9869. break;
  9870. case VertexBuffer.UV2Kind:
  9871. this._strideSize = 2;
  9872. break;
  9873. case VertexBuffer.ColorKind:
  9874. this._strideSize = 4;
  9875. break;
  9876. case VertexBuffer.MatricesIndicesKind:
  9877. this._strideSize = 4;
  9878. break;
  9879. case VertexBuffer.MatricesWeightsKind:
  9880. this._strideSize = 4;
  9881. break;
  9882. }
  9883. }
  9884. // Properties
  9885. VertexBuffer.prototype.isUpdatable = function () {
  9886. return this._updatable;
  9887. };
  9888. VertexBuffer.prototype.getData = function () {
  9889. return this._data;
  9890. };
  9891. VertexBuffer.prototype.getBuffer = function () {
  9892. return this._buffer;
  9893. };
  9894. VertexBuffer.prototype.getStrideSize = function () {
  9895. return this._strideSize;
  9896. };
  9897. // Methods
  9898. VertexBuffer.prototype.create = function (data) {
  9899. if (!data && this._buffer) {
  9900. return; // nothing to do
  9901. }
  9902. data = data || this._data;
  9903. if (!this._buffer) {
  9904. if (this._updatable) {
  9905. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9906. }
  9907. else {
  9908. this._buffer = this._engine.createVertexBuffer(data);
  9909. }
  9910. }
  9911. if (this._updatable) {
  9912. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9913. this._data = data;
  9914. }
  9915. };
  9916. VertexBuffer.prototype.update = function (data) {
  9917. this.create(data);
  9918. };
  9919. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9920. if (!this._buffer) {
  9921. return;
  9922. }
  9923. if (this._updatable) {
  9924. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9925. this._data = null;
  9926. }
  9927. };
  9928. VertexBuffer.prototype.dispose = function () {
  9929. if (!this._buffer) {
  9930. return;
  9931. }
  9932. if (this._engine._releaseBuffer(this._buffer)) {
  9933. this._buffer = null;
  9934. }
  9935. };
  9936. Object.defineProperty(VertexBuffer, "PositionKind", {
  9937. get: function () {
  9938. return VertexBuffer._PositionKind;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(VertexBuffer, "NormalKind", {
  9944. get: function () {
  9945. return VertexBuffer._NormalKind;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(VertexBuffer, "UVKind", {
  9951. get: function () {
  9952. return VertexBuffer._UVKind;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9958. get: function () {
  9959. return VertexBuffer._UV2Kind;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(VertexBuffer, "ColorKind", {
  9965. get: function () {
  9966. return VertexBuffer._ColorKind;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9972. get: function () {
  9973. return VertexBuffer._MatricesIndicesKind;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9979. get: function () {
  9980. return VertexBuffer._MatricesWeightsKind;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. // Enums
  9986. VertexBuffer._PositionKind = "position";
  9987. VertexBuffer._NormalKind = "normal";
  9988. VertexBuffer._UVKind = "uv";
  9989. VertexBuffer._UV2Kind = "uv2";
  9990. VertexBuffer._ColorKind = "color";
  9991. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9992. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9993. return VertexBuffer;
  9994. })();
  9995. BABYLON.VertexBuffer = VertexBuffer;
  9996. })(BABYLON || (BABYLON = {}));
  9997. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9998. var BABYLON;
  9999. (function (BABYLON) {
  10000. var AbstractMesh = (function (_super) {
  10001. __extends(AbstractMesh, _super);
  10002. function AbstractMesh(name, scene) {
  10003. _super.call(this, name, scene);
  10004. // Properties
  10005. this.definedFacingForward = true; // orientation for POV movement & rotation
  10006. this.position = new BABYLON.Vector3(0, 0, 0);
  10007. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10008. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10009. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10010. this.visibility = 1.0;
  10011. this.alphaIndex = Number.MAX_VALUE;
  10012. this.infiniteDistance = false;
  10013. this.isVisible = true;
  10014. this.isPickable = true;
  10015. this.showBoundingBox = false;
  10016. this.showSubMeshesBoundingBox = false;
  10017. this.onDispose = null;
  10018. this.checkCollisions = false;
  10019. this.isBlocker = false;
  10020. this.renderingGroupId = 0;
  10021. this.receiveShadows = false;
  10022. this.renderOutline = false;
  10023. this.outlineColor = BABYLON.Color3.Red();
  10024. this.outlineWidth = 0.02;
  10025. this.renderOverlay = false;
  10026. this.overlayColor = BABYLON.Color3.Red();
  10027. this.overlayAlpha = 0.5;
  10028. this.hasVertexAlpha = false;
  10029. this.useVertexColors = true;
  10030. this.applyFog = true;
  10031. this.useOctreeForRenderingSelection = true;
  10032. this.useOctreeForPicking = true;
  10033. this.useOctreeForCollisions = true;
  10034. this.layerMask = 0x0FFFFFFF;
  10035. // Physics
  10036. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10037. // Collisions
  10038. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10039. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10040. this._collider = new BABYLON.Collider();
  10041. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10042. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10043. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10044. // Cache
  10045. this._localScaling = BABYLON.Matrix.Zero();
  10046. this._localRotation = BABYLON.Matrix.Zero();
  10047. this._localTranslation = BABYLON.Matrix.Zero();
  10048. this._localBillboard = BABYLON.Matrix.Zero();
  10049. this._localPivotScaling = BABYLON.Matrix.Zero();
  10050. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10051. this._localWorld = BABYLON.Matrix.Zero();
  10052. this._worldMatrix = BABYLON.Matrix.Zero();
  10053. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10054. this._absolutePosition = BABYLON.Vector3.Zero();
  10055. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10056. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10057. this._isDirty = false;
  10058. this._pivotMatrix = BABYLON.Matrix.Identity();
  10059. this._isDisposed = false;
  10060. this._renderId = 0;
  10061. this._intersectionsInProgress = new Array();
  10062. this._onAfterWorldMatrixUpdate = new Array();
  10063. scene.addMesh(this);
  10064. }
  10065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10066. get: function () {
  10067. return AbstractMesh._BILLBOARDMODE_NONE;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10073. get: function () {
  10074. return AbstractMesh._BILLBOARDMODE_X;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10080. get: function () {
  10081. return AbstractMesh._BILLBOARDMODE_Y;
  10082. },
  10083. enumerable: true,
  10084. configurable: true
  10085. });
  10086. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10087. get: function () {
  10088. return AbstractMesh._BILLBOARDMODE_Z;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10094. get: function () {
  10095. return AbstractMesh._BILLBOARDMODE_ALL;
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10101. // Methods
  10102. get: function () {
  10103. return false;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. AbstractMesh.prototype.getLOD = function (camera) {
  10109. return this;
  10110. };
  10111. AbstractMesh.prototype.getTotalVertices = function () {
  10112. return 0;
  10113. };
  10114. AbstractMesh.prototype.getIndices = function () {
  10115. return null;
  10116. };
  10117. AbstractMesh.prototype.getVerticesData = function (kind) {
  10118. return null;
  10119. };
  10120. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10121. return false;
  10122. };
  10123. AbstractMesh.prototype.getBoundingInfo = function () {
  10124. if (this._masterMesh) {
  10125. return this._masterMesh.getBoundingInfo();
  10126. }
  10127. if (!this._boundingInfo) {
  10128. this._updateBoundingInfo();
  10129. }
  10130. return this._boundingInfo;
  10131. };
  10132. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10133. get: function () {
  10134. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. AbstractMesh.prototype._preActivate = function () {
  10140. };
  10141. AbstractMesh.prototype._activate = function (renderId) {
  10142. this._renderId = renderId;
  10143. };
  10144. AbstractMesh.prototype.getWorldMatrix = function () {
  10145. if (this._masterMesh) {
  10146. return this._masterMesh.getWorldMatrix();
  10147. }
  10148. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10149. this.computeWorldMatrix();
  10150. }
  10151. return this._worldMatrix;
  10152. };
  10153. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10154. get: function () {
  10155. return this._worldMatrix;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10161. get: function () {
  10162. return this._absolutePosition;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10168. if (!this.rotationQuaternion) {
  10169. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10170. this.rotation = BABYLON.Vector3.Zero();
  10171. }
  10172. if (!space || space === 0 /* LOCAL */) {
  10173. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10174. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10175. }
  10176. else {
  10177. if (this.parent) {
  10178. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10179. invertParentWorldMatrix.invert();
  10180. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10181. }
  10182. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10183. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10184. }
  10185. };
  10186. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10187. var displacementVector = axis.scale(distance);
  10188. if (!space || space === 0 /* LOCAL */) {
  10189. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10190. this.setPositionWithLocalVector(tempV3);
  10191. }
  10192. else {
  10193. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10194. }
  10195. };
  10196. AbstractMesh.prototype.getAbsolutePosition = function () {
  10197. this.computeWorldMatrix();
  10198. return this._absolutePosition;
  10199. };
  10200. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10201. if (!absolutePosition) {
  10202. return;
  10203. }
  10204. var absolutePositionX;
  10205. var absolutePositionY;
  10206. var absolutePositionZ;
  10207. if (absolutePosition.x === undefined) {
  10208. if (arguments.length < 3) {
  10209. return;
  10210. }
  10211. absolutePositionX = arguments[0];
  10212. absolutePositionY = arguments[1];
  10213. absolutePositionZ = arguments[2];
  10214. }
  10215. else {
  10216. absolutePositionX = absolutePosition.x;
  10217. absolutePositionY = absolutePosition.y;
  10218. absolutePositionZ = absolutePosition.z;
  10219. }
  10220. if (this.parent) {
  10221. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10222. invertParentWorldMatrix.invert();
  10223. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10224. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10225. }
  10226. else {
  10227. this.position.x = absolutePositionX;
  10228. this.position.y = absolutePositionY;
  10229. this.position.z = absolutePositionZ;
  10230. }
  10231. };
  10232. // ================================== Point of View Movement =================================
  10233. /**
  10234. * Perform relative position change from the point of view of behind the front of the mesh.
  10235. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10236. * Supports definition of mesh facing forward or backward.
  10237. * @param {number} amountRight
  10238. * @param {number} amountUp
  10239. * @param {number} amountForward
  10240. */
  10241. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10242. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10243. };
  10244. /**
  10245. * Calculate relative position change from the point of view of behind the front of the mesh.
  10246. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10247. * Supports definition of mesh facing forward or backward.
  10248. * @param {number} amountRight
  10249. * @param {number} amountUp
  10250. * @param {number} amountForward
  10251. */
  10252. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10253. var rotMatrix = new BABYLON.Matrix();
  10254. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10255. rotQuaternion.toRotationMatrix(rotMatrix);
  10256. var translationDelta = BABYLON.Vector3.Zero();
  10257. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10259. return translationDelta;
  10260. };
  10261. // ================================== Point of View Rotation =================================
  10262. /**
  10263. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10264. * Supports definition of mesh facing forward or backward.
  10265. * @param {number} flipBack
  10266. * @param {number} twirlClockwise
  10267. * @param {number} tiltRight
  10268. */
  10269. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10270. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10271. };
  10272. /**
  10273. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10274. * Supports definition of mesh facing forward or backward.
  10275. * @param {number} flipBack
  10276. * @param {number} twirlClockwise
  10277. * @param {number} tiltRight
  10278. */
  10279. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10280. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10281. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10282. };
  10283. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10284. this._pivotMatrix = matrix;
  10285. this._cache.pivotMatrixUpdated = true;
  10286. };
  10287. AbstractMesh.prototype.getPivotMatrix = function () {
  10288. return this._pivotMatrix;
  10289. };
  10290. AbstractMesh.prototype._isSynchronized = function () {
  10291. if (this._isDirty) {
  10292. return false;
  10293. }
  10294. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10295. return false;
  10296. if (this._cache.pivotMatrixUpdated) {
  10297. return false;
  10298. }
  10299. if (this.infiniteDistance) {
  10300. return false;
  10301. }
  10302. if (!this._cache.position.equals(this.position))
  10303. return false;
  10304. if (this.rotationQuaternion) {
  10305. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10306. return false;
  10307. }
  10308. else {
  10309. if (!this._cache.rotation.equals(this.rotation))
  10310. return false;
  10311. }
  10312. if (!this._cache.scaling.equals(this.scaling))
  10313. return false;
  10314. return true;
  10315. };
  10316. AbstractMesh.prototype._initCache = function () {
  10317. _super.prototype._initCache.call(this);
  10318. this._cache.localMatrixUpdated = false;
  10319. this._cache.position = BABYLON.Vector3.Zero();
  10320. this._cache.scaling = BABYLON.Vector3.Zero();
  10321. this._cache.rotation = BABYLON.Vector3.Zero();
  10322. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10323. };
  10324. AbstractMesh.prototype.markAsDirty = function (property) {
  10325. if (property === "rotation") {
  10326. this.rotationQuaternion = null;
  10327. }
  10328. this._currentRenderId = Number.MAX_VALUE;
  10329. this._isDirty = true;
  10330. };
  10331. AbstractMesh.prototype._updateBoundingInfo = function () {
  10332. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10333. this._boundingInfo._update(this.worldMatrixFromCache);
  10334. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10335. };
  10336. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10337. if (!this.subMeshes) {
  10338. return;
  10339. }
  10340. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10341. var subMesh = this.subMeshes[subIndex];
  10342. subMesh.updateBoundingInfo(matrix);
  10343. }
  10344. };
  10345. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10346. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10347. return this._worldMatrix;
  10348. }
  10349. this._cache.position.copyFrom(this.position);
  10350. this._cache.scaling.copyFrom(this.scaling);
  10351. this._cache.pivotMatrixUpdated = false;
  10352. this._currentRenderId = this.getScene().getRenderId();
  10353. this._isDirty = false;
  10354. // Scaling
  10355. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10356. // Rotation
  10357. if (this.rotationQuaternion) {
  10358. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10359. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10360. }
  10361. else {
  10362. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10363. this._cache.rotation.copyFrom(this.rotation);
  10364. }
  10365. // Translation
  10366. if (this.infiniteDistance && !this.parent) {
  10367. var camera = this.getScene().activeCamera;
  10368. var cameraWorldMatrix = camera.getWorldMatrix();
  10369. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10370. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10371. }
  10372. else {
  10373. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10374. }
  10375. // Composing transformations
  10376. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10377. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10378. // Billboarding
  10379. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10380. var localPosition = this.position.clone();
  10381. var zero = this.getScene().activeCamera.position.clone();
  10382. if (this.parent && this.parent.position) {
  10383. localPosition.addInPlace(this.parent.position);
  10384. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10385. }
  10386. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10387. zero = this.getScene().activeCamera.position;
  10388. }
  10389. else {
  10390. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10391. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10392. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10393. zero.y = localPosition.y + 0.001;
  10394. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10395. zero.z = localPosition.z + 0.001;
  10396. }
  10397. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10398. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10399. this._localBillboard.invert();
  10400. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10401. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10402. }
  10403. // Local world
  10404. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10405. // Parent
  10406. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10407. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10408. }
  10409. else {
  10410. this._worldMatrix.copyFrom(this._localWorld);
  10411. }
  10412. // Bounding info
  10413. this._updateBoundingInfo();
  10414. // Absolute position
  10415. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10416. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10417. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10418. }
  10419. return this._worldMatrix;
  10420. };
  10421. /**
  10422. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10423. * @param func: callback function to add
  10424. */
  10425. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10426. this._onAfterWorldMatrixUpdate.push(func);
  10427. };
  10428. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10429. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10430. if (index > -1) {
  10431. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10432. }
  10433. };
  10434. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10435. this.computeWorldMatrix();
  10436. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10437. };
  10438. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10439. this.computeWorldMatrix();
  10440. var invLocalWorldMatrix = this._localWorld.clone();
  10441. invLocalWorldMatrix.invert();
  10442. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10443. };
  10444. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10445. this.computeWorldMatrix();
  10446. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10447. };
  10448. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10449. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10450. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10451. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10452. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10453. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10454. /// <returns>Mesh oriented towards targetMesh</returns>
  10455. yawCor = yawCor || 0; // default to zero if undefined
  10456. pitchCor = pitchCor || 0;
  10457. rollCor = rollCor || 0;
  10458. var dv = targetPoint.subtract(this.position);
  10459. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10460. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10461. var pitch = Math.atan2(dv.y, len);
  10462. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10463. };
  10464. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10465. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10466. return false;
  10467. }
  10468. return true;
  10469. };
  10470. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10471. if (!camera) {
  10472. camera = this.getScene().activeCamera;
  10473. }
  10474. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10475. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10476. return false;
  10477. }
  10478. return true;
  10479. };
  10480. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10481. if (!this._boundingInfo || !mesh._boundingInfo) {
  10482. return false;
  10483. }
  10484. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10485. };
  10486. AbstractMesh.prototype.intersectsPoint = function (point) {
  10487. if (!this._boundingInfo) {
  10488. return false;
  10489. }
  10490. return this._boundingInfo.intersectsPoint(point);
  10491. };
  10492. // Physics
  10493. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10494. var physicsEngine = this.getScene().getPhysicsEngine();
  10495. if (!physicsEngine) {
  10496. return;
  10497. }
  10498. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10499. if (impostor.impostor) {
  10500. // Old API
  10501. options = impostor;
  10502. impostor = impostor.impostor;
  10503. }
  10504. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10505. physicsEngine._unregisterMesh(this);
  10506. return;
  10507. }
  10508. if (!options) {
  10509. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10510. }
  10511. else {
  10512. if (!options.mass && options.mass !== 0)
  10513. options.mass = 0;
  10514. if (!options.friction && options.friction !== 0)
  10515. options.friction = 0.2;
  10516. if (!options.restitution && options.restitution !== 0)
  10517. options.restitution = 0.2;
  10518. }
  10519. this._physicImpostor = impostor;
  10520. this._physicsMass = options.mass;
  10521. this._physicsFriction = options.friction;
  10522. this._physicRestitution = options.restitution;
  10523. return physicsEngine._registerMesh(this, impostor, options);
  10524. };
  10525. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10526. if (!this._physicImpostor) {
  10527. return BABYLON.PhysicsEngine.NoImpostor;
  10528. }
  10529. return this._physicImpostor;
  10530. };
  10531. AbstractMesh.prototype.getPhysicsMass = function () {
  10532. if (!this._physicsMass) {
  10533. return 0;
  10534. }
  10535. return this._physicsMass;
  10536. };
  10537. AbstractMesh.prototype.getPhysicsFriction = function () {
  10538. if (!this._physicsFriction) {
  10539. return 0;
  10540. }
  10541. return this._physicsFriction;
  10542. };
  10543. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10544. if (!this._physicRestitution) {
  10545. return 0;
  10546. }
  10547. return this._physicRestitution;
  10548. };
  10549. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10550. if (!camera) {
  10551. camera = this.getScene().activeCamera;
  10552. }
  10553. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10554. };
  10555. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10556. if (!camera) {
  10557. camera = this.getScene().activeCamera;
  10558. }
  10559. return this.absolutePosition.subtract(camera.position).length();
  10560. };
  10561. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10562. if (!this._physicImpostor) {
  10563. return;
  10564. }
  10565. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10566. };
  10567. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10568. if (!this._physicImpostor) {
  10569. return;
  10570. }
  10571. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10572. };
  10573. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10574. if (!this._physicImpostor) {
  10575. return;
  10576. }
  10577. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10578. };
  10579. // Collisions
  10580. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10581. var globalPosition = this.getAbsolutePosition();
  10582. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10583. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10584. this._collider.radius = this.ellipsoid;
  10585. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10586. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10587. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10588. this.position.addInPlace(this._diffPositionForCollisions);
  10589. }
  10590. };
  10591. // Submeshes octree
  10592. /**
  10593. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10594. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10595. */
  10596. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10597. if (maxCapacity === void 0) { maxCapacity = 64; }
  10598. if (maxDepth === void 0) { maxDepth = 2; }
  10599. if (!this._submeshesOctree) {
  10600. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10601. }
  10602. this.computeWorldMatrix(true);
  10603. // Update octree
  10604. var bbox = this.getBoundingInfo().boundingBox;
  10605. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10606. return this._submeshesOctree;
  10607. };
  10608. // Collisions
  10609. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10610. this._generatePointsArray();
  10611. // Transformation
  10612. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10613. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10614. subMesh._lastColliderWorldVertices = [];
  10615. subMesh._trianglePlanes = [];
  10616. var start = subMesh.verticesStart;
  10617. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10618. for (var i = start; i < end; i++) {
  10619. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10620. }
  10621. }
  10622. // Collide
  10623. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10624. };
  10625. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10626. var subMeshes;
  10627. var len;
  10628. // Octrees
  10629. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10630. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10631. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10632. len = intersections.length;
  10633. subMeshes = intersections.data;
  10634. }
  10635. else {
  10636. subMeshes = this.subMeshes;
  10637. len = subMeshes.length;
  10638. }
  10639. for (var index = 0; index < len; index++) {
  10640. var subMesh = subMeshes[index];
  10641. // Bounding test
  10642. if (len > 1 && !subMesh._checkCollision(collider))
  10643. continue;
  10644. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10645. }
  10646. };
  10647. AbstractMesh.prototype._checkCollision = function (collider) {
  10648. // Bounding box test
  10649. if (!this._boundingInfo._checkCollision(collider))
  10650. return;
  10651. // Transformation matrix
  10652. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10653. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10654. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10655. };
  10656. // Picking
  10657. AbstractMesh.prototype._generatePointsArray = function () {
  10658. return false;
  10659. };
  10660. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10661. var pickingInfo = new BABYLON.PickingInfo();
  10662. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10663. return pickingInfo;
  10664. }
  10665. if (!this._generatePointsArray()) {
  10666. return pickingInfo;
  10667. }
  10668. var intersectInfo = null;
  10669. // Octrees
  10670. var subMeshes;
  10671. var len;
  10672. if (this._submeshesOctree && this.useOctreeForPicking) {
  10673. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10674. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10675. len = intersections.length;
  10676. subMeshes = intersections.data;
  10677. }
  10678. else {
  10679. subMeshes = this.subMeshes;
  10680. len = subMeshes.length;
  10681. }
  10682. for (var index = 0; index < len; index++) {
  10683. var subMesh = subMeshes[index];
  10684. // Bounding test
  10685. if (len > 1 && !subMesh.canIntersects(ray))
  10686. continue;
  10687. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10688. if (currentIntersectInfo) {
  10689. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10690. intersectInfo = currentIntersectInfo;
  10691. intersectInfo.subMeshId = index;
  10692. if (fastCheck) {
  10693. break;
  10694. }
  10695. }
  10696. }
  10697. }
  10698. if (intersectInfo) {
  10699. // Get picked point
  10700. var world = this.getWorldMatrix();
  10701. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10702. var direction = ray.direction.clone();
  10703. direction = direction.scale(intersectInfo.distance);
  10704. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10705. var pickedPoint = worldOrigin.add(worldDirection);
  10706. // Return result
  10707. pickingInfo.hit = true;
  10708. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10709. pickingInfo.pickedPoint = pickedPoint;
  10710. pickingInfo.pickedMesh = this;
  10711. pickingInfo.bu = intersectInfo.bu;
  10712. pickingInfo.bv = intersectInfo.bv;
  10713. pickingInfo.faceId = intersectInfo.faceId;
  10714. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10715. return pickingInfo;
  10716. }
  10717. return pickingInfo;
  10718. };
  10719. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10720. return null;
  10721. };
  10722. AbstractMesh.prototype.releaseSubMeshes = function () {
  10723. if (this.subMeshes) {
  10724. while (this.subMeshes.length) {
  10725. this.subMeshes[0].dispose();
  10726. }
  10727. }
  10728. else {
  10729. this.subMeshes = new Array();
  10730. }
  10731. };
  10732. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10733. var index;
  10734. // Physics
  10735. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10736. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10737. }
  10738. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10739. var other = this._intersectionsInProgress[index];
  10740. var pos = other._intersectionsInProgress.indexOf(this);
  10741. other._intersectionsInProgress.splice(pos, 1);
  10742. }
  10743. this._intersectionsInProgress = [];
  10744. // SubMeshes
  10745. this.releaseSubMeshes();
  10746. // Remove from scene
  10747. this.getScene().removeMesh(this);
  10748. if (!doNotRecurse) {
  10749. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10750. if (this.getScene().particleSystems[index].emitter === this) {
  10751. this.getScene().particleSystems[index].dispose();
  10752. index--;
  10753. }
  10754. }
  10755. // Children
  10756. var objects = this.getScene().meshes.slice(0);
  10757. for (index = 0; index < objects.length; index++) {
  10758. if (objects[index].parent === this) {
  10759. objects[index].dispose();
  10760. }
  10761. }
  10762. }
  10763. else {
  10764. for (index = 0; index < this.getScene().meshes.length; index++) {
  10765. var obj = this.getScene().meshes[index];
  10766. if (obj.parent === this) {
  10767. obj.parent = null;
  10768. obj.computeWorldMatrix(true);
  10769. }
  10770. }
  10771. }
  10772. this._onAfterWorldMatrixUpdate = [];
  10773. this._isDisposed = true;
  10774. // Callback
  10775. if (this.onDispose) {
  10776. this.onDispose();
  10777. }
  10778. };
  10779. // Statics
  10780. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10781. AbstractMesh._BILLBOARDMODE_X = 1;
  10782. AbstractMesh._BILLBOARDMODE_Y = 2;
  10783. AbstractMesh._BILLBOARDMODE_Z = 4;
  10784. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10785. return AbstractMesh;
  10786. })(BABYLON.Node);
  10787. BABYLON.AbstractMesh = AbstractMesh;
  10788. })(BABYLON || (BABYLON = {}));
  10789. //# sourceMappingURL=babylon.abstractMesh.js.map
  10790. var BABYLON;
  10791. (function (BABYLON) {
  10792. var _InstancesBatch = (function () {
  10793. function _InstancesBatch() {
  10794. this.mustReturn = false;
  10795. this.visibleInstances = new Array();
  10796. this.renderSelf = new Array();
  10797. }
  10798. return _InstancesBatch;
  10799. })();
  10800. BABYLON._InstancesBatch = _InstancesBatch;
  10801. var Mesh = (function (_super) {
  10802. __extends(Mesh, _super);
  10803. /**
  10804. * @constructor
  10805. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10806. * @param {Scene} scene - The scene to add this mesh to.
  10807. * @param {Node} parent - The parent of this mesh, if it has one
  10808. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10809. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10810. * When false, achieved by calling a clone(), also passing False.
  10811. * This will make creation of children, recursive.
  10812. */
  10813. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10814. if (parent === void 0) { parent = null; }
  10815. _super.call(this, name, scene);
  10816. // Members
  10817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10818. this.instances = new Array();
  10819. this._LODLevels = new Array();
  10820. this._onBeforeRenderCallbacks = new Array();
  10821. this._onAfterRenderCallbacks = new Array();
  10822. this._visibleInstances = {};
  10823. this._renderIdForInstances = new Array();
  10824. this._batchCache = new _InstancesBatch();
  10825. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10826. if (source) {
  10827. // Geometry
  10828. if (source._geometry) {
  10829. source._geometry.applyToMesh(this);
  10830. }
  10831. // Deep copy
  10832. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10833. // Material
  10834. this.material = source.material;
  10835. if (!doNotCloneChildren) {
  10836. for (var index = 0; index < scene.meshes.length; index++) {
  10837. var mesh = scene.meshes[index];
  10838. if (mesh.parent === source) {
  10839. // doNotCloneChildren is always going to be False
  10840. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10841. }
  10842. }
  10843. }
  10844. for (index = 0; index < scene.particleSystems.length; index++) {
  10845. var system = scene.particleSystems[index];
  10846. if (system.emitter === source) {
  10847. system.clone(system.name, this);
  10848. }
  10849. }
  10850. this.computeWorldMatrix(true);
  10851. }
  10852. // Parent
  10853. if (parent !== null) {
  10854. this.parent = parent;
  10855. }
  10856. }
  10857. Object.defineProperty(Mesh, "FRONTSIDE", {
  10858. get: function () {
  10859. return Mesh._FRONTSIDE;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Mesh, "BACKSIDE", {
  10865. get: function () {
  10866. return Mesh._BACKSIDE;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10872. get: function () {
  10873. return Mesh._DOUBLESIDE;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10879. get: function () {
  10880. return Mesh._DEFAULTSIDE;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10886. // Methods
  10887. get: function () {
  10888. return this._LODLevels.length > 0;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Mesh.prototype._sortLODLevels = function () {
  10894. this._LODLevels.sort(function (a, b) {
  10895. if (a.distance < b.distance) {
  10896. return 1;
  10897. }
  10898. if (a.distance > b.distance) {
  10899. return -1;
  10900. }
  10901. return 0;
  10902. });
  10903. };
  10904. /**
  10905. * Add a mesh as LOD level triggered at the given distance.
  10906. * @param {number} distance - the distance from the center of the object to show this level
  10907. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10908. * @return {BABYLON.Mesh} this mesh (for chaining)
  10909. */
  10910. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10911. if (mesh && mesh._masterMesh) {
  10912. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10913. return this;
  10914. }
  10915. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10916. this._LODLevels.push(level);
  10917. if (mesh) {
  10918. mesh._masterMesh = this;
  10919. }
  10920. this._sortLODLevels();
  10921. return this;
  10922. };
  10923. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10924. for (var index = 0; index < this._LODLevels.length; index++) {
  10925. var level = this._LODLevels[index];
  10926. if (level.distance === distance) {
  10927. return level.mesh;
  10928. }
  10929. }
  10930. return null;
  10931. };
  10932. /**
  10933. * Remove a mesh from the LOD array
  10934. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10935. * @return {BABYLON.Mesh} this mesh (for chaining)
  10936. */
  10937. Mesh.prototype.removeLODLevel = function (mesh) {
  10938. for (var index = 0; index < this._LODLevels.length; index++) {
  10939. if (this._LODLevels[index].mesh === mesh) {
  10940. this._LODLevels.splice(index, 1);
  10941. if (mesh) {
  10942. mesh._masterMesh = null;
  10943. }
  10944. }
  10945. }
  10946. this._sortLODLevels();
  10947. return this;
  10948. };
  10949. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10950. if (!this._LODLevels || this._LODLevels.length === 0) {
  10951. return this;
  10952. }
  10953. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10954. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10955. if (this.onLODLevelSelection) {
  10956. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  10957. }
  10958. return this;
  10959. }
  10960. for (var index = 0; index < this._LODLevels.length; index++) {
  10961. var level = this._LODLevels[index];
  10962. if (level.distance < distanceToCamera) {
  10963. if (level.mesh) {
  10964. level.mesh._preActivate();
  10965. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10966. }
  10967. if (this.onLODLevelSelection) {
  10968. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  10969. }
  10970. return level.mesh;
  10971. }
  10972. }
  10973. if (this.onLODLevelSelection) {
  10974. this.onLODLevelSelection(distanceToCamera, this, this);
  10975. }
  10976. return this;
  10977. };
  10978. Object.defineProperty(Mesh.prototype, "geometry", {
  10979. get: function () {
  10980. return this._geometry;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Mesh.prototype.getTotalVertices = function () {
  10986. if (!this._geometry) {
  10987. return 0;
  10988. }
  10989. return this._geometry.getTotalVertices();
  10990. };
  10991. Mesh.prototype.getVerticesData = function (kind) {
  10992. if (!this._geometry) {
  10993. return null;
  10994. }
  10995. return this._geometry.getVerticesData(kind);
  10996. };
  10997. Mesh.prototype.getVertexBuffer = function (kind) {
  10998. if (!this._geometry) {
  10999. return undefined;
  11000. }
  11001. return this._geometry.getVertexBuffer(kind);
  11002. };
  11003. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11004. if (!this._geometry) {
  11005. if (this._delayInfo) {
  11006. return this._delayInfo.indexOf(kind) !== -1;
  11007. }
  11008. return false;
  11009. }
  11010. return this._geometry.isVerticesDataPresent(kind);
  11011. };
  11012. Mesh.prototype.getVerticesDataKinds = function () {
  11013. if (!this._geometry) {
  11014. var result = [];
  11015. if (this._delayInfo) {
  11016. for (var kind in this._delayInfo) {
  11017. result.push(kind);
  11018. }
  11019. }
  11020. return result;
  11021. }
  11022. return this._geometry.getVerticesDataKinds();
  11023. };
  11024. Mesh.prototype.getTotalIndices = function () {
  11025. if (!this._geometry) {
  11026. return 0;
  11027. }
  11028. return this._geometry.getTotalIndices();
  11029. };
  11030. Mesh.prototype.getIndices = function () {
  11031. if (!this._geometry) {
  11032. return [];
  11033. }
  11034. return this._geometry.getIndices();
  11035. };
  11036. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11037. get: function () {
  11038. return this._masterMesh !== null && this._masterMesh !== undefined;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Mesh.prototype.isReady = function () {
  11044. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11045. return false;
  11046. }
  11047. return _super.prototype.isReady.call(this);
  11048. };
  11049. Mesh.prototype.isDisposed = function () {
  11050. return this._isDisposed;
  11051. };
  11052. // Methods
  11053. Mesh.prototype._preActivate = function () {
  11054. var sceneRenderId = this.getScene().getRenderId();
  11055. if (this._preActivateId === sceneRenderId) {
  11056. return;
  11057. }
  11058. this._preActivateId = sceneRenderId;
  11059. this._visibleInstances = null;
  11060. };
  11061. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11062. if (!this._visibleInstances) {
  11063. this._visibleInstances = {};
  11064. this._visibleInstances.defaultRenderId = renderId;
  11065. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11066. }
  11067. if (!this._visibleInstances[renderId]) {
  11068. this._visibleInstances[renderId] = new Array();
  11069. }
  11070. this._visibleInstances[renderId].push(instance);
  11071. };
  11072. Mesh.prototype.refreshBoundingInfo = function () {
  11073. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11074. if (data) {
  11075. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11076. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11077. }
  11078. if (this.subMeshes) {
  11079. for (var index = 0; index < this.subMeshes.length; index++) {
  11080. this.subMeshes[index].refreshBoundingInfo();
  11081. }
  11082. }
  11083. this._updateBoundingInfo();
  11084. };
  11085. Mesh.prototype._createGlobalSubMesh = function () {
  11086. var totalVertices = this.getTotalVertices();
  11087. if (!totalVertices || !this.getIndices()) {
  11088. return null;
  11089. }
  11090. this.releaseSubMeshes();
  11091. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11092. };
  11093. Mesh.prototype.subdivide = function (count) {
  11094. if (count < 1) {
  11095. return;
  11096. }
  11097. var totalIndices = this.getTotalIndices();
  11098. var subdivisionSize = (totalIndices / count) | 0;
  11099. var offset = 0;
  11100. while (subdivisionSize % 3 !== 0) {
  11101. subdivisionSize++;
  11102. }
  11103. this.releaseSubMeshes();
  11104. for (var index = 0; index < count; index++) {
  11105. if (offset >= totalIndices) {
  11106. break;
  11107. }
  11108. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11109. offset += subdivisionSize;
  11110. }
  11111. this.synchronizeInstances();
  11112. };
  11113. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11114. if (kind instanceof Array) {
  11115. var temp = data;
  11116. data = kind;
  11117. kind = temp;
  11118. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11119. }
  11120. if (!this._geometry) {
  11121. var vertexData = new BABYLON.VertexData();
  11122. vertexData.set(data, kind);
  11123. var scene = this.getScene();
  11124. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11125. }
  11126. else {
  11127. this._geometry.setVerticesData(kind, data, updatable, stride);
  11128. }
  11129. };
  11130. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11131. if (!this._geometry) {
  11132. return;
  11133. }
  11134. if (!makeItUnique) {
  11135. this._geometry.updateVerticesData(kind, data, updateExtends);
  11136. }
  11137. else {
  11138. this.makeGeometryUnique();
  11139. this.updateVerticesData(kind, data, updateExtends, false);
  11140. }
  11141. };
  11142. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11143. if (!this._geometry) {
  11144. return;
  11145. }
  11146. if (!makeItUnique) {
  11147. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11148. }
  11149. else {
  11150. this.makeGeometryUnique();
  11151. this.updateVerticesDataDirectly(kind, data, offset, false);
  11152. }
  11153. };
  11154. Mesh.prototype.makeGeometryUnique = function () {
  11155. if (!this._geometry) {
  11156. return;
  11157. }
  11158. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11159. geometry.applyToMesh(this);
  11160. };
  11161. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11162. if (!this._geometry) {
  11163. var vertexData = new BABYLON.VertexData();
  11164. vertexData.indices = indices;
  11165. var scene = this.getScene();
  11166. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11167. }
  11168. else {
  11169. this._geometry.setIndices(indices, totalVertices);
  11170. }
  11171. };
  11172. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11173. var engine = this.getScene().getEngine();
  11174. // Wireframe
  11175. var indexToBind;
  11176. switch (fillMode) {
  11177. case BABYLON.Material.PointFillMode:
  11178. indexToBind = null;
  11179. break;
  11180. case BABYLON.Material.WireFrameFillMode:
  11181. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11182. break;
  11183. default:
  11184. case BABYLON.Material.TriangleFillMode:
  11185. indexToBind = this._geometry.getIndexBuffer();
  11186. break;
  11187. }
  11188. // VBOs
  11189. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11190. };
  11191. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11192. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11193. return;
  11194. }
  11195. var engine = this.getScene().getEngine();
  11196. switch (fillMode) {
  11197. case BABYLON.Material.PointFillMode:
  11198. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11199. break;
  11200. case BABYLON.Material.WireFrameFillMode:
  11201. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11202. break;
  11203. default:
  11204. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11205. }
  11206. };
  11207. Mesh.prototype.registerBeforeRender = function (func) {
  11208. this._onBeforeRenderCallbacks.push(func);
  11209. };
  11210. Mesh.prototype.unregisterBeforeRender = function (func) {
  11211. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11212. if (index > -1) {
  11213. this._onBeforeRenderCallbacks.splice(index, 1);
  11214. }
  11215. };
  11216. Mesh.prototype.registerAfterRender = function (func) {
  11217. this._onAfterRenderCallbacks.push(func);
  11218. };
  11219. Mesh.prototype.unregisterAfterRender = function (func) {
  11220. var index = this._onAfterRenderCallbacks.indexOf(func);
  11221. if (index > -1) {
  11222. this._onAfterRenderCallbacks.splice(index, 1);
  11223. }
  11224. };
  11225. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11226. var scene = this.getScene();
  11227. this._batchCache.mustReturn = false;
  11228. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11229. this._batchCache.visibleInstances[subMeshId] = null;
  11230. if (this._visibleInstances) {
  11231. var currentRenderId = scene.getRenderId();
  11232. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11233. var selfRenderId = this._renderId;
  11234. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11235. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11236. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11237. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11238. }
  11239. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11240. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11241. this._batchCache.mustReturn = true;
  11242. return this._batchCache;
  11243. }
  11244. if (currentRenderId !== selfRenderId) {
  11245. this._batchCache.renderSelf[subMeshId] = false;
  11246. }
  11247. }
  11248. this._renderIdForInstances[subMeshId] = currentRenderId;
  11249. }
  11250. return this._batchCache;
  11251. };
  11252. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11253. var visibleInstances = batch.visibleInstances[subMesh._id];
  11254. var matricesCount = visibleInstances.length + 1;
  11255. var bufferSize = matricesCount * 16 * 4;
  11256. while (this._instancesBufferSize < bufferSize) {
  11257. this._instancesBufferSize *= 2;
  11258. }
  11259. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11260. if (this._worldMatricesInstancesBuffer) {
  11261. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11262. }
  11263. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11264. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11265. }
  11266. var offset = 0;
  11267. var instancesCount = 0;
  11268. var world = this.getWorldMatrix();
  11269. if (batch.renderSelf[subMesh._id]) {
  11270. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11271. offset += 16;
  11272. instancesCount++;
  11273. }
  11274. if (visibleInstances) {
  11275. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11276. var instance = visibleInstances[instanceIndex];
  11277. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11278. offset += 16;
  11279. instancesCount++;
  11280. }
  11281. }
  11282. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11283. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11284. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11285. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11286. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11287. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11288. this._draw(subMesh, fillMode, instancesCount);
  11289. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11290. };
  11291. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11292. var scene = this.getScene();
  11293. var engine = scene.getEngine();
  11294. if (hardwareInstancedRendering) {
  11295. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11296. }
  11297. else {
  11298. if (batch.renderSelf[subMesh._id]) {
  11299. // Draw
  11300. if (onBeforeDraw) {
  11301. onBeforeDraw(false, this.getWorldMatrix());
  11302. }
  11303. this._draw(subMesh, fillMode);
  11304. }
  11305. if (batch.visibleInstances[subMesh._id]) {
  11306. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11307. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11308. // World
  11309. var world = instance.getWorldMatrix();
  11310. if (onBeforeDraw) {
  11311. onBeforeDraw(true, world);
  11312. }
  11313. // Draw
  11314. this._draw(subMesh, fillMode);
  11315. }
  11316. }
  11317. }
  11318. };
  11319. Mesh.prototype.render = function (subMesh) {
  11320. var scene = this.getScene();
  11321. // Managing instances
  11322. var batch = this._getInstancesRenderList(subMesh._id);
  11323. if (batch.mustReturn) {
  11324. return;
  11325. }
  11326. // Checking geometry state
  11327. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11328. return;
  11329. }
  11330. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11331. this._onBeforeRenderCallbacks[callbackIndex](this);
  11332. }
  11333. var engine = scene.getEngine();
  11334. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11335. // Material
  11336. var effectiveMaterial = subMesh.getMaterial();
  11337. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11338. return;
  11339. }
  11340. // Outline - step 1
  11341. var savedDepthWrite = engine.getDepthWrite();
  11342. if (this.renderOutline) {
  11343. engine.setDepthWrite(false);
  11344. scene.getOutlineRenderer().render(subMesh, batch);
  11345. engine.setDepthWrite(savedDepthWrite);
  11346. }
  11347. effectiveMaterial._preBind();
  11348. var effect = effectiveMaterial.getEffect();
  11349. // Bind
  11350. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11351. this._bind(subMesh, effect, fillMode);
  11352. var world = this.getWorldMatrix();
  11353. effectiveMaterial.bind(world, this);
  11354. // Draw
  11355. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11356. if (isInstance) {
  11357. effectiveMaterial.bindOnlyWorldMatrix(world);
  11358. }
  11359. });
  11360. // Unbind
  11361. effectiveMaterial.unbind();
  11362. // Outline - step 2
  11363. if (this.renderOutline && savedDepthWrite) {
  11364. engine.setDepthWrite(true);
  11365. engine.setColorWrite(false);
  11366. scene.getOutlineRenderer().render(subMesh, batch);
  11367. engine.setColorWrite(true);
  11368. }
  11369. // Overlay
  11370. if (this.renderOverlay) {
  11371. var currentMode = engine.getAlphaMode();
  11372. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11373. scene.getOutlineRenderer().render(subMesh, batch, true);
  11374. engine.setAlphaMode(currentMode);
  11375. }
  11376. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11377. this._onAfterRenderCallbacks[callbackIndex](this);
  11378. }
  11379. };
  11380. Mesh.prototype.getEmittedParticleSystems = function () {
  11381. var results = new Array();
  11382. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11383. var particleSystem = this.getScene().particleSystems[index];
  11384. if (particleSystem.emitter === this) {
  11385. results.push(particleSystem);
  11386. }
  11387. }
  11388. return results;
  11389. };
  11390. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11391. var results = new Array();
  11392. var descendants = this.getDescendants();
  11393. descendants.push(this);
  11394. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11395. var particleSystem = this.getScene().particleSystems[index];
  11396. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11397. results.push(particleSystem);
  11398. }
  11399. }
  11400. return results;
  11401. };
  11402. Mesh.prototype.getChildren = function () {
  11403. var results = [];
  11404. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11405. var mesh = this.getScene().meshes[index];
  11406. if (mesh.parent === this) {
  11407. results.push(mesh);
  11408. }
  11409. }
  11410. return results;
  11411. };
  11412. Mesh.prototype._checkDelayState = function () {
  11413. var _this = this;
  11414. var that = this;
  11415. var scene = this.getScene();
  11416. if (this._geometry) {
  11417. this._geometry.load(scene);
  11418. }
  11419. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11420. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11421. scene._addPendingData(that);
  11422. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11423. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11424. if (data instanceof ArrayBuffer) {
  11425. _this._delayLoadingFunction(data, _this);
  11426. }
  11427. else {
  11428. _this._delayLoadingFunction(JSON.parse(data), _this);
  11429. }
  11430. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11431. scene._removePendingData(_this);
  11432. }, function () {
  11433. }, scene.database, getBinaryData);
  11434. }
  11435. };
  11436. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11437. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11438. return false;
  11439. }
  11440. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11441. return false;
  11442. }
  11443. this._checkDelayState();
  11444. return true;
  11445. };
  11446. Mesh.prototype.setMaterialByID = function (id) {
  11447. var materials = this.getScene().materials;
  11448. for (var index = 0; index < materials.length; index++) {
  11449. if (materials[index].id === id) {
  11450. this.material = materials[index];
  11451. return;
  11452. }
  11453. }
  11454. // Multi
  11455. var multiMaterials = this.getScene().multiMaterials;
  11456. for (index = 0; index < multiMaterials.length; index++) {
  11457. if (multiMaterials[index].id === id) {
  11458. this.material = multiMaterials[index];
  11459. return;
  11460. }
  11461. }
  11462. };
  11463. Mesh.prototype.getAnimatables = function () {
  11464. var results = [];
  11465. if (this.material) {
  11466. results.push(this.material);
  11467. }
  11468. if (this.skeleton) {
  11469. results.push(this.skeleton);
  11470. }
  11471. return results;
  11472. };
  11473. // Geometry
  11474. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11475. // Position
  11476. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11477. return;
  11478. }
  11479. this._resetPointsArrayCache();
  11480. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11481. var temp = [];
  11482. for (var index = 0; index < data.length; index += 3) {
  11483. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11484. }
  11485. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11486. // Normals
  11487. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11488. return;
  11489. }
  11490. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11491. for (index = 0; index < data.length; index += 3) {
  11492. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11493. }
  11494. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11495. };
  11496. // Cache
  11497. Mesh.prototype._resetPointsArrayCache = function () {
  11498. this._positions = null;
  11499. };
  11500. Mesh.prototype._generatePointsArray = function () {
  11501. if (this._positions)
  11502. return true;
  11503. this._positions = [];
  11504. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11505. if (!data) {
  11506. return false;
  11507. }
  11508. for (var index = 0; index < data.length; index += 3) {
  11509. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11510. }
  11511. return true;
  11512. };
  11513. // Clone
  11514. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11515. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11516. };
  11517. // Dispose
  11518. Mesh.prototype.dispose = function (doNotRecurse) {
  11519. if (this._geometry) {
  11520. this._geometry.releaseForMesh(this, true);
  11521. }
  11522. // Instances
  11523. if (this._worldMatricesInstancesBuffer) {
  11524. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11525. this._worldMatricesInstancesBuffer = null;
  11526. }
  11527. while (this.instances.length) {
  11528. this.instances[0].dispose();
  11529. }
  11530. _super.prototype.dispose.call(this, doNotRecurse);
  11531. };
  11532. // Geometric tools
  11533. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11534. var _this = this;
  11535. var scene = this.getScene();
  11536. var onload = function (img) {
  11537. // Getting height map data
  11538. var canvas = document.createElement("canvas");
  11539. var context = canvas.getContext("2d");
  11540. var heightMapWidth = img.width;
  11541. var heightMapHeight = img.height;
  11542. canvas.width = heightMapWidth;
  11543. canvas.height = heightMapHeight;
  11544. context.drawImage(img, 0, 0);
  11545. // Create VertexData from map data
  11546. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11547. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11548. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11549. //execute success callback, if set
  11550. if (onSuccess) {
  11551. onSuccess(_this);
  11552. }
  11553. };
  11554. BABYLON.Tools.LoadImage(url, onload, function () {
  11555. }, scene.database);
  11556. };
  11557. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11558. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11559. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11560. return;
  11561. }
  11562. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11563. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11564. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11565. var position = BABYLON.Vector3.Zero();
  11566. var normal = BABYLON.Vector3.Zero();
  11567. var uv = BABYLON.Vector2.Zero();
  11568. for (var index = 0; index < positions.length; index += 3) {
  11569. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11570. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11571. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11572. // Compute height
  11573. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11574. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11575. var pos = (u + v * heightMapWidth) * 4;
  11576. var r = buffer[pos] / 255.0;
  11577. var g = buffer[pos + 1] / 255.0;
  11578. var b = buffer[pos + 2] / 255.0;
  11579. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11580. normal.normalize();
  11581. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11582. position = position.add(normal);
  11583. position.toArray(positions, index);
  11584. }
  11585. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11586. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11587. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11588. };
  11589. Mesh.prototype.convertToFlatShadedMesh = function () {
  11590. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11591. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11592. var kinds = this.getVerticesDataKinds();
  11593. var vbs = [];
  11594. var data = [];
  11595. var newdata = [];
  11596. var updatableNormals = false;
  11597. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11598. var kind = kinds[kindIndex];
  11599. var vertexBuffer = this.getVertexBuffer(kind);
  11600. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11601. updatableNormals = vertexBuffer.isUpdatable();
  11602. kinds.splice(kindIndex, 1);
  11603. kindIndex--;
  11604. continue;
  11605. }
  11606. vbs[kind] = vertexBuffer;
  11607. data[kind] = vbs[kind].getData();
  11608. newdata[kind] = [];
  11609. }
  11610. // Save previous submeshes
  11611. var previousSubmeshes = this.subMeshes.slice(0);
  11612. var indices = this.getIndices();
  11613. var totalIndices = this.getTotalIndices();
  11614. for (var index = 0; index < totalIndices; index++) {
  11615. var vertexIndex = indices[index];
  11616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11617. kind = kinds[kindIndex];
  11618. var stride = vbs[kind].getStrideSize();
  11619. for (var offset = 0; offset < stride; offset++) {
  11620. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11621. }
  11622. }
  11623. }
  11624. // Updating faces & normal
  11625. var normals = [];
  11626. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11627. for (index = 0; index < totalIndices; index += 3) {
  11628. indices[index] = index;
  11629. indices[index + 1] = index + 1;
  11630. indices[index + 2] = index + 2;
  11631. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11632. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11633. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11634. var p1p2 = p1.subtract(p2);
  11635. var p3p2 = p3.subtract(p2);
  11636. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11637. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11638. normals.push(normal.x);
  11639. normals.push(normal.y);
  11640. normals.push(normal.z);
  11641. }
  11642. }
  11643. this.setIndices(indices);
  11644. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11645. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11646. kind = kinds[kindIndex];
  11647. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11648. }
  11649. // Updating submeshes
  11650. this.releaseSubMeshes();
  11651. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11652. var previousOne = previousSubmeshes[submeshIndex];
  11653. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11654. }
  11655. this.synchronizeInstances();
  11656. };
  11657. // Instances
  11658. Mesh.prototype.createInstance = function (name) {
  11659. return new BABYLON.InstancedMesh(name, this);
  11660. };
  11661. Mesh.prototype.synchronizeInstances = function () {
  11662. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11663. var instance = this.instances[instanceIndex];
  11664. instance._syncSubMeshes();
  11665. }
  11666. };
  11667. /**
  11668. * Simplify the mesh according to the given array of settings.
  11669. * Function will return immediately and will simplify async.
  11670. * @param settings a collection of simplification settings.
  11671. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11672. * @param type the type of simplification to run.
  11673. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11674. */
  11675. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11676. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11677. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11678. this.getScene().simplificationQueue.addTask({
  11679. settings: settings,
  11680. parallelProcessing: parallelProcessing,
  11681. mesh: this,
  11682. simplificationType: simplificationType,
  11683. successCallback: successCallback
  11684. });
  11685. };
  11686. /**
  11687. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11688. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11689. * This should be used together with the simplification to avoid disappearing triangles.
  11690. * @param successCallback an optional success callback to be called after the optimization finished.
  11691. */
  11692. Mesh.prototype.optimizeIndices = function (successCallback) {
  11693. var _this = this;
  11694. var indices = this.getIndices();
  11695. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11696. var vectorPositions = [];
  11697. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11698. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11699. }
  11700. var dupes = [];
  11701. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11702. var realPos = vectorPositions.length - 1 - iteration;
  11703. var testedPosition = vectorPositions[realPos];
  11704. for (var j = 0; j < realPos; ++j) {
  11705. var againstPosition = vectorPositions[j];
  11706. if (testedPosition.equals(againstPosition)) {
  11707. dupes[realPos] = j;
  11708. break;
  11709. }
  11710. }
  11711. }, function () {
  11712. for (var i = 0; i < indices.length; ++i) {
  11713. indices[i] = dupes[indices[i]] || indices[i];
  11714. }
  11715. //indices are now reordered
  11716. var originalSubMeshes = _this.subMeshes.slice(0);
  11717. _this.setIndices(indices);
  11718. _this.subMeshes = originalSubMeshes;
  11719. if (successCallback) {
  11720. successCallback(_this);
  11721. }
  11722. });
  11723. };
  11724. // Statics
  11725. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11726. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11727. var ribbon = new Mesh(name, scene);
  11728. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11729. vertexData.applyToMesh(ribbon, updatable);
  11730. return ribbon;
  11731. };
  11732. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11733. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11734. var box = new Mesh(name, scene);
  11735. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11736. vertexData.applyToMesh(box, updatable);
  11737. return box;
  11738. };
  11739. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11740. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11741. var sphere = new Mesh(name, scene);
  11742. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11743. vertexData.applyToMesh(sphere, updatable);
  11744. return sphere;
  11745. };
  11746. // Cylinder and cone (Code inspired by SharpDX.org)
  11747. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11748. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11749. // subdivisions is a new parameter, we need to support old signature
  11750. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11751. if (scene !== undefined) {
  11752. updatable = scene;
  11753. }
  11754. scene = subdivisions;
  11755. subdivisions = 1;
  11756. }
  11757. var cylinder = new Mesh(name, scene);
  11758. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11759. vertexData.applyToMesh(cylinder, updatable);
  11760. return cylinder;
  11761. };
  11762. // Torus (Code from SharpDX.org)
  11763. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11764. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11765. var torus = new Mesh(name, scene);
  11766. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11767. vertexData.applyToMesh(torus, updatable);
  11768. return torus;
  11769. };
  11770. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11771. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11772. var torusKnot = new Mesh(name, scene);
  11773. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11774. vertexData.applyToMesh(torusKnot, updatable);
  11775. return torusKnot;
  11776. };
  11777. // Lines
  11778. Mesh.CreateLines = function (name, points, scene, updatable) {
  11779. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11780. var vertexData = BABYLON.VertexData.CreateLines(points);
  11781. vertexData.applyToMesh(lines, updatable);
  11782. return lines;
  11783. };
  11784. // Extrusion
  11785. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11786. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11787. scale = scale || 1;
  11788. rotation = rotation || 0;
  11789. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11790. return extruded;
  11791. };
  11792. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11793. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11794. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11795. return extrudedCustom;
  11796. };
  11797. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11798. var path3D = new BABYLON.Path3D(curve);
  11799. var tangents = path3D.getTangents();
  11800. var normals = path3D.getNormals();
  11801. var binormals = path3D.getBinormals();
  11802. var distances = path3D.getDistances();
  11803. var shapePaths = new Array();
  11804. var angle = 0;
  11805. var returnScale = function (i, distance) {
  11806. return scale;
  11807. };
  11808. var returnRotation = function (i, distance) {
  11809. return rotation;
  11810. };
  11811. var rotate = custom ? rotateFunction : returnRotation;
  11812. var scl = custom ? scaleFunction : returnScale;
  11813. for (var i = 0; i < curve.length; i++) {
  11814. var shapePath = new Array();
  11815. var angleStep = rotate(i, distances[i]);
  11816. var scaleRatio = scl(i, distances[i]);
  11817. for (var p = 0; p < shape.length; p++) {
  11818. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11819. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11820. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11821. shapePath.push(rotated);
  11822. }
  11823. shapePaths.push(shapePath);
  11824. angle += angleStep;
  11825. }
  11826. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11827. return extrudedGeneric;
  11828. };
  11829. // Plane & ground
  11830. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11831. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11832. var plane = new Mesh(name, scene);
  11833. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11834. vertexData.applyToMesh(plane, updatable);
  11835. return plane;
  11836. };
  11837. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11838. var ground = new BABYLON.GroundMesh(name, scene);
  11839. ground._setReady(false);
  11840. ground._subdivisions = subdivisions;
  11841. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11842. vertexData.applyToMesh(ground, updatable);
  11843. ground._setReady(true);
  11844. return ground;
  11845. };
  11846. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11847. var tiledGround = new Mesh(name, scene);
  11848. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11849. vertexData.applyToMesh(tiledGround, updatable);
  11850. return tiledGround;
  11851. };
  11852. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11853. var ground = new BABYLON.GroundMesh(name, scene);
  11854. ground._subdivisions = subdivisions;
  11855. ground._setReady(false);
  11856. var onload = function (img) {
  11857. // Getting height map data
  11858. var canvas = document.createElement("canvas");
  11859. var context = canvas.getContext("2d");
  11860. var heightMapWidth = img.width;
  11861. var heightMapHeight = img.height;
  11862. canvas.width = heightMapWidth;
  11863. canvas.height = heightMapHeight;
  11864. context.drawImage(img, 0, 0);
  11865. // Create VertexData from map data
  11866. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11867. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11868. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11869. vertexData.applyToMesh(ground, updatable);
  11870. ground._setReady(true);
  11871. //execute ready callback, if set
  11872. if (onReady) {
  11873. onReady(ground);
  11874. }
  11875. };
  11876. BABYLON.Tools.LoadImage(url, onload, function () {
  11877. }, scene.database);
  11878. return ground;
  11879. };
  11880. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11881. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11882. var path3D = new BABYLON.Path3D(path);
  11883. var tangents = path3D.getTangents();
  11884. var normals = path3D.getNormals();
  11885. var distances = path3D.getDistances();
  11886. var pi2 = Math.PI * 2;
  11887. var step = pi2 / tesselation;
  11888. var returnRadius = function (i, distance) { return radius; };
  11889. var radiusFunctionFinal = radiusFunction || returnRadius;
  11890. var circlePaths = new Array();
  11891. var circlePath;
  11892. var rad;
  11893. var normal;
  11894. var rotated;
  11895. var rotationMatrix;
  11896. for (var i = 0; i < path.length; i++) {
  11897. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11898. circlePath = Array(); // current circle array
  11899. normal = normals[i]; // current normal
  11900. for (var ang = 0; ang < pi2; ang += step) {
  11901. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11902. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11903. circlePath.push(rotated);
  11904. }
  11905. circlePaths.push(circlePath);
  11906. }
  11907. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11908. return tube;
  11909. };
  11910. // Decals
  11911. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  11912. if (angle === void 0) { angle = 0; }
  11913. var indices = sourceMesh.getIndices();
  11914. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11915. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11916. // Getting correct rotation
  11917. if (!normal) {
  11918. var target = new BABYLON.Vector3(0, 0, 1);
  11919. var camera = sourceMesh.getScene().activeCamera;
  11920. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  11921. normal = camera.globalPosition.subtract(cameraWorldTarget);
  11922. }
  11923. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  11924. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  11925. var pitch = Math.atan2(normal.y, len);
  11926. // Matrix
  11927. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  11928. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  11929. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  11930. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  11931. var vertexData = new BABYLON.VertexData();
  11932. vertexData.indices = [];
  11933. vertexData.positions = [];
  11934. vertexData.normals = [];
  11935. vertexData.uvs = [];
  11936. var currentVertexDataIndex = 0;
  11937. var extractDecalVector3 = function (indexId) {
  11938. var vertexId = indices[indexId];
  11939. var result = new BABYLON.PositionNormalVertex();
  11940. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  11941. // Send vector to decal local world
  11942. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  11943. // Get normal
  11944. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  11945. return result;
  11946. };
  11947. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  11948. var clip = function (vertices, axis) {
  11949. if (vertices.length === 0) {
  11950. return vertices;
  11951. }
  11952. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  11953. var clipVertices = function (v0, v1) {
  11954. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  11955. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  11956. };
  11957. var result = new Array();
  11958. for (var index = 0; index < vertices.length; index += 3) {
  11959. var v1Out;
  11960. var v2Out;
  11961. var v3Out;
  11962. var total = 0;
  11963. var nV1, nV2, nV3, nV4;
  11964. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  11965. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  11966. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  11967. v1Out = d1 > 0;
  11968. v2Out = d2 > 0;
  11969. v3Out = d3 > 0;
  11970. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  11971. switch (total) {
  11972. case 0:
  11973. result.push(vertices[index]);
  11974. result.push(vertices[index + 1]);
  11975. result.push(vertices[index + 2]);
  11976. break;
  11977. case 1:
  11978. if (v1Out) {
  11979. nV1 = vertices[index + 1];
  11980. nV2 = vertices[index + 2];
  11981. nV3 = clipVertices(vertices[index], nV1);
  11982. nV4 = clipVertices(vertices[index], nV2);
  11983. }
  11984. if (v2Out) {
  11985. nV1 = vertices[index];
  11986. nV2 = vertices[index + 2];
  11987. nV3 = clipVertices(vertices[index + 1], nV1);
  11988. nV4 = clipVertices(vertices[index + 1], nV2);
  11989. result.push(nV3);
  11990. result.push(nV2.clone());
  11991. result.push(nV1.clone());
  11992. result.push(nV2.clone());
  11993. result.push(nV3.clone());
  11994. result.push(nV4);
  11995. break;
  11996. }
  11997. if (v3Out) {
  11998. nV1 = vertices[index];
  11999. nV2 = vertices[index + 1];
  12000. nV3 = clipVertices(vertices[index + 2], nV1);
  12001. nV4 = clipVertices(vertices[index + 2], nV2);
  12002. }
  12003. result.push(nV1.clone());
  12004. result.push(nV2.clone());
  12005. result.push(nV3);
  12006. result.push(nV4);
  12007. result.push(nV3.clone());
  12008. result.push(nV2.clone());
  12009. break;
  12010. case 2:
  12011. if (!v1Out) {
  12012. nV1 = vertices[index].clone();
  12013. nV2 = clipVertices(nV1, vertices[index + 1]);
  12014. nV3 = clipVertices(nV1, vertices[index + 2]);
  12015. result.push(nV1);
  12016. result.push(nV2);
  12017. result.push(nV3);
  12018. }
  12019. if (!v2Out) {
  12020. nV1 = vertices[index + 1].clone();
  12021. nV2 = clipVertices(nV1, vertices[index + 2]);
  12022. nV3 = clipVertices(nV1, vertices[index]);
  12023. result.push(nV1);
  12024. result.push(nV2);
  12025. result.push(nV3);
  12026. }
  12027. if (!v3Out) {
  12028. nV1 = vertices[index + 2].clone();
  12029. nV2 = clipVertices(nV1, vertices[index]);
  12030. nV3 = clipVertices(nV1, vertices[index + 1]);
  12031. result.push(nV1);
  12032. result.push(nV2);
  12033. result.push(nV3);
  12034. }
  12035. break;
  12036. case 3:
  12037. break;
  12038. }
  12039. }
  12040. return result;
  12041. };
  12042. for (var index = 0; index < indices.length; index += 3) {
  12043. var faceVertices = new Array();
  12044. faceVertices.push(extractDecalVector3(index));
  12045. faceVertices.push(extractDecalVector3(index + 1));
  12046. faceVertices.push(extractDecalVector3(index + 2));
  12047. // Clip
  12048. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12049. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12052. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12053. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12054. if (faceVertices.length === 0) {
  12055. continue;
  12056. }
  12057. // Add UVs and get back to world
  12058. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12059. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12060. var vertex = faceVertices[vIndex];
  12061. vertexData.indices.push(currentVertexDataIndex);
  12062. //Vector3.TransformCoordinates(vertex.position, localRotationMatrix).toArray(vertexData.positions, currentVertexDataIndex * 3);
  12063. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12064. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12065. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12066. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12067. currentVertexDataIndex++;
  12068. }
  12069. }
  12070. // Return mesh
  12071. var decal = new Mesh(name, sourceMesh.getScene());
  12072. vertexData.applyToMesh(decal);
  12073. decal.position = position.clone();
  12074. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12075. return decal;
  12076. };
  12077. // Tools
  12078. Mesh.MinMax = function (meshes) {
  12079. var minVector = null;
  12080. var maxVector = null;
  12081. for (var i in meshes) {
  12082. var mesh = meshes[i];
  12083. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12084. if (!minVector) {
  12085. minVector = boundingBox.minimumWorld;
  12086. maxVector = boundingBox.maximumWorld;
  12087. continue;
  12088. }
  12089. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12090. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12091. }
  12092. return {
  12093. min: minVector,
  12094. max: maxVector
  12095. };
  12096. };
  12097. Mesh.Center = function (meshesOrMinMaxVector) {
  12098. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12099. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12100. };
  12101. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12102. if (disposeSource === void 0) { disposeSource = true; }
  12103. var source = meshes[0];
  12104. var material = source.material;
  12105. var scene = source.getScene();
  12106. if (!allow32BitsIndices) {
  12107. var totalVertices = 0;
  12108. for (var index = 0; index < meshes.length; index++) {
  12109. totalVertices += meshes[index].getTotalVertices();
  12110. if (totalVertices > 65536) {
  12111. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12112. return null;
  12113. }
  12114. }
  12115. }
  12116. // Merge
  12117. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12118. vertexData.transform(source.getWorldMatrix());
  12119. for (index = 1; index < meshes.length; index++) {
  12120. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12121. otherVertexData.transform(meshes[index].getWorldMatrix());
  12122. vertexData.merge(otherVertexData);
  12123. }
  12124. var newMesh = new Mesh(source.name + "_merged", scene);
  12125. vertexData.applyToMesh(newMesh);
  12126. // Setting properties
  12127. newMesh.material = material;
  12128. newMesh.checkCollisions = source.checkCollisions;
  12129. // Cleaning
  12130. if (disposeSource) {
  12131. for (index = 0; index < meshes.length; index++) {
  12132. meshes[index].dispose();
  12133. }
  12134. }
  12135. return newMesh;
  12136. };
  12137. // Consts
  12138. Mesh._FRONTSIDE = 0;
  12139. Mesh._BACKSIDE = 1;
  12140. Mesh._DOUBLESIDE = 2;
  12141. Mesh._DEFAULTSIDE = 0;
  12142. return Mesh;
  12143. })(BABYLON.AbstractMesh);
  12144. BABYLON.Mesh = Mesh;
  12145. })(BABYLON || (BABYLON = {}));
  12146. //# sourceMappingURL=babylon.mesh.js.map
  12147. var BABYLON;
  12148. (function (BABYLON) {
  12149. var GroundMesh = (function (_super) {
  12150. __extends(GroundMesh, _super);
  12151. function GroundMesh(name, scene) {
  12152. _super.call(this, name, scene);
  12153. this.generateOctree = false;
  12154. this._worldInverse = new BABYLON.Matrix();
  12155. }
  12156. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12157. get: function () {
  12158. return this._subdivisions;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. GroundMesh.prototype.optimize = function (chunksCount) {
  12164. this.subdivide(this._subdivisions);
  12165. this.createOrUpdateSubmeshesOctree(32);
  12166. };
  12167. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12168. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12169. this.getWorldMatrix().invertToRef(this._worldInverse);
  12170. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12171. var pickInfo = this.intersects(ray);
  12172. if (pickInfo.hit) {
  12173. return pickInfo.pickedPoint.y;
  12174. }
  12175. return 0;
  12176. };
  12177. return GroundMesh;
  12178. })(BABYLON.Mesh);
  12179. BABYLON.GroundMesh = GroundMesh;
  12180. })(BABYLON || (BABYLON = {}));
  12181. //# sourceMappingURL=babylon.groundMesh.js.map
  12182. var BABYLON;
  12183. (function (BABYLON) {
  12184. /**
  12185. * Creates an instance based on a source mesh.
  12186. */
  12187. var InstancedMesh = (function (_super) {
  12188. __extends(InstancedMesh, _super);
  12189. function InstancedMesh(name, source) {
  12190. _super.call(this, name, source.getScene());
  12191. source.instances.push(this);
  12192. this._sourceMesh = source;
  12193. this.position.copyFrom(source.position);
  12194. this.rotation.copyFrom(source.rotation);
  12195. this.scaling.copyFrom(source.scaling);
  12196. if (source.rotationQuaternion) {
  12197. this.rotationQuaternion = source.rotationQuaternion.clone();
  12198. }
  12199. this.infiniteDistance = source.infiniteDistance;
  12200. this.setPivotMatrix(source.getPivotMatrix());
  12201. this.refreshBoundingInfo();
  12202. this._syncSubMeshes();
  12203. }
  12204. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12205. // Methods
  12206. get: function () {
  12207. return this._sourceMesh.receiveShadows;
  12208. },
  12209. enumerable: true,
  12210. configurable: true
  12211. });
  12212. Object.defineProperty(InstancedMesh.prototype, "material", {
  12213. get: function () {
  12214. return this._sourceMesh.material;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12220. get: function () {
  12221. return this._sourceMesh.visibility;
  12222. },
  12223. enumerable: true,
  12224. configurable: true
  12225. });
  12226. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12227. get: function () {
  12228. return this._sourceMesh.skeleton;
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. InstancedMesh.prototype.getTotalVertices = function () {
  12234. return this._sourceMesh.getTotalVertices();
  12235. };
  12236. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12237. get: function () {
  12238. return this._sourceMesh;
  12239. },
  12240. enumerable: true,
  12241. configurable: true
  12242. });
  12243. InstancedMesh.prototype.getVerticesData = function (kind) {
  12244. return this._sourceMesh.getVerticesData(kind);
  12245. };
  12246. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12247. return this._sourceMesh.isVerticesDataPresent(kind);
  12248. };
  12249. InstancedMesh.prototype.getIndices = function () {
  12250. return this._sourceMesh.getIndices();
  12251. };
  12252. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12253. get: function () {
  12254. return this._sourceMesh._positions;
  12255. },
  12256. enumerable: true,
  12257. configurable: true
  12258. });
  12259. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12260. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12261. if (data) {
  12262. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12263. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12264. }
  12265. this._updateBoundingInfo();
  12266. };
  12267. InstancedMesh.prototype._preActivate = function () {
  12268. if (this._currentLOD) {
  12269. this._currentLOD._preActivate();
  12270. }
  12271. };
  12272. InstancedMesh.prototype._activate = function (renderId) {
  12273. if (this._currentLOD) {
  12274. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12275. }
  12276. };
  12277. InstancedMesh.prototype.getLOD = function (camera) {
  12278. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12279. if (this._currentLOD === this.sourceMesh) {
  12280. return this;
  12281. }
  12282. return this._currentLOD;
  12283. };
  12284. InstancedMesh.prototype._syncSubMeshes = function () {
  12285. this.releaseSubMeshes();
  12286. if (this._sourceMesh.subMeshes) {
  12287. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12288. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12289. }
  12290. }
  12291. };
  12292. InstancedMesh.prototype._generatePointsArray = function () {
  12293. return this._sourceMesh._generatePointsArray();
  12294. };
  12295. // Clone
  12296. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12297. var result = this._sourceMesh.createInstance(name);
  12298. // Deep copy
  12299. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12300. // Bounding info
  12301. this.refreshBoundingInfo();
  12302. // Parent
  12303. if (newParent) {
  12304. result.parent = newParent;
  12305. }
  12306. if (!doNotCloneChildren) {
  12307. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12308. var mesh = this.getScene().meshes[index];
  12309. if (mesh.parent === this) {
  12310. mesh.clone(mesh.name, result);
  12311. }
  12312. }
  12313. }
  12314. result.computeWorldMatrix(true);
  12315. return result;
  12316. };
  12317. // Dispoe
  12318. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12319. // Remove from mesh
  12320. var index = this._sourceMesh.instances.indexOf(this);
  12321. this._sourceMesh.instances.splice(index, 1);
  12322. _super.prototype.dispose.call(this, doNotRecurse);
  12323. };
  12324. return InstancedMesh;
  12325. })(BABYLON.AbstractMesh);
  12326. BABYLON.InstancedMesh = InstancedMesh;
  12327. })(BABYLON || (BABYLON = {}));
  12328. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12329. (function (BABYLON) {
  12330. var SubMesh = (function () {
  12331. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12332. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12333. this.materialIndex = materialIndex;
  12334. this.verticesStart = verticesStart;
  12335. this.verticesCount = verticesCount;
  12336. this.indexStart = indexStart;
  12337. this.indexCount = indexCount;
  12338. this._renderId = 0;
  12339. this._mesh = mesh;
  12340. this._renderingMesh = renderingMesh || mesh;
  12341. mesh.subMeshes.push(this);
  12342. this._id = mesh.subMeshes.length - 1;
  12343. if (createBoundingBox) {
  12344. this.refreshBoundingInfo();
  12345. mesh.computeWorldMatrix(true);
  12346. }
  12347. }
  12348. SubMesh.prototype.getBoundingInfo = function () {
  12349. return this._boundingInfo;
  12350. };
  12351. SubMesh.prototype.getMesh = function () {
  12352. return this._mesh;
  12353. };
  12354. SubMesh.prototype.getRenderingMesh = function () {
  12355. return this._renderingMesh;
  12356. };
  12357. SubMesh.prototype.getMaterial = function () {
  12358. var rootMaterial = this._renderingMesh.material;
  12359. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12360. var multiMaterial = rootMaterial;
  12361. return multiMaterial.getSubMaterial(this.materialIndex);
  12362. }
  12363. if (!rootMaterial) {
  12364. return this._mesh.getScene().defaultMaterial;
  12365. }
  12366. return rootMaterial;
  12367. };
  12368. // Methods
  12369. SubMesh.prototype.refreshBoundingInfo = function () {
  12370. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12371. if (!data) {
  12372. this._boundingInfo = this._mesh._boundingInfo;
  12373. return;
  12374. }
  12375. var indices = this._renderingMesh.getIndices();
  12376. var extend;
  12377. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12378. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12379. }
  12380. else {
  12381. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12382. }
  12383. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12384. };
  12385. SubMesh.prototype._checkCollision = function (collider) {
  12386. return this._boundingInfo._checkCollision(collider);
  12387. };
  12388. SubMesh.prototype.updateBoundingInfo = function (world) {
  12389. if (!this._boundingInfo) {
  12390. this.refreshBoundingInfo();
  12391. }
  12392. this._boundingInfo._update(world);
  12393. };
  12394. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12395. return this._boundingInfo.isInFrustum(frustumPlanes);
  12396. };
  12397. SubMesh.prototype.render = function () {
  12398. this._renderingMesh.render(this);
  12399. };
  12400. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12401. if (!this._linesIndexBuffer) {
  12402. var linesIndices = [];
  12403. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12404. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12405. }
  12406. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12407. this.linesIndexCount = linesIndices.length;
  12408. }
  12409. return this._linesIndexBuffer;
  12410. };
  12411. SubMesh.prototype.canIntersects = function (ray) {
  12412. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12413. };
  12414. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12415. var intersectInfo = null;
  12416. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12417. var p0 = positions[indices[index]];
  12418. var p1 = positions[indices[index + 1]];
  12419. var p2 = positions[indices[index + 2]];
  12420. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12421. if (currentIntersectInfo) {
  12422. if (currentIntersectInfo.distance < 0) {
  12423. continue;
  12424. }
  12425. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12426. intersectInfo = currentIntersectInfo;
  12427. intersectInfo.faceId = index / 3;
  12428. if (fastCheck) {
  12429. break;
  12430. }
  12431. }
  12432. }
  12433. }
  12434. return intersectInfo;
  12435. };
  12436. // Clone
  12437. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12438. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12439. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12440. return result;
  12441. };
  12442. // Dispose
  12443. SubMesh.prototype.dispose = function () {
  12444. if (this._linesIndexBuffer) {
  12445. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12446. this._linesIndexBuffer = null;
  12447. }
  12448. // Remove from mesh
  12449. var index = this._mesh.subMeshes.indexOf(this);
  12450. this._mesh.subMeshes.splice(index, 1);
  12451. };
  12452. // Statics
  12453. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12454. var minVertexIndex = Number.MAX_VALUE;
  12455. var maxVertexIndex = -Number.MAX_VALUE;
  12456. renderingMesh = renderingMesh || mesh;
  12457. var indices = renderingMesh.getIndices();
  12458. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12459. var vertexIndex = indices[index];
  12460. if (vertexIndex < minVertexIndex)
  12461. minVertexIndex = vertexIndex;
  12462. if (vertexIndex > maxVertexIndex)
  12463. maxVertexIndex = vertexIndex;
  12464. }
  12465. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12466. };
  12467. return SubMesh;
  12468. })();
  12469. BABYLON.SubMesh = SubMesh;
  12470. })(BABYLON || (BABYLON = {}));
  12471. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12472. (function (BABYLON) {
  12473. var BaseTexture = (function () {
  12474. function BaseTexture(scene) {
  12475. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12476. this.hasAlpha = false;
  12477. this.getAlphaFromRGB = false;
  12478. this.level = 1;
  12479. this.isCube = false;
  12480. this.isRenderTarget = false;
  12481. this.animations = new Array();
  12482. this.coordinatesIndex = 0;
  12483. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12484. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12485. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12486. this.anisotropicFilteringLevel = 4;
  12487. this._scene = scene;
  12488. this._scene.textures.push(this);
  12489. }
  12490. BaseTexture.prototype.getScene = function () {
  12491. return this._scene;
  12492. };
  12493. BaseTexture.prototype.getTextureMatrix = function () {
  12494. return null;
  12495. };
  12496. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12497. return null;
  12498. };
  12499. BaseTexture.prototype.getInternalTexture = function () {
  12500. return this._texture;
  12501. };
  12502. BaseTexture.prototype.isReady = function () {
  12503. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12504. return true;
  12505. }
  12506. if (this._texture) {
  12507. return this._texture.isReady;
  12508. }
  12509. return false;
  12510. };
  12511. BaseTexture.prototype.getSize = function () {
  12512. if (this._texture._width) {
  12513. return { width: this._texture._width, height: this._texture._height };
  12514. }
  12515. if (this._texture._size) {
  12516. return { width: this._texture._size, height: this._texture._size };
  12517. }
  12518. return { width: 0, height: 0 };
  12519. };
  12520. BaseTexture.prototype.getBaseSize = function () {
  12521. if (!this.isReady())
  12522. return { width: 0, height: 0 };
  12523. if (this._texture._size) {
  12524. return { width: this._texture._size, height: this._texture._size };
  12525. }
  12526. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12527. };
  12528. BaseTexture.prototype.scale = function (ratio) {
  12529. };
  12530. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12531. get: function () {
  12532. return false;
  12533. },
  12534. enumerable: true,
  12535. configurable: true
  12536. });
  12537. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12538. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12539. for (var index = 0; index < texturesCache.length; index++) {
  12540. var texturesCacheEntry = texturesCache[index];
  12541. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12542. texturesCache.splice(index, 1);
  12543. return;
  12544. }
  12545. }
  12546. };
  12547. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12548. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12549. for (var index = 0; index < texturesCache.length; index++) {
  12550. var texturesCacheEntry = texturesCache[index];
  12551. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12552. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12553. texturesCacheEntry.references++;
  12554. return texturesCacheEntry;
  12555. }
  12556. }
  12557. }
  12558. return null;
  12559. };
  12560. BaseTexture.prototype.delayLoad = function () {
  12561. };
  12562. BaseTexture.prototype.releaseInternalTexture = function () {
  12563. if (!this._texture) {
  12564. return;
  12565. }
  12566. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12567. this._texture.references--;
  12568. // Final reference ?
  12569. if (this._texture.references === 0) {
  12570. var index = texturesCache.indexOf(this._texture);
  12571. texturesCache.splice(index, 1);
  12572. this._scene.getEngine()._releaseTexture(this._texture);
  12573. delete this._texture;
  12574. }
  12575. };
  12576. BaseTexture.prototype.clone = function () {
  12577. return null;
  12578. };
  12579. BaseTexture.prototype.dispose = function () {
  12580. // Remove from scene
  12581. var index = this._scene.textures.indexOf(this);
  12582. if (index >= 0) {
  12583. this._scene.textures.splice(index, 1);
  12584. }
  12585. if (this._texture === undefined) {
  12586. return;
  12587. }
  12588. this.releaseInternalTexture();
  12589. // Callback
  12590. if (this.onDispose) {
  12591. this.onDispose();
  12592. }
  12593. };
  12594. return BaseTexture;
  12595. })();
  12596. BABYLON.BaseTexture = BaseTexture;
  12597. })(BABYLON || (BABYLON = {}));
  12598. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12599. (function (BABYLON) {
  12600. var RenderingGroup = (function () {
  12601. function RenderingGroup(index, scene) {
  12602. this.index = index;
  12603. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12604. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12605. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12606. this._scene = scene;
  12607. }
  12608. RenderingGroup.prototype.render = function (customRenderFunction) {
  12609. if (customRenderFunction) {
  12610. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12611. return true;
  12612. }
  12613. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12614. return false;
  12615. }
  12616. var engine = this._scene.getEngine();
  12617. // Opaque
  12618. var subIndex;
  12619. var submesh;
  12620. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12621. submesh = this._opaqueSubMeshes.data[subIndex];
  12622. submesh.render();
  12623. }
  12624. // Alpha test
  12625. engine.setAlphaTesting(true);
  12626. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12627. submesh = this._alphaTestSubMeshes.data[subIndex];
  12628. submesh.render();
  12629. }
  12630. engine.setAlphaTesting(false);
  12631. // Transparent
  12632. if (this._transparentSubMeshes.length) {
  12633. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12634. submesh = this._transparentSubMeshes.data[subIndex];
  12635. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12636. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12637. }
  12638. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12639. sortedArray.sort(function (a, b) {
  12640. // Alpha index first
  12641. if (a._alphaIndex > b._alphaIndex) {
  12642. return 1;
  12643. }
  12644. if (a._alphaIndex < b._alphaIndex) {
  12645. return -1;
  12646. }
  12647. // Then distance to camera
  12648. if (a._distanceToCamera < b._distanceToCamera) {
  12649. return 1;
  12650. }
  12651. if (a._distanceToCamera > b._distanceToCamera) {
  12652. return -1;
  12653. }
  12654. return 0;
  12655. });
  12656. // Rendering
  12657. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12658. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12659. submesh = sortedArray[subIndex];
  12660. submesh.render();
  12661. }
  12662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12663. }
  12664. return true;
  12665. };
  12666. RenderingGroup.prototype.prepare = function () {
  12667. this._opaqueSubMeshes.reset();
  12668. this._transparentSubMeshes.reset();
  12669. this._alphaTestSubMeshes.reset();
  12670. };
  12671. RenderingGroup.prototype.dispatch = function (subMesh) {
  12672. var material = subMesh.getMaterial();
  12673. var mesh = subMesh.getMesh();
  12674. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12675. this._transparentSubMeshes.push(subMesh);
  12676. }
  12677. else if (material.needAlphaTesting()) {
  12678. this._alphaTestSubMeshes.push(subMesh);
  12679. }
  12680. else {
  12681. this._opaqueSubMeshes.push(subMesh); // Opaque
  12682. }
  12683. };
  12684. return RenderingGroup;
  12685. })();
  12686. BABYLON.RenderingGroup = RenderingGroup;
  12687. })(BABYLON || (BABYLON = {}));
  12688. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12689. (function (BABYLON) {
  12690. var RenderingManager = (function () {
  12691. function RenderingManager(scene) {
  12692. this._renderingGroups = new Array();
  12693. this._scene = scene;
  12694. }
  12695. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12696. if (this._scene._activeParticleSystems.length === 0) {
  12697. return;
  12698. }
  12699. // Particles
  12700. var beforeParticlesDate = BABYLON.Tools.Now;
  12701. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12702. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12703. if (particleSystem.renderingGroupId !== index) {
  12704. continue;
  12705. }
  12706. this._clearDepthBuffer();
  12707. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12708. this._scene._activeParticles += particleSystem.render();
  12709. }
  12710. }
  12711. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12712. };
  12713. RenderingManager.prototype._renderSprites = function (index) {
  12714. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12715. return;
  12716. }
  12717. // Sprites
  12718. var beforeSpritessDate = BABYLON.Tools.Now;
  12719. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12720. var spriteManager = this._scene.spriteManagers[id];
  12721. if (spriteManager.renderingGroupId === index) {
  12722. this._clearDepthBuffer();
  12723. spriteManager.render();
  12724. }
  12725. }
  12726. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12727. };
  12728. RenderingManager.prototype._clearDepthBuffer = function () {
  12729. if (this._depthBufferAlreadyCleaned) {
  12730. return;
  12731. }
  12732. this._scene.getEngine().clear(0, false, true);
  12733. this._depthBufferAlreadyCleaned = true;
  12734. };
  12735. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12736. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12737. this._depthBufferAlreadyCleaned = false;
  12738. var renderingGroup = this._renderingGroups[index];
  12739. var needToStepBack = false;
  12740. if (renderingGroup) {
  12741. this._clearDepthBuffer();
  12742. if (!renderingGroup.render(customRenderFunction)) {
  12743. this._renderingGroups.splice(index, 1);
  12744. needToStepBack = true;
  12745. }
  12746. }
  12747. if (renderSprites) {
  12748. this._renderSprites(index);
  12749. }
  12750. if (renderParticles) {
  12751. this._renderParticles(index, activeMeshes);
  12752. }
  12753. if (needToStepBack) {
  12754. index--;
  12755. }
  12756. }
  12757. };
  12758. RenderingManager.prototype.reset = function () {
  12759. for (var index in this._renderingGroups) {
  12760. var renderingGroup = this._renderingGroups[index];
  12761. renderingGroup.prepare();
  12762. }
  12763. };
  12764. RenderingManager.prototype.dispatch = function (subMesh) {
  12765. var mesh = subMesh.getMesh();
  12766. var renderingGroupId = mesh.renderingGroupId || 0;
  12767. if (!this._renderingGroups[renderingGroupId]) {
  12768. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12769. }
  12770. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12771. };
  12772. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12773. return RenderingManager;
  12774. })();
  12775. BABYLON.RenderingManager = RenderingManager;
  12776. })(BABYLON || (BABYLON = {}));
  12777. //# sourceMappingURL=babylon.renderingManager.js.map
  12778. var BABYLON;
  12779. (function (BABYLON) {
  12780. var Texture = (function (_super) {
  12781. __extends(Texture, _super);
  12782. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12783. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12784. if (onLoad === void 0) { onLoad = null; }
  12785. if (onError === void 0) { onError = null; }
  12786. if (buffer === void 0) { buffer = null; }
  12787. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12788. _super.call(this, scene);
  12789. this.uOffset = 0;
  12790. this.vOffset = 0;
  12791. this.uScale = 1.0;
  12792. this.vScale = 1.0;
  12793. this.uAng = 0;
  12794. this.vAng = 0;
  12795. this.wAng = 0;
  12796. this.name = url;
  12797. this.url = url;
  12798. this._noMipmap = noMipmap;
  12799. this._invertY = invertY;
  12800. this._samplingMode = samplingMode;
  12801. this._buffer = buffer;
  12802. this._deleteBuffer = deleteBuffer;
  12803. if (!url) {
  12804. return;
  12805. }
  12806. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12807. if (!this._texture) {
  12808. if (!scene.useDelayedTextureLoading) {
  12809. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12810. if (deleteBuffer) {
  12811. delete this._buffer;
  12812. }
  12813. }
  12814. else {
  12815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12816. }
  12817. }
  12818. }
  12819. Texture.prototype.delayLoad = function () {
  12820. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12821. return;
  12822. }
  12823. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12824. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12825. if (!this._texture) {
  12826. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12827. if (this._deleteBuffer) {
  12828. delete this._buffer;
  12829. }
  12830. }
  12831. };
  12832. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12833. if (!this._texture) {
  12834. return;
  12835. }
  12836. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12837. };
  12838. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12839. x -= this.uOffset + 0.5;
  12840. y -= this.vOffset + 0.5;
  12841. z -= 0.5;
  12842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12843. t.x *= this.uScale;
  12844. t.y *= this.vScale;
  12845. t.x += 0.5;
  12846. t.y += 0.5;
  12847. t.z += 0.5;
  12848. };
  12849. Texture.prototype.getTextureMatrix = function () {
  12850. 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) {
  12851. return this._cachedTextureMatrix;
  12852. }
  12853. this._cachedUOffset = this.uOffset;
  12854. this._cachedVOffset = this.vOffset;
  12855. this._cachedUScale = this.uScale;
  12856. this._cachedVScale = this.vScale;
  12857. this._cachedUAng = this.uAng;
  12858. this._cachedVAng = this.vAng;
  12859. this._cachedWAng = this.wAng;
  12860. if (!this._cachedTextureMatrix) {
  12861. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12862. this._rowGenerationMatrix = new BABYLON.Matrix();
  12863. this._t0 = BABYLON.Vector3.Zero();
  12864. this._t1 = BABYLON.Vector3.Zero();
  12865. this._t2 = BABYLON.Vector3.Zero();
  12866. }
  12867. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12868. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12869. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12870. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12871. this._t1.subtractInPlace(this._t0);
  12872. this._t2.subtractInPlace(this._t0);
  12873. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12874. this._cachedTextureMatrix.m[0] = this._t1.x;
  12875. this._cachedTextureMatrix.m[1] = this._t1.y;
  12876. this._cachedTextureMatrix.m[2] = this._t1.z;
  12877. this._cachedTextureMatrix.m[4] = this._t2.x;
  12878. this._cachedTextureMatrix.m[5] = this._t2.y;
  12879. this._cachedTextureMatrix.m[6] = this._t2.z;
  12880. this._cachedTextureMatrix.m[8] = this._t0.x;
  12881. this._cachedTextureMatrix.m[9] = this._t0.y;
  12882. this._cachedTextureMatrix.m[10] = this._t0.z;
  12883. return this._cachedTextureMatrix;
  12884. };
  12885. Texture.prototype.getReflectionTextureMatrix = function () {
  12886. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12887. return this._cachedTextureMatrix;
  12888. }
  12889. if (!this._cachedTextureMatrix) {
  12890. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12891. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12892. }
  12893. this._cachedCoordinatesMode = this.coordinatesMode;
  12894. switch (this.coordinatesMode) {
  12895. case Texture.SPHERICAL_MODE:
  12896. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12897. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12898. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12899. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12900. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12901. break;
  12902. case Texture.PLANAR_MODE:
  12903. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12904. this._cachedTextureMatrix[0] = this.uScale;
  12905. this._cachedTextureMatrix[5] = this.vScale;
  12906. this._cachedTextureMatrix[12] = this.uOffset;
  12907. this._cachedTextureMatrix[13] = this.vOffset;
  12908. break;
  12909. case Texture.PROJECTION_MODE:
  12910. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12911. this._projectionModeMatrix.m[0] = 0.5;
  12912. this._projectionModeMatrix.m[5] = -0.5;
  12913. this._projectionModeMatrix.m[10] = 0.0;
  12914. this._projectionModeMatrix.m[12] = 0.5;
  12915. this._projectionModeMatrix.m[13] = 0.5;
  12916. this._projectionModeMatrix.m[14] = 1.0;
  12917. this._projectionModeMatrix.m[15] = 1.0;
  12918. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12919. break;
  12920. default:
  12921. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12922. break;
  12923. }
  12924. return this._cachedTextureMatrix;
  12925. };
  12926. Texture.prototype.clone = function () {
  12927. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12928. // Base texture
  12929. newTexture.hasAlpha = this.hasAlpha;
  12930. newTexture.level = this.level;
  12931. newTexture.wrapU = this.wrapU;
  12932. newTexture.wrapV = this.wrapV;
  12933. newTexture.coordinatesIndex = this.coordinatesIndex;
  12934. newTexture.coordinatesMode = this.coordinatesMode;
  12935. // Texture
  12936. newTexture.uOffset = this.uOffset;
  12937. newTexture.vOffset = this.vOffset;
  12938. newTexture.uScale = this.uScale;
  12939. newTexture.vScale = this.vScale;
  12940. newTexture.uAng = this.uAng;
  12941. newTexture.vAng = this.vAng;
  12942. newTexture.wAng = this.wAng;
  12943. return newTexture;
  12944. };
  12945. // Statics
  12946. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12947. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12948. if (onLoad === void 0) { onLoad = null; }
  12949. if (onError === void 0) { onError = null; }
  12950. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12951. };
  12952. // Constants
  12953. Texture.NEAREST_SAMPLINGMODE = 1;
  12954. Texture.BILINEAR_SAMPLINGMODE = 2;
  12955. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12956. Texture.EXPLICIT_MODE = 0;
  12957. Texture.SPHERICAL_MODE = 1;
  12958. Texture.PLANAR_MODE = 2;
  12959. Texture.CUBIC_MODE = 3;
  12960. Texture.PROJECTION_MODE = 4;
  12961. Texture.SKYBOX_MODE = 5;
  12962. Texture.CLAMP_ADDRESSMODE = 0;
  12963. Texture.WRAP_ADDRESSMODE = 1;
  12964. Texture.MIRROR_ADDRESSMODE = 2;
  12965. return Texture;
  12966. })(BABYLON.BaseTexture);
  12967. BABYLON.Texture = Texture;
  12968. })(BABYLON || (BABYLON = {}));
  12969. //# sourceMappingURL=babylon.texture.js.map
  12970. var BABYLON;
  12971. (function (BABYLON) {
  12972. var CubeTexture = (function (_super) {
  12973. __extends(CubeTexture, _super);
  12974. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12975. _super.call(this, scene);
  12976. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12977. this.name = rootUrl;
  12978. this.url = rootUrl;
  12979. this._noMipmap = noMipmap;
  12980. this.hasAlpha = false;
  12981. this._texture = this._getFromCache(rootUrl, noMipmap);
  12982. if (!extensions) {
  12983. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12984. }
  12985. this._extensions = extensions;
  12986. if (!this._texture) {
  12987. if (!scene.useDelayedTextureLoading) {
  12988. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12989. }
  12990. else {
  12991. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12992. }
  12993. }
  12994. this.isCube = true;
  12995. this._textureMatrix = BABYLON.Matrix.Identity();
  12996. }
  12997. CubeTexture.prototype.clone = function () {
  12998. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12999. // Base texture
  13000. newTexture.level = this.level;
  13001. newTexture.wrapU = this.wrapU;
  13002. newTexture.wrapV = this.wrapV;
  13003. newTexture.coordinatesIndex = this.coordinatesIndex;
  13004. newTexture.coordinatesMode = this.coordinatesMode;
  13005. return newTexture;
  13006. };
  13007. // Methods
  13008. CubeTexture.prototype.delayLoad = function () {
  13009. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13010. return;
  13011. }
  13012. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13013. this._texture = this._getFromCache(this.url, this._noMipmap);
  13014. if (!this._texture) {
  13015. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13016. }
  13017. };
  13018. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13019. return this._textureMatrix;
  13020. };
  13021. return CubeTexture;
  13022. })(BABYLON.BaseTexture);
  13023. BABYLON.CubeTexture = CubeTexture;
  13024. })(BABYLON || (BABYLON = {}));
  13025. //# sourceMappingURL=babylon.cubeTexture.js.map
  13026. var BABYLON;
  13027. (function (BABYLON) {
  13028. var RenderTargetTexture = (function (_super) {
  13029. __extends(RenderTargetTexture, _super);
  13030. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13031. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13032. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13033. _super.call(this, null, scene, !generateMipMaps);
  13034. this.renderList = new Array();
  13035. this.renderParticles = true;
  13036. this.renderSprites = false;
  13037. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13038. this._currentRefreshId = -1;
  13039. this._refreshRate = 1;
  13040. this.name = name;
  13041. this.isRenderTarget = true;
  13042. this._size = size;
  13043. this._generateMipMaps = generateMipMaps;
  13044. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13045. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13046. // Rendering groups
  13047. this._renderingManager = new BABYLON.RenderingManager(scene);
  13048. }
  13049. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13050. this._currentRefreshId = -1;
  13051. };
  13052. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13053. get: function () {
  13054. return this._refreshRate;
  13055. },
  13056. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13057. set: function (value) {
  13058. this._refreshRate = value;
  13059. this.resetRefreshCounter();
  13060. },
  13061. enumerable: true,
  13062. configurable: true
  13063. });
  13064. RenderTargetTexture.prototype._shouldRender = function () {
  13065. if (this._currentRefreshId === -1) {
  13066. this._currentRefreshId = 1;
  13067. return true;
  13068. }
  13069. if (this.refreshRate === this._currentRefreshId) {
  13070. this._currentRefreshId = 1;
  13071. return true;
  13072. }
  13073. this._currentRefreshId++;
  13074. return false;
  13075. };
  13076. RenderTargetTexture.prototype.isReady = function () {
  13077. if (!this.getScene().renderTargetsEnabled) {
  13078. return false;
  13079. }
  13080. return _super.prototype.isReady.call(this);
  13081. };
  13082. RenderTargetTexture.prototype.getRenderSize = function () {
  13083. return this._size;
  13084. };
  13085. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13086. get: function () {
  13087. return true;
  13088. },
  13089. enumerable: true,
  13090. configurable: true
  13091. });
  13092. RenderTargetTexture.prototype.scale = function (ratio) {
  13093. var newSize = this._size * ratio;
  13094. this.resize(newSize, this._generateMipMaps);
  13095. };
  13096. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13097. this.releaseInternalTexture();
  13098. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13099. };
  13100. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13101. var scene = this.getScene();
  13102. var engine = scene.getEngine();
  13103. if (this._waitingRenderList) {
  13104. this.renderList = [];
  13105. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13106. var id = this._waitingRenderList[index];
  13107. this.renderList.push(scene.getMeshByID(id));
  13108. }
  13109. delete this._waitingRenderList;
  13110. }
  13111. if (this.renderList && this.renderList.length === 0) {
  13112. return;
  13113. }
  13114. // Bind
  13115. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13116. engine.bindFramebuffer(this._texture);
  13117. }
  13118. this._renderingManager.reset();
  13119. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13120. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13121. var mesh = currentRenderList[meshIndex];
  13122. if (mesh) {
  13123. if (!mesh.isReady()) {
  13124. // Reset _currentRefreshId
  13125. this.resetRefreshCounter();
  13126. continue;
  13127. }
  13128. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13129. mesh._activate(scene.getRenderId());
  13130. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13131. var subMesh = mesh.subMeshes[subIndex];
  13132. scene._activeVertices += subMesh.indexCount;
  13133. this._renderingManager.dispatch(subMesh);
  13134. }
  13135. }
  13136. }
  13137. }
  13138. if (this.onBeforeRender) {
  13139. this.onBeforeRender();
  13140. }
  13141. // Clear
  13142. if (this.onClear) {
  13143. this.onClear(engine);
  13144. }
  13145. else {
  13146. engine.clear(scene.clearColor, true, true);
  13147. }
  13148. if (!this._doNotChangeAspectRatio) {
  13149. scene.updateTransformMatrix(true);
  13150. }
  13151. // Render
  13152. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13153. if (useCameraPostProcess) {
  13154. scene.postProcessManager._finalizeFrame(false, this._texture);
  13155. }
  13156. if (!this._doNotChangeAspectRatio) {
  13157. scene.updateTransformMatrix(true);
  13158. }
  13159. if (this.onAfterRender) {
  13160. this.onAfterRender();
  13161. }
  13162. // Dump ?
  13163. if (dumpForDebug) {
  13164. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13165. }
  13166. // Unbind
  13167. engine.unBindFramebuffer(this._texture);
  13168. if (this.onAfterUnbind) {
  13169. this.onAfterUnbind();
  13170. }
  13171. };
  13172. RenderTargetTexture.prototype.clone = function () {
  13173. var textureSize = this.getSize();
  13174. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13175. // Base texture
  13176. newTexture.hasAlpha = this.hasAlpha;
  13177. newTexture.level = this.level;
  13178. // RenderTarget Texture
  13179. newTexture.coordinatesMode = this.coordinatesMode;
  13180. newTexture.renderList = this.renderList.slice(0);
  13181. return newTexture;
  13182. };
  13183. return RenderTargetTexture;
  13184. })(BABYLON.Texture);
  13185. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13186. })(BABYLON || (BABYLON = {}));
  13187. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13188. var BABYLON;
  13189. (function (BABYLON) {
  13190. var ProceduralTexture = (function (_super) {
  13191. __extends(ProceduralTexture, _super);
  13192. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13193. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13194. _super.call(this, null, scene, !generateMipMaps);
  13195. this._currentRefreshId = -1;
  13196. this._refreshRate = 1;
  13197. this._vertexDeclaration = [2];
  13198. this._vertexStrideSize = 2 * 4;
  13199. this._uniforms = new Array();
  13200. this._samplers = new Array();
  13201. this._textures = new Array();
  13202. this._floats = new Array();
  13203. this._floatsArrays = {};
  13204. this._colors3 = new Array();
  13205. this._colors4 = new Array();
  13206. this._vectors2 = new Array();
  13207. this._vectors3 = new Array();
  13208. this._matrices = new Array();
  13209. this._fallbackTextureUsed = false;
  13210. scene._proceduralTextures.push(this);
  13211. this.name = name;
  13212. this.isRenderTarget = true;
  13213. this._size = size;
  13214. this._generateMipMaps = generateMipMaps;
  13215. this.setFragment(fragment);
  13216. this._fallbackTexture = fallbackTexture;
  13217. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13218. // VBO
  13219. var vertices = [];
  13220. vertices.push(1, 1);
  13221. vertices.push(-1, 1);
  13222. vertices.push(-1, -1);
  13223. vertices.push(1, -1);
  13224. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13225. // Indices
  13226. var indices = [];
  13227. indices.push(0);
  13228. indices.push(1);
  13229. indices.push(2);
  13230. indices.push(0);
  13231. indices.push(2);
  13232. indices.push(3);
  13233. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13234. }
  13235. ProceduralTexture.prototype.reset = function () {
  13236. if (this._effect === undefined) {
  13237. return;
  13238. }
  13239. var engine = this.getScene().getEngine();
  13240. engine._releaseEffect(this._effect);
  13241. };
  13242. ProceduralTexture.prototype.isReady = function () {
  13243. var _this = this;
  13244. var engine = this.getScene().getEngine();
  13245. var shaders;
  13246. if (!this._fragment) {
  13247. return false;
  13248. }
  13249. if (this._fallbackTextureUsed) {
  13250. return true;
  13251. }
  13252. if (this._fragment.fragmentElement !== undefined) {
  13253. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13254. }
  13255. else {
  13256. shaders = { vertex: "procedural", fragment: this._fragment };
  13257. }
  13258. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13259. _this.releaseInternalTexture();
  13260. if (_this._fallbackTexture) {
  13261. _this._texture = _this._fallbackTexture._texture;
  13262. _this._texture.references++;
  13263. }
  13264. _this._fallbackTextureUsed = true;
  13265. });
  13266. return this._effect.isReady();
  13267. };
  13268. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13269. this._currentRefreshId = -1;
  13270. };
  13271. ProceduralTexture.prototype.setFragment = function (fragment) {
  13272. this._fragment = fragment;
  13273. };
  13274. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13275. get: function () {
  13276. return this._refreshRate;
  13277. },
  13278. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13279. set: function (value) {
  13280. this._refreshRate = value;
  13281. this.resetRefreshCounter();
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. ProceduralTexture.prototype._shouldRender = function () {
  13287. if (!this.isReady() || !this._texture) {
  13288. return false;
  13289. }
  13290. if (this._fallbackTextureUsed) {
  13291. return false;
  13292. }
  13293. if (this._currentRefreshId === -1) {
  13294. this._currentRefreshId = 1;
  13295. return true;
  13296. }
  13297. if (this.refreshRate === this._currentRefreshId) {
  13298. this._currentRefreshId = 1;
  13299. return true;
  13300. }
  13301. this._currentRefreshId++;
  13302. return false;
  13303. };
  13304. ProceduralTexture.prototype.getRenderSize = function () {
  13305. return this._size;
  13306. };
  13307. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13308. if (this._fallbackTextureUsed) {
  13309. return;
  13310. }
  13311. this.releaseInternalTexture();
  13312. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13313. };
  13314. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13315. if (this._uniforms.indexOf(uniformName) === -1) {
  13316. this._uniforms.push(uniformName);
  13317. }
  13318. };
  13319. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13320. if (this._samplers.indexOf(name) === -1) {
  13321. this._samplers.push(name);
  13322. }
  13323. this._textures[name] = texture;
  13324. return this;
  13325. };
  13326. ProceduralTexture.prototype.setFloat = function (name, value) {
  13327. this._checkUniform(name);
  13328. this._floats[name] = value;
  13329. return this;
  13330. };
  13331. ProceduralTexture.prototype.setFloats = function (name, value) {
  13332. this._checkUniform(name);
  13333. this._floatsArrays[name] = value;
  13334. return this;
  13335. };
  13336. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13337. this._checkUniform(name);
  13338. this._colors3[name] = value;
  13339. return this;
  13340. };
  13341. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13342. this._checkUniform(name);
  13343. this._colors4[name] = value;
  13344. return this;
  13345. };
  13346. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13347. this._checkUniform(name);
  13348. this._vectors2[name] = value;
  13349. return this;
  13350. };
  13351. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13352. this._checkUniform(name);
  13353. this._vectors3[name] = value;
  13354. return this;
  13355. };
  13356. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13357. this._checkUniform(name);
  13358. this._matrices[name] = value;
  13359. return this;
  13360. };
  13361. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13362. var scene = this.getScene();
  13363. var engine = scene.getEngine();
  13364. engine.bindFramebuffer(this._texture);
  13365. // Clear
  13366. engine.clear(scene.clearColor, true, true);
  13367. // Render
  13368. engine.enableEffect(this._effect);
  13369. engine.setState(false);
  13370. for (var name in this._textures) {
  13371. this._effect.setTexture(name, this._textures[name]);
  13372. }
  13373. for (name in this._floats) {
  13374. this._effect.setFloat(name, this._floats[name]);
  13375. }
  13376. for (name in this._floatsArrays) {
  13377. this._effect.setArray(name, this._floatsArrays[name]);
  13378. }
  13379. for (name in this._colors3) {
  13380. this._effect.setColor3(name, this._colors3[name]);
  13381. }
  13382. for (name in this._colors4) {
  13383. var color = this._colors4[name];
  13384. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13385. }
  13386. for (name in this._vectors2) {
  13387. this._effect.setVector2(name, this._vectors2[name]);
  13388. }
  13389. for (name in this._vectors3) {
  13390. this._effect.setVector3(name, this._vectors3[name]);
  13391. }
  13392. for (name in this._matrices) {
  13393. this._effect.setMatrix(name, this._matrices[name]);
  13394. }
  13395. // VBOs
  13396. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13397. // Draw order
  13398. engine.draw(true, 0, 6);
  13399. // Unbind
  13400. engine.unBindFramebuffer(this._texture);
  13401. };
  13402. ProceduralTexture.prototype.clone = function () {
  13403. var textureSize = this.getSize();
  13404. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13405. // Base texture
  13406. newTexture.hasAlpha = this.hasAlpha;
  13407. newTexture.level = this.level;
  13408. // RenderTarget Texture
  13409. newTexture.coordinatesMode = this.coordinatesMode;
  13410. return newTexture;
  13411. };
  13412. ProceduralTexture.prototype.dispose = function () {
  13413. var index = this.getScene()._proceduralTextures.indexOf(this);
  13414. if (index >= 0) {
  13415. this.getScene()._proceduralTextures.splice(index, 1);
  13416. }
  13417. _super.prototype.dispose.call(this);
  13418. };
  13419. return ProceduralTexture;
  13420. })(BABYLON.Texture);
  13421. BABYLON.ProceduralTexture = ProceduralTexture;
  13422. })(BABYLON || (BABYLON = {}));
  13423. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13424. var BABYLON;
  13425. (function (BABYLON) {
  13426. var WoodProceduralTexture = (function (_super) {
  13427. __extends(WoodProceduralTexture, _super);
  13428. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13429. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13430. this._ampScale = 100.0;
  13431. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13432. this.updateShaderUniforms();
  13433. this.refreshRate = 0;
  13434. }
  13435. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13436. this.setFloat("ampScale", this._ampScale);
  13437. this.setColor3("woodColor", this._woodColor);
  13438. };
  13439. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13440. get: function () {
  13441. return this._ampScale;
  13442. },
  13443. set: function (value) {
  13444. this._ampScale = value;
  13445. this.updateShaderUniforms();
  13446. },
  13447. enumerable: true,
  13448. configurable: true
  13449. });
  13450. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13451. get: function () {
  13452. return this._woodColor;
  13453. },
  13454. set: function (value) {
  13455. this._woodColor = value;
  13456. this.updateShaderUniforms();
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. return WoodProceduralTexture;
  13462. })(BABYLON.ProceduralTexture);
  13463. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13464. var FireProceduralTexture = (function (_super) {
  13465. __extends(FireProceduralTexture, _super);
  13466. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13467. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13468. this._time = 0.0;
  13469. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13470. this._autoGenerateTime = true;
  13471. this._alphaThreshold = 0.5;
  13472. this._fireColors = FireProceduralTexture.RedFireColors;
  13473. this.updateShaderUniforms();
  13474. this.refreshRate = 1;
  13475. }
  13476. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13477. this.setFloat("time", this._time);
  13478. this.setVector2("speed", this._speed);
  13479. this.setColor3("c1", this._fireColors[0]);
  13480. this.setColor3("c2", this._fireColors[1]);
  13481. this.setColor3("c3", this._fireColors[2]);
  13482. this.setColor3("c4", this._fireColors[3]);
  13483. this.setColor3("c5", this._fireColors[4]);
  13484. this.setColor3("c6", this._fireColors[5]);
  13485. this.setFloat("alphaThreshold", this._alphaThreshold);
  13486. };
  13487. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13488. if (this._autoGenerateTime) {
  13489. this._time += this.getScene().getAnimationRatio() * 0.03;
  13490. this.updateShaderUniforms();
  13491. }
  13492. _super.prototype.render.call(this, useCameraPostProcess);
  13493. };
  13494. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13495. get: function () {
  13496. return [
  13497. new BABYLON.Color3(0.5, 0.0, 1.0),
  13498. new BABYLON.Color3(0.9, 0.0, 1.0),
  13499. new BABYLON.Color3(0.2, 0.0, 1.0),
  13500. new BABYLON.Color3(1.0, 0.9, 1.0),
  13501. new BABYLON.Color3(0.1, 0.1, 1.0),
  13502. new BABYLON.Color3(0.9, 0.9, 1.0)
  13503. ];
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13509. get: function () {
  13510. return [
  13511. new BABYLON.Color3(0.5, 1.0, 0.0),
  13512. new BABYLON.Color3(0.5, 1.0, 0.0),
  13513. new BABYLON.Color3(0.3, 0.4, 0.0),
  13514. new BABYLON.Color3(0.5, 1.0, 0.0),
  13515. new BABYLON.Color3(0.2, 0.0, 0.0),
  13516. new BABYLON.Color3(0.5, 1.0, 0.0)
  13517. ];
  13518. },
  13519. enumerable: true,
  13520. configurable: true
  13521. });
  13522. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13523. get: function () {
  13524. return [
  13525. new BABYLON.Color3(0.5, 0.0, 0.1),
  13526. new BABYLON.Color3(0.9, 0.0, 0.0),
  13527. new BABYLON.Color3(0.2, 0.0, 0.0),
  13528. new BABYLON.Color3(1.0, 0.9, 0.0),
  13529. new BABYLON.Color3(0.1, 0.1, 0.1),
  13530. new BABYLON.Color3(0.9, 0.9, 0.9)
  13531. ];
  13532. },
  13533. enumerable: true,
  13534. configurable: true
  13535. });
  13536. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13537. get: function () {
  13538. return [
  13539. new BABYLON.Color3(0.1, 0.0, 0.5),
  13540. new BABYLON.Color3(0.0, 0.0, 0.5),
  13541. new BABYLON.Color3(0.1, 0.0, 0.2),
  13542. new BABYLON.Color3(0.0, 0.0, 1.0),
  13543. new BABYLON.Color3(0.1, 0.2, 0.3),
  13544. new BABYLON.Color3(0.0, 0.2, 0.9)
  13545. ];
  13546. },
  13547. enumerable: true,
  13548. configurable: true
  13549. });
  13550. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13551. get: function () {
  13552. return this._fireColors;
  13553. },
  13554. set: function (value) {
  13555. this._fireColors = value;
  13556. this.updateShaderUniforms();
  13557. },
  13558. enumerable: true,
  13559. configurable: true
  13560. });
  13561. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13562. get: function () {
  13563. return this._time;
  13564. },
  13565. set: function (value) {
  13566. this._time = value;
  13567. this.updateShaderUniforms();
  13568. },
  13569. enumerable: true,
  13570. configurable: true
  13571. });
  13572. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13573. get: function () {
  13574. return this._speed;
  13575. },
  13576. set: function (value) {
  13577. this._speed = value;
  13578. this.updateShaderUniforms();
  13579. },
  13580. enumerable: true,
  13581. configurable: true
  13582. });
  13583. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13584. get: function () {
  13585. return this._alphaThreshold;
  13586. },
  13587. set: function (value) {
  13588. this._alphaThreshold = value;
  13589. this.updateShaderUniforms();
  13590. },
  13591. enumerable: true,
  13592. configurable: true
  13593. });
  13594. return FireProceduralTexture;
  13595. })(BABYLON.ProceduralTexture);
  13596. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13597. var CloudProceduralTexture = (function (_super) {
  13598. __extends(CloudProceduralTexture, _super);
  13599. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13600. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13601. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13602. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13603. this.updateShaderUniforms();
  13604. this.refreshRate = 0;
  13605. }
  13606. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13607. this.setColor3("skyColor", this._skyColor);
  13608. this.setColor3("cloudColor", this._cloudColor);
  13609. };
  13610. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13611. get: function () {
  13612. return this._skyColor;
  13613. },
  13614. set: function (value) {
  13615. this._skyColor = value;
  13616. this.updateShaderUniforms();
  13617. },
  13618. enumerable: true,
  13619. configurable: true
  13620. });
  13621. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13622. get: function () {
  13623. return this._cloudColor;
  13624. },
  13625. set: function (value) {
  13626. this._cloudColor = value;
  13627. this.updateShaderUniforms();
  13628. },
  13629. enumerable: true,
  13630. configurable: true
  13631. });
  13632. return CloudProceduralTexture;
  13633. })(BABYLON.ProceduralTexture);
  13634. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13635. var GrassProceduralTexture = (function (_super) {
  13636. __extends(GrassProceduralTexture, _super);
  13637. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13638. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13639. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13640. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13641. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13642. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13643. this._grassColors = [
  13644. new BABYLON.Color3(0.29, 0.38, 0.02),
  13645. new BABYLON.Color3(0.36, 0.49, 0.09),
  13646. new BABYLON.Color3(0.51, 0.6, 0.28)
  13647. ];
  13648. this.updateShaderUniforms();
  13649. this.refreshRate = 0;
  13650. }
  13651. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13652. this.setColor3("herb1Color", this._grassColors[0]);
  13653. this.setColor3("herb2Color", this._grassColors[1]);
  13654. this.setColor3("herb3Color", this._grassColors[2]);
  13655. this.setColor3("groundColor", this._groundColor);
  13656. };
  13657. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13658. get: function () {
  13659. return this._grassColors;
  13660. },
  13661. set: function (value) {
  13662. this._grassColors = value;
  13663. this.updateShaderUniforms();
  13664. },
  13665. enumerable: true,
  13666. configurable: true
  13667. });
  13668. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13669. get: function () {
  13670. return this._groundColor;
  13671. },
  13672. set: function (value) {
  13673. this.groundColor = value;
  13674. this.updateShaderUniforms();
  13675. },
  13676. enumerable: true,
  13677. configurable: true
  13678. });
  13679. return GrassProceduralTexture;
  13680. })(BABYLON.ProceduralTexture);
  13681. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13682. var RoadProceduralTexture = (function (_super) {
  13683. __extends(RoadProceduralTexture, _super);
  13684. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13685. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13686. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13687. this.updateShaderUniforms();
  13688. this.refreshRate = 0;
  13689. }
  13690. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13691. this.setColor3("roadColor", this._roadColor);
  13692. };
  13693. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13694. get: function () {
  13695. return this._roadColor;
  13696. },
  13697. set: function (value) {
  13698. this._roadColor = value;
  13699. this.updateShaderUniforms();
  13700. },
  13701. enumerable: true,
  13702. configurable: true
  13703. });
  13704. return RoadProceduralTexture;
  13705. })(BABYLON.ProceduralTexture);
  13706. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13707. var BrickProceduralTexture = (function (_super) {
  13708. __extends(BrickProceduralTexture, _super);
  13709. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13710. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13711. this._numberOfBricksHeight = 15;
  13712. this._numberOfBricksWidth = 5;
  13713. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13714. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13715. this.updateShaderUniforms();
  13716. this.refreshRate = 0;
  13717. }
  13718. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13719. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13720. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13721. this.setColor3("brickColor", this._brickColor);
  13722. this.setColor3("jointColor", this._jointColor);
  13723. };
  13724. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13725. get: function () {
  13726. return this._numberOfBricksHeight;
  13727. },
  13728. set: function (value) {
  13729. this._numberOfBricksHeight = value;
  13730. this.updateShaderUniforms();
  13731. },
  13732. enumerable: true,
  13733. configurable: true
  13734. });
  13735. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13736. get: function () {
  13737. return this._numberOfBricksWidth;
  13738. },
  13739. set: function (value) {
  13740. this._numberOfBricksHeight = value;
  13741. this.updateShaderUniforms();
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13747. get: function () {
  13748. return this._jointColor;
  13749. },
  13750. set: function (value) {
  13751. this._jointColor = value;
  13752. this.updateShaderUniforms();
  13753. },
  13754. enumerable: true,
  13755. configurable: true
  13756. });
  13757. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13758. get: function () {
  13759. return this._brickColor;
  13760. },
  13761. set: function (value) {
  13762. this._brickColor = value;
  13763. this.updateShaderUniforms();
  13764. },
  13765. enumerable: true,
  13766. configurable: true
  13767. });
  13768. return BrickProceduralTexture;
  13769. })(BABYLON.ProceduralTexture);
  13770. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13771. var MarbleProceduralTexture = (function (_super) {
  13772. __extends(MarbleProceduralTexture, _super);
  13773. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13774. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13775. this._numberOfTilesHeight = 3;
  13776. this._numberOfTilesWidth = 3;
  13777. this._amplitude = 9.0;
  13778. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13779. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13780. this.updateShaderUniforms();
  13781. this.refreshRate = 0;
  13782. }
  13783. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13784. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13785. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13786. this.setFloat("amplitude", this._amplitude);
  13787. this.setColor3("marbleColor", this._marbleColor);
  13788. this.setColor3("jointColor", this._jointColor);
  13789. };
  13790. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13791. get: function () {
  13792. return this._numberOfTilesHeight;
  13793. },
  13794. set: function (value) {
  13795. this._numberOfTilesHeight = value;
  13796. this.updateShaderUniforms();
  13797. },
  13798. enumerable: true,
  13799. configurable: true
  13800. });
  13801. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13802. get: function () {
  13803. return this._numberOfTilesWidth;
  13804. },
  13805. set: function (value) {
  13806. this._numberOfTilesWidth = value;
  13807. this.updateShaderUniforms();
  13808. },
  13809. enumerable: true,
  13810. configurable: true
  13811. });
  13812. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13813. get: function () {
  13814. return this._jointColor;
  13815. },
  13816. set: function (value) {
  13817. this._jointColor = value;
  13818. this.updateShaderUniforms();
  13819. },
  13820. enumerable: true,
  13821. configurable: true
  13822. });
  13823. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13824. get: function () {
  13825. return this._marbleColor;
  13826. },
  13827. set: function (value) {
  13828. this._marbleColor = value;
  13829. this.updateShaderUniforms();
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. return MarbleProceduralTexture;
  13835. })(BABYLON.ProceduralTexture);
  13836. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13837. })(BABYLON || (BABYLON = {}));
  13838. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13839. var BABYLON;
  13840. (function (BABYLON) {
  13841. var CustomProceduralTexture = (function (_super) {
  13842. __extends(CustomProceduralTexture, _super);
  13843. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13844. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13845. this._animate = true;
  13846. this._time = 0;
  13847. this._texturePath = texturePath;
  13848. //Try to load json
  13849. this.loadJson(texturePath);
  13850. this.refreshRate = 1;
  13851. }
  13852. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13853. var _this = this;
  13854. var that = this;
  13855. function noConfigFile() {
  13856. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13857. try {
  13858. that.setFragment(that._texturePath);
  13859. }
  13860. catch (ex) {
  13861. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13862. }
  13863. }
  13864. var configFileUrl = jsonUrl + "/config.json";
  13865. var xhr = new XMLHttpRequest();
  13866. xhr.open("GET", configFileUrl, true);
  13867. xhr.addEventListener("load", function () {
  13868. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13869. try {
  13870. _this._config = JSON.parse(xhr.response);
  13871. _this.updateShaderUniforms();
  13872. _this.updateTextures();
  13873. _this.setFragment(_this._texturePath + "/custom");
  13874. _this._animate = _this._config.animate;
  13875. _this.refreshRate = _this._config.refreshrate;
  13876. }
  13877. catch (ex) {
  13878. noConfigFile();
  13879. }
  13880. }
  13881. else {
  13882. noConfigFile();
  13883. }
  13884. }, false);
  13885. xhr.addEventListener("error", function () {
  13886. noConfigFile();
  13887. }, false);
  13888. try {
  13889. xhr.send();
  13890. }
  13891. catch (ex) {
  13892. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13893. }
  13894. };
  13895. CustomProceduralTexture.prototype.isReady = function () {
  13896. if (!_super.prototype.isReady.call(this)) {
  13897. return false;
  13898. }
  13899. for (var name in this._textures) {
  13900. var texture = this._textures[name];
  13901. if (!texture.isReady()) {
  13902. return false;
  13903. }
  13904. }
  13905. return true;
  13906. };
  13907. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13908. if (this._animate) {
  13909. this._time += this.getScene().getAnimationRatio() * 0.03;
  13910. this.updateShaderUniforms();
  13911. }
  13912. _super.prototype.render.call(this, useCameraPostProcess);
  13913. };
  13914. CustomProceduralTexture.prototype.updateTextures = function () {
  13915. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13916. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13917. }
  13918. };
  13919. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13920. if (this._config) {
  13921. for (var j = 0; j < this._config.uniforms.length; j++) {
  13922. var uniform = this._config.uniforms[j];
  13923. switch (uniform.type) {
  13924. case "float":
  13925. this.setFloat(uniform.name, uniform.value);
  13926. break;
  13927. case "color3":
  13928. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13929. break;
  13930. case "color4":
  13931. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13932. break;
  13933. case "vector2":
  13934. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13935. break;
  13936. case "vector3":
  13937. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13938. break;
  13939. }
  13940. }
  13941. }
  13942. this.setFloat("time", this._time);
  13943. };
  13944. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13945. get: function () {
  13946. return this._animate;
  13947. },
  13948. set: function (value) {
  13949. this._animate = value;
  13950. },
  13951. enumerable: true,
  13952. configurable: true
  13953. });
  13954. return CustomProceduralTexture;
  13955. })(BABYLON.ProceduralTexture);
  13956. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13957. })(BABYLON || (BABYLON = {}));
  13958. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13959. var BABYLON;
  13960. (function (BABYLON) {
  13961. var MirrorTexture = (function (_super) {
  13962. __extends(MirrorTexture, _super);
  13963. function MirrorTexture(name, size, scene, generateMipMaps) {
  13964. var _this = this;
  13965. _super.call(this, name, size, scene, generateMipMaps, true);
  13966. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13967. this._transformMatrix = BABYLON.Matrix.Zero();
  13968. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13969. this.onBeforeRender = function () {
  13970. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13971. _this._savedViewMatrix = scene.getViewMatrix();
  13972. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13973. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13974. scene.clipPlane = _this.mirrorPlane;
  13975. scene.getEngine().cullBackFaces = false;
  13976. };
  13977. this.onAfterRender = function () {
  13978. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13979. scene.getEngine().cullBackFaces = true;
  13980. delete scene.clipPlane;
  13981. };
  13982. }
  13983. MirrorTexture.prototype.clone = function () {
  13984. var textureSize = this.getSize();
  13985. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13986. // Base texture
  13987. newTexture.hasAlpha = this.hasAlpha;
  13988. newTexture.level = this.level;
  13989. // Mirror Texture
  13990. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13991. newTexture.renderList = this.renderList.slice(0);
  13992. return newTexture;
  13993. };
  13994. return MirrorTexture;
  13995. })(BABYLON.RenderTargetTexture);
  13996. BABYLON.MirrorTexture = MirrorTexture;
  13997. })(BABYLON || (BABYLON = {}));
  13998. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13999. var BABYLON;
  14000. (function (BABYLON) {
  14001. var DynamicTexture = (function (_super) {
  14002. __extends(DynamicTexture, _super);
  14003. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14005. _super.call(this, null, scene, !generateMipMaps);
  14006. this.name = name;
  14007. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14008. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14009. this._generateMipMaps = generateMipMaps;
  14010. if (options.getContext) {
  14011. this._canvas = options;
  14012. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14013. }
  14014. else {
  14015. this._canvas = document.createElement("canvas");
  14016. if (options.width) {
  14017. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14018. }
  14019. else {
  14020. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14021. }
  14022. }
  14023. var textureSize = this.getSize();
  14024. this._canvas.width = textureSize.width;
  14025. this._canvas.height = textureSize.height;
  14026. this._context = this._canvas.getContext("2d");
  14027. }
  14028. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14029. get: function () {
  14030. return true;
  14031. },
  14032. enumerable: true,
  14033. configurable: true
  14034. });
  14035. DynamicTexture.prototype.scale = function (ratio) {
  14036. var textureSize = this.getSize();
  14037. textureSize.width *= ratio;
  14038. textureSize.height *= ratio;
  14039. this._canvas.width = textureSize.width;
  14040. this._canvas.height = textureSize.height;
  14041. this.releaseInternalTexture();
  14042. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14043. };
  14044. DynamicTexture.prototype.getContext = function () {
  14045. return this._context;
  14046. };
  14047. DynamicTexture.prototype.clear = function () {
  14048. var size = this.getSize();
  14049. this._context.fillRect(0, 0, size.width, size.height);
  14050. };
  14051. DynamicTexture.prototype.update = function (invertY) {
  14052. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14053. };
  14054. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14055. if (update === void 0) { update = true; }
  14056. var size = this.getSize();
  14057. if (clearColor) {
  14058. this._context.fillStyle = clearColor;
  14059. this._context.fillRect(0, 0, size.width, size.height);
  14060. }
  14061. this._context.font = font;
  14062. if (x === null) {
  14063. var textSize = this._context.measureText(text);
  14064. x = (size.width - textSize.width) / 2;
  14065. }
  14066. this._context.fillStyle = color;
  14067. this._context.fillText(text, x, y);
  14068. if (update) {
  14069. this.update(invertY);
  14070. }
  14071. };
  14072. DynamicTexture.prototype.clone = function () {
  14073. var textureSize = this.getSize();
  14074. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14075. // Base texture
  14076. newTexture.hasAlpha = this.hasAlpha;
  14077. newTexture.level = this.level;
  14078. // Dynamic Texture
  14079. newTexture.wrapU = this.wrapU;
  14080. newTexture.wrapV = this.wrapV;
  14081. return newTexture;
  14082. };
  14083. return DynamicTexture;
  14084. })(BABYLON.Texture);
  14085. BABYLON.DynamicTexture = DynamicTexture;
  14086. })(BABYLON || (BABYLON = {}));
  14087. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14088. var BABYLON;
  14089. (function (BABYLON) {
  14090. var VideoTexture = (function (_super) {
  14091. __extends(VideoTexture, _super);
  14092. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14093. var _this = this;
  14094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14095. _super.call(this, null, scene, !generateMipMaps, invertY);
  14096. this._autoLaunch = true;
  14097. this.name = name;
  14098. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14099. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14100. var requiredWidth = size.width || size;
  14101. var requiredHeight = size.height || size;
  14102. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14103. var textureSize = this.getSize();
  14104. this.video = document.createElement("video");
  14105. this.video.width = textureSize.width;
  14106. this.video.height = textureSize.height;
  14107. this.video.autoplay = false;
  14108. this.video.loop = true;
  14109. this.video.addEventListener("canplaythrough", function () {
  14110. if (_this._texture) {
  14111. _this._texture.isReady = true;
  14112. }
  14113. });
  14114. urls.forEach(function (url) {
  14115. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14116. var source = document.createElement("source");
  14117. source.src = url;
  14118. _this.video.appendChild(source);
  14119. });
  14120. this._lastUpdate = BABYLON.Tools.Now;
  14121. }
  14122. VideoTexture.prototype.update = function () {
  14123. if (this._autoLaunch) {
  14124. this._autoLaunch = false;
  14125. this.video.play();
  14126. }
  14127. var now = BABYLON.Tools.Now;
  14128. if (now - this._lastUpdate < 15) {
  14129. return false;
  14130. }
  14131. this._lastUpdate = now;
  14132. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14133. return true;
  14134. };
  14135. return VideoTexture;
  14136. })(BABYLON.Texture);
  14137. BABYLON.VideoTexture = VideoTexture;
  14138. })(BABYLON || (BABYLON = {}));
  14139. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14140. (function (BABYLON) {
  14141. var EffectFallbacks = (function () {
  14142. function EffectFallbacks() {
  14143. this._defines = {};
  14144. this._currentRank = 32;
  14145. this._maxRank = -1;
  14146. }
  14147. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14148. if (!this._defines[rank]) {
  14149. if (rank < this._currentRank) {
  14150. this._currentRank = rank;
  14151. }
  14152. if (rank > this._maxRank) {
  14153. this._maxRank = rank;
  14154. }
  14155. this._defines[rank] = new Array();
  14156. }
  14157. this._defines[rank].push(define);
  14158. };
  14159. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14160. get: function () {
  14161. return this._currentRank <= this._maxRank;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14167. var currentFallbacks = this._defines[this._currentRank];
  14168. for (var index = 0; index < currentFallbacks.length; index++) {
  14169. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14170. }
  14171. this._currentRank++;
  14172. return currentDefines;
  14173. };
  14174. return EffectFallbacks;
  14175. })();
  14176. BABYLON.EffectFallbacks = EffectFallbacks;
  14177. var Effect = (function () {
  14178. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14179. var _this = this;
  14180. this._isReady = false;
  14181. this._compilationError = "";
  14182. this._valueCache = [];
  14183. this._engine = engine;
  14184. this.name = baseName;
  14185. this.defines = defines;
  14186. this._uniformsNames = uniformsNames.concat(samplers);
  14187. this._samplers = samplers;
  14188. this._attributesNames = attributesNames;
  14189. this.onError = onError;
  14190. this.onCompiled = onCompiled;
  14191. var vertexSource;
  14192. var fragmentSource;
  14193. if (baseName.vertexElement) {
  14194. vertexSource = document.getElementById(baseName.vertexElement);
  14195. if (!vertexSource) {
  14196. vertexSource = baseName.vertexElement;
  14197. }
  14198. }
  14199. else {
  14200. vertexSource = baseName.vertex || baseName;
  14201. }
  14202. if (baseName.fragmentElement) {
  14203. fragmentSource = document.getElementById(baseName.fragmentElement);
  14204. if (!fragmentSource) {
  14205. fragmentSource = baseName.fragmentElement;
  14206. }
  14207. }
  14208. else {
  14209. fragmentSource = baseName.fragment || baseName;
  14210. }
  14211. this._loadVertexShader(vertexSource, function (vertexCode) {
  14212. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14213. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14214. });
  14215. });
  14216. }
  14217. // Properties
  14218. Effect.prototype.isReady = function () {
  14219. return this._isReady;
  14220. };
  14221. Effect.prototype.getProgram = function () {
  14222. return this._program;
  14223. };
  14224. Effect.prototype.getAttributesNames = function () {
  14225. return this._attributesNames;
  14226. };
  14227. Effect.prototype.getAttributeLocation = function (index) {
  14228. return this._attributes[index];
  14229. };
  14230. Effect.prototype.getAttributeLocationByName = function (name) {
  14231. var index = this._attributesNames.indexOf(name);
  14232. return this._attributes[index];
  14233. };
  14234. Effect.prototype.getAttributesCount = function () {
  14235. return this._attributes.length;
  14236. };
  14237. Effect.prototype.getUniformIndex = function (uniformName) {
  14238. return this._uniformsNames.indexOf(uniformName);
  14239. };
  14240. Effect.prototype.getUniform = function (uniformName) {
  14241. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14242. };
  14243. Effect.prototype.getSamplers = function () {
  14244. return this._samplers;
  14245. };
  14246. Effect.prototype.getCompilationError = function () {
  14247. return this._compilationError;
  14248. };
  14249. // Methods
  14250. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14251. // DOM element ?
  14252. if (vertex instanceof HTMLElement) {
  14253. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14254. callback(vertexCode);
  14255. return;
  14256. }
  14257. // Is in local store ?
  14258. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14259. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14260. return;
  14261. }
  14262. var vertexShaderUrl;
  14263. if (vertex[0] === ".") {
  14264. vertexShaderUrl = vertex;
  14265. }
  14266. else {
  14267. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14268. }
  14269. // Vertex shader
  14270. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14271. };
  14272. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14273. // DOM element ?
  14274. if (fragment instanceof HTMLElement) {
  14275. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14276. callback(fragmentCode);
  14277. return;
  14278. }
  14279. // Is in local store ?
  14280. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14281. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14282. return;
  14283. }
  14284. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14285. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14286. return;
  14287. }
  14288. var fragmentShaderUrl;
  14289. if (fragment[0] === ".") {
  14290. fragmentShaderUrl = fragment;
  14291. }
  14292. else {
  14293. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14294. }
  14295. // Fragment shader
  14296. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14297. };
  14298. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14299. try {
  14300. var engine = this._engine;
  14301. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14302. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14303. this._attributes = engine.getAttributes(this._program, attributesNames);
  14304. for (var index = 0; index < this._samplers.length; index++) {
  14305. var sampler = this.getUniform(this._samplers[index]);
  14306. if (sampler == null) {
  14307. this._samplers.splice(index, 1);
  14308. index--;
  14309. }
  14310. }
  14311. engine.bindSamplers(this);
  14312. this._isReady = true;
  14313. if (this.onCompiled) {
  14314. this.onCompiled(this);
  14315. }
  14316. }
  14317. catch (e) {
  14318. // Is it a problem with precision?
  14319. if (e.message.indexOf("highp") !== -1) {
  14320. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14321. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14322. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14323. return;
  14324. }
  14325. // Let's go through fallbacks then
  14326. if (fallbacks && fallbacks.isMoreFallbacks) {
  14327. defines = fallbacks.reduce(defines);
  14328. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14329. }
  14330. else {
  14331. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14332. BABYLON.Tools.Error("Defines: " + defines);
  14333. BABYLON.Tools.Error("Error: " + e.message);
  14334. this._compilationError = e.message;
  14335. if (this.onError) {
  14336. this.onError(this, this._compilationError);
  14337. }
  14338. }
  14339. }
  14340. };
  14341. Effect.prototype._bindTexture = function (channel, texture) {
  14342. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14343. };
  14344. Effect.prototype.setTexture = function (channel, texture) {
  14345. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14346. };
  14347. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14348. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14349. };
  14350. //public _cacheMatrix(uniformName, matrix) {
  14351. // if (!this._valueCache[uniformName]) {
  14352. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14353. // }
  14354. // for (var index = 0; index < 16; index++) {
  14355. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14356. // }
  14357. //};
  14358. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14359. if (!this._valueCache[uniformName]) {
  14360. this._valueCache[uniformName] = [x, y];
  14361. return;
  14362. }
  14363. this._valueCache[uniformName][0] = x;
  14364. this._valueCache[uniformName][1] = y;
  14365. };
  14366. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14367. if (!this._valueCache[uniformName]) {
  14368. this._valueCache[uniformName] = [x, y, z];
  14369. return;
  14370. }
  14371. this._valueCache[uniformName][0] = x;
  14372. this._valueCache[uniformName][1] = y;
  14373. this._valueCache[uniformName][2] = z;
  14374. };
  14375. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14376. if (!this._valueCache[uniformName]) {
  14377. this._valueCache[uniformName] = [x, y, z, w];
  14378. return;
  14379. }
  14380. this._valueCache[uniformName][0] = x;
  14381. this._valueCache[uniformName][1] = y;
  14382. this._valueCache[uniformName][2] = z;
  14383. this._valueCache[uniformName][3] = w;
  14384. };
  14385. Effect.prototype.setArray = function (uniformName, array) {
  14386. this._engine.setArray(this.getUniform(uniformName), array);
  14387. return this;
  14388. };
  14389. Effect.prototype.setArray2 = function (uniformName, array) {
  14390. this._engine.setArray2(this.getUniform(uniformName), array);
  14391. return this;
  14392. };
  14393. Effect.prototype.setArray3 = function (uniformName, array) {
  14394. this._engine.setArray3(this.getUniform(uniformName), array);
  14395. return this;
  14396. };
  14397. Effect.prototype.setArray4 = function (uniformName, array) {
  14398. this._engine.setArray4(this.getUniform(uniformName), array);
  14399. return this;
  14400. };
  14401. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14402. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14403. return this;
  14404. };
  14405. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14406. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14407. // return;
  14408. //this._cacheMatrix(uniformName, matrix);
  14409. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14410. return this;
  14411. };
  14412. Effect.prototype.setFloat = function (uniformName, value) {
  14413. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14414. return this;
  14415. this._valueCache[uniformName] = value;
  14416. this._engine.setFloat(this.getUniform(uniformName), value);
  14417. return this;
  14418. };
  14419. Effect.prototype.setBool = function (uniformName, bool) {
  14420. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14421. return this;
  14422. this._valueCache[uniformName] = bool;
  14423. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14424. return this;
  14425. };
  14426. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14427. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14428. return this;
  14429. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14430. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14431. return this;
  14432. };
  14433. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14434. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14435. return this;
  14436. this._cacheFloat2(uniformName, x, y);
  14437. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14438. return this;
  14439. };
  14440. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14441. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14442. return this;
  14443. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14444. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14445. return this;
  14446. };
  14447. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14448. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14449. return this;
  14450. this._cacheFloat3(uniformName, x, y, z);
  14451. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14452. return this;
  14453. };
  14454. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14455. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14456. return this;
  14457. this._cacheFloat4(uniformName, x, y, z, w);
  14458. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14459. return this;
  14460. };
  14461. Effect.prototype.setColor3 = function (uniformName, color3) {
  14462. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14463. return this;
  14464. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14465. this._engine.setColor3(this.getUniform(uniformName), color3);
  14466. return this;
  14467. };
  14468. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14469. 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)
  14470. return this;
  14471. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14472. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14473. return this;
  14474. };
  14475. // Statics
  14476. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\nvec4 leftFrag = texture2D(leftSampler, vUV);\nleftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\nvec4 rightFrag = texture2D(textureSampler, vUV);\nrightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\ngl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14477. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\nfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\ngl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14478. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\nfloat weights[7];\nweights[0] = 0.05;\nweights[1] = 0.1;\nweights[2] = 0.2;\nweights[3] = 0.3;\nweights[4] = 0.2;\nweights[5] = 0.1;\nweights[6] = 0.05;\n\nvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\nvec2 texelStep = texelSize * direction * blurWidth;\nvec2 start = vUV - 3.0 * texelStep;\n\nvec4 baseColor = vec4(0., 0., 0., 0.);\nvec2 texelOffset = vec2(0., 0.);\n\nfor (int i = 0; i < 7; i++)\n{\nbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\ntexelOffset += texelStep;\n}\n\ngl_FragColor = baseColor;\n}",
  14479. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\nfloat brickW = 1.0 / numberOfBricksWidth;\nfloat brickH = 1.0 / numberOfBricksHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.05;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\nif (brickColorSwitch == 0.0)\ncolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\nelse if (brickColorSwitch == 2.0)\ncolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n}\n\ngl_FragColor = vec4(color, 1.0);\n}",
  14480. chromaticAberrationPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvoid main(void)\n{\nvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius = sqrt(radius2);\n\nvec4 original = texture2D(textureSampler, vUV);\n\nif (chromatic_aberration > 0.0) {\nvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\nfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\nfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n\nvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\noriginal.r = texture2D(textureSampler, ref_coords_r).r;\noriginal.g = texture2D(textureSampler, ref_coords_g).g;\noriginal.b = texture2D(textureSampler, ref_coords_b).b;\n}\n\ngl_FragColor = original;\n}",
  14481. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\n\nvec2 p = vUV * 12.0;\nvec3 c = mix(skyColor, cloudColor, fbm(p));\ngl_FragColor = vec4(c, 1);\n\n}",
  14482. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14483. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14484. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\nfloat sliceSize = 1.0 / width; // space of 1 slice\nfloat slicePixelSize = sliceSize / width; // space of 1 pixel\nfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\nfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\nfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\nfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\nfloat s0 = xOffset + (zSlice0 * sliceSize);\nfloat s1 = xOffset + (zSlice1 * sliceSize);\nvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\nvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\nfloat zOffset = mod(uv.z * width, 1.0);\nvec4 result = mix(slice0Color, slice1Color, zOffset);\nreturn result;\n}\n\nvoid main(void)\n{\nvec4 screen_color = texture2D(textureSampler, vUV);\ngl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14485. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\nvec2 onePixel = vec2(1.0, 1.0) / screenSize;\nvec4 colorSum =\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\n\nif (kernelWeight <= 0.0) {\nkernelWeight = 1.0;\n}\n\ngl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14486. 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\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\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 vec3 shadowsInfo1;\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 vec3 shadowsInfo2;\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 vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn vPositionUVW;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\nreturn dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\nif (depth.z > shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat visibility = 1.;\n\nvec2 poissonDisk[4];\npoissonDisk[0] = vec2(-0.94201624, -0.39906216);\npoissonDisk[1] = vec2(0.94558609, -0.76890725);\npoissonDisk[2] = vec2(-0.094184101, -0.92938870);\npoissonDisk[3] = vec2(0.34495938, 0.29387760);\n\nfloat biasedDepth = depth.z - bias;\n\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\nreturn visibility;\n}\n\nfloat linstep(float low, float high, float v) {\nreturn clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\nfloat p = smoothstep(compare - bias, compare, moments.x);\nfloat variance = max(moments.y - moments.x * moments.x, 0.02);\nfloat d = compare - moments.x;\nfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\nreturn clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\nvec3 dp1 = dFdx(p);\nvec3 dp2 = dFdy(p);\nvec2 duv1 = dFdx(uv);\nvec2 duv2 = dFdy(uv);\n\nvec3 dp2perp = cross(dp2, normal);\nvec3 dp1perp = cross(normal, dp1);\nvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\nvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\nfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\nreturn mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\nvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\nmap = map * 255. / 127. - 128. / 127.;\nmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\nreturn normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nstruct lightingInfo\n{\nvec3 diffuse;\nvec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 lightVectorW;\nfloat attenuation = 1.0;\nif (lightData.w == 0.)\n{\nvec3 direction = lightData.xyz - vPositionW;\n\nattenuation = max(0., 1.0 - length(direction) / range);\nlightVectorW = normalize(direction);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, max(1., vSpecularColor.a));\n\nresult.diffuse = ndl * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * attenuation;\n\nreturn result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 direction = lightData.xyz - vPositionW;\nvec3 lightVectorW = normalize(direction);\nfloat attenuation = max(0., 1.0 - length(direction) / range);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * spotAtten * attenuation;\n\nreturn result;\n}\n\nresult.diffuse = vec3(0.);\nresult.specular = vec3(0.);\n\nreturn result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\nlightingInfo result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = mix(groundColor, diffuseColor, ndl);\nresult.specular = specComp * specularColor;\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\nalpha *= baseColor.a;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n#ifdef NORMAL\nvec3 normalW = normalize(vNormalW);\n#else\nvec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\nnormalW = perturbNormal(viewDirectionW);\n#endif\n\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\nlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n#ifdef SHADOWPCF0\nshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n#ifdef SHADOWPCF1\nshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n#ifdef SHADOWPCF2\nshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n#ifdef SHADOWPCF3\nshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\nalpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14487. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\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\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\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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) {\nmat4 finalWorld;\n\n#ifdef REFLECTION\nvPositionUVW = position;\n#endif\n\n#ifdef INSTANCES\nfinalWorld = mat4(world0, world1, world2, world3);\n#else\nfinalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = finalWorld * (m0 + m1 + m2);\n#endif\n\n#endif\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\n\n#ifdef NORMAL\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize = pointSize;\n#endif\n}",
  14488. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\nfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\ngl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14489. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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#if defined(ALPHATEST) || defined(NEED_UV)\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14490. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\n\nvoid main(void)\n{\nvec4 colorDepth = vec4(0.0);\n\nfor (int x = -OFFSET; x <= OFFSET; x++)\nfor (int y = -OFFSET; y <= OFFSET; y++)\ncolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\ngl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14491. depthOfFieldPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float edge_blur;\nuniform bool highlights;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\nvec2 getDistortedCoords(vec2 coords) {\n\nif (distortion == 0.0) { return coords; }\n\nvec2 direction = 1.0 * normalize(centered_screen_pos);\nvec2 dist_coords = vec2(0.5, 0.5);\ndist_coords.x = 0.5 + direction.x * radius2 * 1.0;\ndist_coords.y = 0.5 + direction.y * radius2 * 1.0;\nfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\ndist_coords = mix(coords, dist_coords, dist_amount);\n\nreturn dist_coords;\n}\n\nvec4 getBlurColor(vec2 coords, float size) {\n\nvec4 col = texture2D(textureSampler, coords);\nif (size == 0.0) { return col; }\n\nfloat blur_level = min(3.0, ceil(size / 1.0));\n\nfloat w = (size / screen_width);\nfloat h = (size / screen_height);\nfloat total_weight = 1.0;\n\ncol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\ncol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\ncol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\ncol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\ncol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\ncol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\ncol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\ncol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\ncol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\ncol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\ntotal_weight += 8.18;\n\nif (blur_level > 1.0) {\ncol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\ncol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\ncol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\ncol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\ncol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\ncol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\ncol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\ncol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\ncol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\ncol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\ntotal_weight += 5.96;\n}\n\nif (blur_level > 2.0) {\ncol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\ncol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\ncol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\ncol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\ncol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\ncol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\ncol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\ncol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\ncol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\ntotal_weight += 2.97;\n}\n\ncol /= total_weight; // scales color according to weights\ncol.a = 1.0;\n\n\nreturn col;\n}\n\nvec2 rand(vec2 co)\n{\nfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\nfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\nreturn clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvoid main(void)\n{\n\ncentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\nradius = sqrt(radius2);\n\nvec4 final_color;\nvec2 distorted_coords = getDistortedCoords(vUV);\nvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\nfloat dof_blur_amount = 0.0;\nfloat depth_bias = 0.0; // positive if the pixel is further than focus depth; negative if closer\nif (focus_depth != -1.0) {\nvec4 depth_sample = texture2D(depthSampler, distorted_coords);\nfloat depth = depth_sample.r;\ndepth_bias = depth - focus_depth;\n\nif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\nelse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\n\nif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n}\n\nfloat edge_blur_amount = 0.0;\nif (edge_blur > 0.0) {\nedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n}\n\nfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\n\nif (blur_amount == 0.0) {\ngl_FragColor = texture2D(textureSampler, distorted_coords);\n}\nelse {\n\ngl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\n\nif (depth_bias > 0.0 && highlights) {\ngl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\n}\n\nif (blur_noise) {\nvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\nvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\ngl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n}\n}\n\nif (grain_amount > 0.0) {\nvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\ngl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\n}\n}",
  14492. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(passSampler, vUV);\n}",
  14493. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\nvec3 baseColor = texture2D(textureSampler, vUV).rgb;\nvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\ngl_FragColor = vec4(updatedColor, 1.0);\n}",
  14494. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\nvec2 p = vUV * 8.0;\nfloat q = fbm(p - time * 0.1);\nvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\nvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\nvec3 color = c * cos(shift * vUV.y);\nfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\ngl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14495. 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(){\nvec2 localTexelSize = texelSize;\nvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\nvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\nvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\nvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\nvec4 rgbM = texture2D(textureSampler, vUV);\nvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\nvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\nfloat dirReduce = max(\n(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\n\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\ndir * rcpDirMin)) * localTexelSize;\n\nvec4 rgbA = 0.5 * (\ntexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\ntexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\nvec4 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(textureSampler, vUV + dir * -0.5) +\ntexture2D(textureSampler, vUV + dir * 0.5));\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\ngl_FragColor = rgbA;\n}\nelse {\ngl_FragColor = rgbB;\n}\n}",
  14496. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\ncolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\ncolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\ncolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\ngl_FragColor = vec4(color, 1.0);\n}",
  14497. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14498. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14499. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\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#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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\nreturn dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv));\n\nif (depth.z > shadow)\n{\nreturn 0.;\n}\nreturn 1.;\n}\n\nfloat ChebychevInequality(vec2 moments, float t)\n{\nif (t <= moments.x)\n{\nreturn 1.0;\n}\n\nfloat variance = moments.y - (moments.x * moments.x);\nvariance = max(variance, 0.);\n\nfloat d = t - moments.x;\nreturn variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW;\nif (lightData.w == 0.)\n{\nlightVectorW = normalize(lightData.xyz - vPositionW);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\nresult[0] = ndl * diffuseColor.rgb;\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = ndl * spotAtten * diffuseColor.rgb;\nresult[1] = specComp * specularColor * spotAtten;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nresult[0] = vec3(0.);\nresult[1] = vec3(0.);\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\nmat3 result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\nvec3 normalW = normalize(vNormalW);\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\nmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14500. 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\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\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\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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn position;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = world * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = world * (m0 + m1 + m2);\n#endif\n\n#else\nfinalWorld = world;\n#endif\n\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef REFLECTION\nvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n}",
  14501. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14502. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14503. lensHighlightsPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float gain;\nuniform float threshold;\nuniform bool pentagon;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight = color;\nfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\nfloat lum_threshold;\nif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\nelse { lum_threshold = 0.5 + 0.44 * threshold; }\n\nluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n\nhighlight *= luminance * gain;\nhighlight.a = 1.0;\n\nreturn highlight;\n}\n\nvoid main(void)\n{\nvec4 original = texture2D(textureSampler, vUV);\n\nif (gain == -1.0) {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nreturn;\n}\n\nfloat w = 2.0 / screen_width;\nfloat h = 2.0 / screen_height;\n\nfloat weight = 1.0;\n\nvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n\nif (pentagon) {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n}\nelse {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n}\n\nblurred /= 39.0;\n\ngl_FragColor = blurred;\n\n}",
  14504. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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{\nfloat val = 0.0;\nfloat freq = 1.0;\nfor (int i = 0; i < 4; i++)\n{\nval += abs(noise(P*freq) / freq);\nfreq *= 2.07;\n}\nreturn val;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\nvec3 col;\nx = 0.5*(x + 1.);\nx = sqrt(x);\nx = sqrt(x);\nx = sqrt(x);\ncol = vec3(.2 + .75*x);\ncol.b *= 0.95;\nreturn col;\n}\n\nvoid main()\n{\nfloat brickW = 1.0 / numberOfTilesWidth;\nfloat brickH = 1.0 / numberOfTilesHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.01;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\nt += amplitude * turbulence(brickvUV.xy);\nt = sin(t);\ncolor = marble_color(t);\n}\n\ngl_FragColor = vec4(color, 0.0);\n}",
  14505. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\nvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\nfloat rSq = theta.x * theta.x + theta.y * theta.y;\nvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\nreturn LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\nvec2 tc = HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nelse{\ngl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n}\n}",
  14506. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\ngl_FragColor = color;\n}",
  14507. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\nvec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14508. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\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\nif (fClipDistance > 0.0)\ndiscard;\n#endif\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\ngl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14509. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\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) {\nvec3 viewPos = (view * vec4(position, 1.0)).xyz;\nvec3 cornerPos;\nfloat size = options.y;\nfloat angle = options.x;\nvec2 offset = options.zw;\n\ncornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\nvUV = offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos = invView * vec4(viewPos, 1.0);\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14510. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(textureSampler, vUV);\n}",
  14511. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14512. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\nvPosition = position;\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14513. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\nfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\nvec2 uv = vUV - vec2(0.5);\nvec2 offset = uv * depth * ref;\nvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\ngl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14514. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\nvec3 color = roadColor * ratioy;\ngl_FragColor = vec4(color, 1.0);\n}",
  14515. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\nconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\nconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\nvec4 res = fract(depth * bit_shift);\nres -= res.xxyz * bit_mask;\n\nreturn res;\n}\n\nvec2 packHalf(float depth)\n{\nconst vec2 bitOffset = vec2(1.0 / 255., 0.);\nvec2 color = vec2(depth, fract(depth * 255.));\n\nreturn color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\nfloat depth = vPosition.z / vPosition.w;\ndepth = depth * 0.5 + 0.5;\n\n#ifdef VSM\nfloat moment1 = depth;\nfloat moment2 = moment1 * moment1;\n\ngl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\ngl_FragColor = pack(depth);\n#endif\n}",
  14516. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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\nvarying vec4 vPosition;\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\nvPosition = viewProjection * finalWorld * vec4(position, 1.0);\ngl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14517. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\nif (alphaTest)\n{\nif (baseColor.a < 0.95)\ndiscard;\n}\n\nbaseColor *= vColor;\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\nbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = baseColor;\n}",
  14518. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\nvec2 cornerPos;\n\nfloat angle = position.w;\nvec2 size = vec2(options.x, options.y);\nvec2 offset = options.zw;\nvec2 uvScale = textureInfos.xy;\n\ncornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\n\nvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\nvUV = (uvOffset + cellInfo.zw) * uvScale;\n\n#ifdef FOG\nfFogDistance = viewPos.z;\n#endif\n}",
  14519. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.001);\nconst vec2 offset2 = vec2(0.001, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\nfloat depth1 = texture2D(textureSampler, coords + offset1).r;\nfloat depth2 = texture2D(textureSampler, coords + offset2).r;\n\nvec3 p1 = vec3(offset1, depth1 - depth);\nvec3 p2 = vec3(offset2, depth2 - depth);\n\nvec3 normal = cross(p1, p2);\nnormal.z = -normal.z;\n\nreturn normalize(normal);\n}\n\nvoid main(void)\n{\nconst float base = 0.2;\n\nvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\nfloat depth = texture2D(textureSampler, vUV).r;\nvec3 position = vec3(vUV, depth);\nvec3 normal = normalFromDepth(depth, vUV);\nfloat radiusDepth = radius / depth;\nfloat occlusion = 0.0;\n\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\n\nfor (int i = 0; i < SAMPLES; i++)\n{\nray = radiusDepth * reflect(sampleSphere[i], random);\nhemiRay = position + sign(dot(ray, normal)) * ray;\n\nocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\ndifference = depth - occlusionDepth;\n\nocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n}\n\nfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\nfloat result = clamp(ao + base, 0.0, 1.0);\ngl_FragColor.r = result;\ngl_FragColor.g = result;\ngl_FragColor.b = result;\ngl_FragColor.a = 1.0;\n}",
  14520. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\ngl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14521. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\nvec2 tc = vUV;\nvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\ndeltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\nfloat illuminationDecay = 1.0;\n\nvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\nfor(int i=0; i < NUM_SAMPLES; i++) {\ntc -= deltaTexCoord;\nvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\nsample *= illuminationDecay * weight;\ncolor += sample;\nilluminationDecay *= decay;\n}\n\nvec4 realColor = texture2D(textureSampler, vUV);\ngl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14522. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\nif (diffuseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef OPACITY\nvec4 opacityColor = texture2D(opacitySampler, vUV);\nfloat alpha = 1.0;\n\n#ifdef OPACITYRGB\nopacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n#else\nalpha *= opacityColor.a * opacityLevel;\n#endif\n\n#if defined(BASIC_RENDER)\ngl_FragColor = vec4(diffuseColor.rgb, alpha);\n#else\ngl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n#endif\n\ngl_FragColor.a = alpha;\n#else\n#ifndef BASIC_RENDER\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#else\ngl_FragColor = diffuseColor;\n#endif\n#endif\n\n}",
  14523. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\nvec3 wood = woodColor * ratioy;\ngl_FragColor = vec4(wood, 1.0);\n}",
  14524. };
  14525. return Effect;
  14526. })();
  14527. BABYLON.Effect = Effect;
  14528. })(BABYLON || (BABYLON = {}));
  14529. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14530. (function (BABYLON) {
  14531. var Material = (function () {
  14532. function Material(name, scene, doNotAdd) {
  14533. this.name = name;
  14534. this.checkReadyOnEveryCall = true;
  14535. this.checkReadyOnlyOnce = false;
  14536. this.state = "";
  14537. this.alpha = 1.0;
  14538. this.backFaceCulling = true;
  14539. this._wasPreviouslyReady = false;
  14540. this._fillMode = Material.TriangleFillMode;
  14541. this.pointSize = 1.0;
  14542. this.zOffset = 0;
  14543. this.id = name;
  14544. this._scene = scene;
  14545. if (!doNotAdd) {
  14546. scene.materials.push(this);
  14547. }
  14548. }
  14549. Object.defineProperty(Material, "TriangleFillMode", {
  14550. get: function () {
  14551. return Material._TriangleFillMode;
  14552. },
  14553. enumerable: true,
  14554. configurable: true
  14555. });
  14556. Object.defineProperty(Material, "WireFrameFillMode", {
  14557. get: function () {
  14558. return Material._WireFrameFillMode;
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Object.defineProperty(Material, "PointFillMode", {
  14564. get: function () {
  14565. return Material._PointFillMode;
  14566. },
  14567. enumerable: true,
  14568. configurable: true
  14569. });
  14570. Object.defineProperty(Material.prototype, "wireframe", {
  14571. get: function () {
  14572. return this._fillMode === Material.WireFrameFillMode;
  14573. },
  14574. set: function (value) {
  14575. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14576. },
  14577. enumerable: true,
  14578. configurable: true
  14579. });
  14580. Object.defineProperty(Material.prototype, "pointsCloud", {
  14581. get: function () {
  14582. return this._fillMode === Material.PointFillMode;
  14583. },
  14584. set: function (value) {
  14585. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14586. },
  14587. enumerable: true,
  14588. configurable: true
  14589. });
  14590. Object.defineProperty(Material.prototype, "fillMode", {
  14591. get: function () {
  14592. return this._fillMode;
  14593. },
  14594. set: function (value) {
  14595. this._fillMode = value;
  14596. },
  14597. enumerable: true,
  14598. configurable: true
  14599. });
  14600. Material.prototype.isReady = function (mesh, useInstances) {
  14601. return true;
  14602. };
  14603. Material.prototype.getEffect = function () {
  14604. return this._effect;
  14605. };
  14606. Material.prototype.getScene = function () {
  14607. return this._scene;
  14608. };
  14609. Material.prototype.needAlphaBlending = function () {
  14610. return (this.alpha < 1.0);
  14611. };
  14612. Material.prototype.needAlphaTesting = function () {
  14613. return false;
  14614. };
  14615. Material.prototype.getAlphaTestTexture = function () {
  14616. return null;
  14617. };
  14618. Material.prototype.trackCreation = function (onCompiled, onError) {
  14619. };
  14620. Material.prototype._preBind = function () {
  14621. var engine = this._scene.getEngine();
  14622. engine.enableEffect(this._effect);
  14623. engine.setState(this.backFaceCulling, this.zOffset);
  14624. };
  14625. Material.prototype.bind = function (world, mesh) {
  14626. this._scene._cachedMaterial = this;
  14627. if (this.onBind) {
  14628. this.onBind(this, mesh);
  14629. }
  14630. };
  14631. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14632. };
  14633. Material.prototype.unbind = function () {
  14634. };
  14635. Material.prototype.dispose = function (forceDisposeEffect) {
  14636. // Remove from scene
  14637. var index = this._scene.materials.indexOf(this);
  14638. this._scene.materials.splice(index, 1);
  14639. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14640. if (forceDisposeEffect && this._effect) {
  14641. this._scene.getEngine()._releaseEffect(this._effect);
  14642. this._effect = null;
  14643. }
  14644. // Callback
  14645. if (this.onDispose) {
  14646. this.onDispose();
  14647. }
  14648. };
  14649. Material._TriangleFillMode = 0;
  14650. Material._WireFrameFillMode = 1;
  14651. Material._PointFillMode = 2;
  14652. return Material;
  14653. })();
  14654. BABYLON.Material = Material;
  14655. })(BABYLON || (BABYLON = {}));
  14656. //# sourceMappingURL=babylon.material.js.map
  14657. var BABYLON;
  14658. (function (BABYLON) {
  14659. var maxSimultaneousLights = 4;
  14660. var FresnelParameters = (function () {
  14661. function FresnelParameters() {
  14662. this.isEnabled = true;
  14663. this.leftColor = BABYLON.Color3.White();
  14664. this.rightColor = BABYLON.Color3.Black();
  14665. this.bias = 0;
  14666. this.power = 1;
  14667. }
  14668. return FresnelParameters;
  14669. })();
  14670. BABYLON.FresnelParameters = FresnelParameters;
  14671. var StandardMaterial = (function (_super) {
  14672. __extends(StandardMaterial, _super);
  14673. function StandardMaterial(name, scene) {
  14674. var _this = this;
  14675. _super.call(this, name, scene);
  14676. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14677. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14678. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14679. this.specularPower = 64;
  14680. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14681. this.useAlphaFromDiffuseTexture = false;
  14682. this.useSpecularOverAlpha = true;
  14683. this.fogEnabled = true;
  14684. this._cachedDefines = null;
  14685. this._renderTargets = new BABYLON.SmartArray(16);
  14686. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14687. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14688. this._scaledDiffuse = new BABYLON.Color3();
  14689. this._scaledSpecular = new BABYLON.Color3();
  14690. this.getRenderTargetTextures = function () {
  14691. _this._renderTargets.reset();
  14692. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14693. _this._renderTargets.push(_this.reflectionTexture);
  14694. }
  14695. return _this._renderTargets;
  14696. };
  14697. }
  14698. StandardMaterial.prototype.needAlphaBlending = function () {
  14699. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14700. };
  14701. StandardMaterial.prototype.needAlphaTesting = function () {
  14702. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14703. };
  14704. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14705. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14706. };
  14707. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14708. return this.diffuseTexture;
  14709. };
  14710. // Methods
  14711. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14712. if (this.checkReadyOnlyOnce) {
  14713. if (this._wasPreviouslyReady) {
  14714. }
  14715. }
  14716. var scene = this.getScene();
  14717. if (!this.checkReadyOnEveryCall) {
  14718. if (this._renderId === scene.getRenderId()) {
  14719. }
  14720. }
  14721. var engine = scene.getEngine();
  14722. var defines = [];
  14723. var fallbacks = new BABYLON.EffectFallbacks();
  14724. var needNormals = false;
  14725. var needUVs = false;
  14726. // Textures
  14727. if (scene.texturesEnabled) {
  14728. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14729. if (!this.diffuseTexture.isReady()) {
  14730. return false;
  14731. }
  14732. else {
  14733. needUVs = true;
  14734. defines.push("#define DIFFUSE");
  14735. }
  14736. }
  14737. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14738. if (!this.ambientTexture.isReady()) {
  14739. return false;
  14740. }
  14741. else {
  14742. needUVs = true;
  14743. defines.push("#define AMBIENT");
  14744. }
  14745. }
  14746. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14747. if (!this.opacityTexture.isReady()) {
  14748. return false;
  14749. }
  14750. else {
  14751. needUVs = true;
  14752. defines.push("#define OPACITY");
  14753. if (this.opacityTexture.getAlphaFromRGB) {
  14754. defines.push("#define OPACITYRGB");
  14755. }
  14756. }
  14757. }
  14758. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14759. if (!this.reflectionTexture.isReady()) {
  14760. return false;
  14761. }
  14762. else {
  14763. needNormals = true;
  14764. needUVs = true;
  14765. defines.push("#define REFLECTION");
  14766. fallbacks.addFallback(0, "REFLECTION");
  14767. }
  14768. }
  14769. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14770. if (!this.emissiveTexture.isReady()) {
  14771. return false;
  14772. }
  14773. else {
  14774. needUVs = true;
  14775. defines.push("#define EMISSIVE");
  14776. }
  14777. }
  14778. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14779. if (!this.specularTexture.isReady()) {
  14780. return false;
  14781. }
  14782. else {
  14783. needUVs = true;
  14784. defines.push("#define SPECULAR");
  14785. fallbacks.addFallback(0, "SPECULAR");
  14786. }
  14787. }
  14788. }
  14789. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14790. if (!this.bumpTexture.isReady()) {
  14791. return false;
  14792. }
  14793. else {
  14794. needUVs = true;
  14795. defines.push("#define BUMP");
  14796. fallbacks.addFallback(0, "BUMP");
  14797. }
  14798. }
  14799. // Effect
  14800. if (this.useSpecularOverAlpha) {
  14801. defines.push("#define SPECULAROVERALPHA");
  14802. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14803. }
  14804. if (scene.clipPlane) {
  14805. defines.push("#define CLIPPLANE");
  14806. }
  14807. if (engine.getAlphaTesting()) {
  14808. defines.push("#define ALPHATEST");
  14809. }
  14810. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14811. defines.push("#define ALPHAFROMDIFFUSE");
  14812. }
  14813. // Point size
  14814. if (this.pointsCloud || scene.forcePointsCloud) {
  14815. defines.push("#define POINTSIZE");
  14816. }
  14817. // Fog
  14818. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14819. defines.push("#define FOG");
  14820. fallbacks.addFallback(1, "FOG");
  14821. }
  14822. var shadowsActivated = false;
  14823. var lightIndex = 0;
  14824. if (scene.lightsEnabled) {
  14825. for (var index = 0; index < scene.lights.length; index++) {
  14826. var light = scene.lights[index];
  14827. if (!light.isEnabled()) {
  14828. continue;
  14829. }
  14830. // Excluded check
  14831. if (light._excludedMeshesIds.length > 0) {
  14832. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14833. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14834. if (excludedMesh) {
  14835. light.excludedMeshes.push(excludedMesh);
  14836. }
  14837. }
  14838. light._excludedMeshesIds = [];
  14839. }
  14840. // Included check
  14841. if (light._includedOnlyMeshesIds.length > 0) {
  14842. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14843. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14844. if (includedOnlyMesh) {
  14845. light.includedOnlyMeshes.push(includedOnlyMesh);
  14846. }
  14847. }
  14848. light._includedOnlyMeshesIds = [];
  14849. }
  14850. if (!light.canAffectMesh(mesh)) {
  14851. continue;
  14852. }
  14853. needNormals = true;
  14854. defines.push("#define LIGHT" + lightIndex);
  14855. if (lightIndex > 0) {
  14856. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14857. }
  14858. var type;
  14859. if (light instanceof BABYLON.SpotLight) {
  14860. type = "#define SPOTLIGHT" + lightIndex;
  14861. }
  14862. else if (light instanceof BABYLON.HemisphericLight) {
  14863. type = "#define HEMILIGHT" + lightIndex;
  14864. }
  14865. else {
  14866. type = "#define POINTDIRLIGHT" + lightIndex;
  14867. }
  14868. defines.push(type);
  14869. if (lightIndex > 0) {
  14870. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14871. }
  14872. // Shadows
  14873. if (scene.shadowsEnabled) {
  14874. var shadowGenerator = light.getShadowGenerator();
  14875. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14876. defines.push("#define SHADOW" + lightIndex);
  14877. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14878. if (!shadowsActivated) {
  14879. defines.push("#define SHADOWS");
  14880. shadowsActivated = true;
  14881. }
  14882. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14883. defines.push("#define SHADOWVSM" + lightIndex);
  14884. if (lightIndex > 0) {
  14885. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14886. }
  14887. }
  14888. if (shadowGenerator.usePoissonSampling) {
  14889. defines.push("#define SHADOWPCF" + lightIndex);
  14890. if (lightIndex > 0) {
  14891. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14892. }
  14893. }
  14894. }
  14895. }
  14896. lightIndex++;
  14897. if (lightIndex === maxSimultaneousLights)
  14898. break;
  14899. }
  14900. }
  14901. if (StandardMaterial.FresnelEnabled) {
  14902. // Fresnel
  14903. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14904. var fresnelRank = 1;
  14905. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14906. defines.push("#define DIFFUSEFRESNEL");
  14907. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14908. fresnelRank++;
  14909. }
  14910. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14911. defines.push("#define OPACITYFRESNEL");
  14912. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14913. fresnelRank++;
  14914. }
  14915. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14916. defines.push("#define REFLECTIONFRESNEL");
  14917. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14918. fresnelRank++;
  14919. }
  14920. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14921. defines.push("#define EMISSIVEFRESNEL");
  14922. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14923. fresnelRank++;
  14924. }
  14925. needNormals = true;
  14926. defines.push("#define FRESNEL");
  14927. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14928. }
  14929. }
  14930. // Attribs
  14931. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14932. if (mesh) {
  14933. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14934. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14935. defines.push("#define NORMAL");
  14936. }
  14937. if (needUVs) {
  14938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14939. attribs.push(BABYLON.VertexBuffer.UVKind);
  14940. defines.push("#define UV1");
  14941. }
  14942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14944. defines.push("#define UV2");
  14945. }
  14946. }
  14947. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14948. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14949. defines.push("#define VERTEXCOLOR");
  14950. if (mesh.hasVertexAlpha) {
  14951. defines.push("#define VERTEXALPHA");
  14952. }
  14953. }
  14954. if (mesh.useBones) {
  14955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14957. defines.push("#define BONES");
  14958. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14959. defines.push("#define BONES4");
  14960. fallbacks.addFallback(0, "BONES4");
  14961. }
  14962. // Instances
  14963. if (useInstances) {
  14964. defines.push("#define INSTANCES");
  14965. attribs.push("world0");
  14966. attribs.push("world1");
  14967. attribs.push("world2");
  14968. attribs.push("world3");
  14969. }
  14970. }
  14971. // Get correct effect
  14972. var join = defines.join("\n");
  14973. if (this._cachedDefines !== join) {
  14974. this._cachedDefines = join;
  14975. scene.resetCachedMaterial();
  14976. // Legacy browser patch
  14977. var shaderName = "default";
  14978. if (!scene.getEngine().getCaps().standardDerivatives) {
  14979. shaderName = "legacydefault";
  14980. }
  14981. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  14982. }
  14983. if (!this._effect.isReady()) {
  14984. return false;
  14985. }
  14986. this._renderId = scene.getRenderId();
  14987. this._wasPreviouslyReady = true;
  14988. return true;
  14989. };
  14990. StandardMaterial.prototype.unbind = function () {
  14991. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14992. this._effect.setTexture("reflection2DSampler", null);
  14993. }
  14994. };
  14995. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14996. this._effect.setMatrix("world", world);
  14997. };
  14998. StandardMaterial.prototype.bind = function (world, mesh) {
  14999. var scene = this.getScene();
  15000. // Matrices
  15001. this.bindOnlyWorldMatrix(world);
  15002. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15003. // Bones
  15004. if (mesh && mesh.useBones) {
  15005. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15006. }
  15007. if (scene.getCachedMaterial() !== this) {
  15008. if (StandardMaterial.FresnelEnabled) {
  15009. // Fresnel
  15010. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15011. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15012. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15013. }
  15014. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15015. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15016. }
  15017. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15018. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15019. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15020. }
  15021. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15022. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15023. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15024. }
  15025. }
  15026. // Textures
  15027. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15028. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15029. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15030. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15031. }
  15032. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15033. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15034. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15035. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15036. }
  15037. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15038. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15039. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15040. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15041. }
  15042. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15043. if (this.reflectionTexture.isCube) {
  15044. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15045. }
  15046. else {
  15047. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15048. }
  15049. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15050. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15051. }
  15052. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15053. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15054. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15055. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15056. }
  15057. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15058. this._effect.setTexture("specularSampler", this.specularTexture);
  15059. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15060. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15061. }
  15062. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15063. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15064. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15065. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15066. }
  15067. // Clip plane
  15068. if (scene.clipPlane) {
  15069. var clipPlane = scene.clipPlane;
  15070. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15071. }
  15072. // Point size
  15073. if (this.pointsCloud) {
  15074. this._effect.setFloat("pointSize", this.pointSize);
  15075. }
  15076. // Colors
  15077. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15078. // Scaling down color according to emissive
  15079. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15080. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15081. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15082. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15083. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15084. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15085. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15086. }
  15087. // Scaling down color according to emissive
  15088. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15089. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15090. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15091. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15092. if (scene.lightsEnabled) {
  15093. var lightIndex = 0;
  15094. for (var index = 0; index < scene.lights.length; index++) {
  15095. var light = scene.lights[index];
  15096. if (!light.isEnabled()) {
  15097. continue;
  15098. }
  15099. if (!light.canAffectMesh(mesh)) {
  15100. continue;
  15101. }
  15102. if (light instanceof BABYLON.PointLight) {
  15103. // Point Light
  15104. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15105. }
  15106. else if (light instanceof BABYLON.DirectionalLight) {
  15107. // Directional Light
  15108. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15109. }
  15110. else if (light instanceof BABYLON.SpotLight) {
  15111. // Spot Light
  15112. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15113. }
  15114. else if (light instanceof BABYLON.HemisphericLight) {
  15115. // Hemispheric Light
  15116. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15117. }
  15118. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15119. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15120. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15121. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15122. // Shadows
  15123. if (scene.shadowsEnabled) {
  15124. var shadowGenerator = light.getShadowGenerator();
  15125. if (mesh.receiveShadows && shadowGenerator) {
  15126. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15127. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15128. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15129. }
  15130. }
  15131. lightIndex++;
  15132. if (lightIndex === maxSimultaneousLights)
  15133. break;
  15134. }
  15135. }
  15136. // View
  15137. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15138. this._effect.setMatrix("view", scene.getViewMatrix());
  15139. }
  15140. // Fog
  15141. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15142. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15143. this._effect.setColor3("vFogColor", scene.fogColor);
  15144. }
  15145. _super.prototype.bind.call(this, world, mesh);
  15146. };
  15147. StandardMaterial.prototype.getAnimatables = function () {
  15148. var results = [];
  15149. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15150. results.push(this.diffuseTexture);
  15151. }
  15152. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15153. results.push(this.ambientTexture);
  15154. }
  15155. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15156. results.push(this.opacityTexture);
  15157. }
  15158. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15159. results.push(this.reflectionTexture);
  15160. }
  15161. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15162. results.push(this.emissiveTexture);
  15163. }
  15164. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15165. results.push(this.specularTexture);
  15166. }
  15167. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15168. results.push(this.bumpTexture);
  15169. }
  15170. return results;
  15171. };
  15172. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15173. if (this.diffuseTexture) {
  15174. this.diffuseTexture.dispose();
  15175. }
  15176. if (this.ambientTexture) {
  15177. this.ambientTexture.dispose();
  15178. }
  15179. if (this.opacityTexture) {
  15180. this.opacityTexture.dispose();
  15181. }
  15182. if (this.reflectionTexture) {
  15183. this.reflectionTexture.dispose();
  15184. }
  15185. if (this.emissiveTexture) {
  15186. this.emissiveTexture.dispose();
  15187. }
  15188. if (this.specularTexture) {
  15189. this.specularTexture.dispose();
  15190. }
  15191. if (this.bumpTexture) {
  15192. this.bumpTexture.dispose();
  15193. }
  15194. _super.prototype.dispose.call(this, forceDisposeEffect);
  15195. };
  15196. StandardMaterial.prototype.clone = function (name) {
  15197. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15198. // Base material
  15199. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15200. newStandardMaterial.alpha = this.alpha;
  15201. newStandardMaterial.fillMode = this.fillMode;
  15202. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15203. // Standard material
  15204. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15205. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15206. }
  15207. if (this.ambientTexture && this.ambientTexture.clone) {
  15208. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15209. }
  15210. if (this.opacityTexture && this.opacityTexture.clone) {
  15211. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15212. }
  15213. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15214. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15215. }
  15216. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15217. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15218. }
  15219. if (this.specularTexture && this.specularTexture.clone) {
  15220. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15221. }
  15222. if (this.bumpTexture && this.bumpTexture.clone) {
  15223. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15224. }
  15225. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15226. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15227. newStandardMaterial.specularColor = this.specularColor.clone();
  15228. newStandardMaterial.specularPower = this.specularPower;
  15229. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15230. return newStandardMaterial;
  15231. };
  15232. // Statics
  15233. // Flags used to enable or disable a type of texture for all Standard Materials
  15234. StandardMaterial.DiffuseTextureEnabled = true;
  15235. StandardMaterial.AmbientTextureEnabled = true;
  15236. StandardMaterial.OpacityTextureEnabled = true;
  15237. StandardMaterial.ReflectionTextureEnabled = true;
  15238. StandardMaterial.EmissiveTextureEnabled = true;
  15239. StandardMaterial.SpecularTextureEnabled = true;
  15240. StandardMaterial.BumpTextureEnabled = true;
  15241. StandardMaterial.FresnelEnabled = true;
  15242. return StandardMaterial;
  15243. })(BABYLON.Material);
  15244. BABYLON.StandardMaterial = StandardMaterial;
  15245. })(BABYLON || (BABYLON = {}));
  15246. //# sourceMappingURL=babylon.standardMaterial.js.map
  15247. var BABYLON;
  15248. (function (BABYLON) {
  15249. var MultiMaterial = (function (_super) {
  15250. __extends(MultiMaterial, _super);
  15251. function MultiMaterial(name, scene) {
  15252. _super.call(this, name, scene, true);
  15253. this.subMaterials = new Array();
  15254. scene.multiMaterials.push(this);
  15255. }
  15256. // Properties
  15257. MultiMaterial.prototype.getSubMaterial = function (index) {
  15258. if (index < 0 || index >= this.subMaterials.length) {
  15259. return this.getScene().defaultMaterial;
  15260. }
  15261. return this.subMaterials[index];
  15262. };
  15263. // Methods
  15264. MultiMaterial.prototype.isReady = function (mesh) {
  15265. for (var index = 0; index < this.subMaterials.length; index++) {
  15266. var subMaterial = this.subMaterials[index];
  15267. if (subMaterial) {
  15268. if (!this.subMaterials[index].isReady(mesh)) {
  15269. return false;
  15270. }
  15271. }
  15272. }
  15273. return true;
  15274. };
  15275. return MultiMaterial;
  15276. })(BABYLON.Material);
  15277. BABYLON.MultiMaterial = MultiMaterial;
  15278. })(BABYLON || (BABYLON = {}));
  15279. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15280. (function (BABYLON) {
  15281. var Database = (function () {
  15282. function Database(urlToScene, callbackManifestChecked) {
  15283. // Handling various flavors of prefixed version of IndexedDB
  15284. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15285. this.callbackManifestChecked = callbackManifestChecked;
  15286. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15287. this.db = null;
  15288. this.enableSceneOffline = false;
  15289. this.enableTexturesOffline = false;
  15290. this.manifestVersionFound = 0;
  15291. this.mustUpdateRessources = false;
  15292. this.hasReachedQuota = false;
  15293. this.checkManifestFile();
  15294. }
  15295. Database.prototype.checkManifestFile = function () {
  15296. var _this = this;
  15297. function noManifestFile() {
  15298. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15299. that.enableSceneOffline = false;
  15300. that.enableTexturesOffline = false;
  15301. that.callbackManifestChecked(false);
  15302. }
  15303. var that = this;
  15304. var manifestURL = this.currentSceneUrl + ".manifest";
  15305. var xhr = new XMLHttpRequest();
  15306. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15307. xhr.open("GET", manifestURLTimeStamped, true);
  15308. xhr.addEventListener("load", function () {
  15309. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15310. try {
  15311. var manifestFile = JSON.parse(xhr.response);
  15312. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15313. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15314. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15315. _this.manifestVersionFound = manifestFile.version;
  15316. }
  15317. if (_this.callbackManifestChecked) {
  15318. _this.callbackManifestChecked(true);
  15319. }
  15320. }
  15321. catch (ex) {
  15322. noManifestFile();
  15323. }
  15324. }
  15325. else {
  15326. noManifestFile();
  15327. }
  15328. }, false);
  15329. xhr.addEventListener("error", function (event) {
  15330. noManifestFile();
  15331. }, false);
  15332. try {
  15333. xhr.send();
  15334. }
  15335. catch (ex) {
  15336. BABYLON.Tools.Error("Error on XHR send request.");
  15337. that.callbackManifestChecked(false);
  15338. }
  15339. };
  15340. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15341. var _this = this;
  15342. function handleError() {
  15343. that.isSupported = false;
  15344. if (errorCallback)
  15345. errorCallback();
  15346. }
  15347. var that = this;
  15348. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15349. // Your browser doesn't support IndexedDB
  15350. this.isSupported = false;
  15351. if (errorCallback)
  15352. errorCallback();
  15353. }
  15354. else {
  15355. // If the DB hasn't been opened or created yet
  15356. if (!this.db) {
  15357. this.hasReachedQuota = false;
  15358. this.isSupported = true;
  15359. var request = this.idbFactory.open("babylonjs", 1);
  15360. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15361. request.onerror = function (event) {
  15362. handleError();
  15363. };
  15364. // executes when a version change transaction cannot complete due to other active transactions
  15365. request.onblocked = function (event) {
  15366. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15367. handleError();
  15368. };
  15369. // DB has been opened successfully
  15370. request.onsuccess = function (event) {
  15371. _this.db = request.result;
  15372. successCallback();
  15373. };
  15374. // Initialization of the DB. Creating Scenes & Textures stores
  15375. request.onupgradeneeded = function (event) {
  15376. _this.db = (event.target).result;
  15377. try {
  15378. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15379. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15380. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15381. }
  15382. catch (ex) {
  15383. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15384. handleError();
  15385. }
  15386. };
  15387. }
  15388. else {
  15389. if (successCallback)
  15390. successCallback();
  15391. }
  15392. }
  15393. };
  15394. Database.prototype.loadImageFromDB = function (url, image) {
  15395. var _this = this;
  15396. var completeURL = Database.ReturnFullUrlLocation(url);
  15397. var saveAndLoadImage = function () {
  15398. if (!_this.hasReachedQuota && _this.db !== null) {
  15399. // the texture is not yet in the DB, let's try to save it
  15400. _this._saveImageIntoDBAsync(completeURL, image);
  15401. }
  15402. else {
  15403. image.src = url;
  15404. }
  15405. };
  15406. if (!this.mustUpdateRessources) {
  15407. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15408. }
  15409. else {
  15410. saveAndLoadImage();
  15411. }
  15412. };
  15413. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15414. if (this.isSupported && this.db !== null) {
  15415. var texture;
  15416. var transaction = this.db.transaction(["textures"]);
  15417. transaction.onabort = function (event) {
  15418. image.src = url;
  15419. };
  15420. transaction.oncomplete = function (event) {
  15421. var blobTextureURL;
  15422. if (texture) {
  15423. var URL = window.URL || window.webkitURL;
  15424. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15425. image.onerror = function () {
  15426. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15427. image.src = url;
  15428. };
  15429. image.src = blobTextureURL;
  15430. }
  15431. else {
  15432. notInDBCallback();
  15433. }
  15434. };
  15435. var getRequest = transaction.objectStore("textures").get(url);
  15436. getRequest.onsuccess = function (event) {
  15437. texture = (event.target).result;
  15438. };
  15439. getRequest.onerror = function (event) {
  15440. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15441. image.src = url;
  15442. };
  15443. }
  15444. else {
  15445. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15446. image.src = url;
  15447. }
  15448. };
  15449. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15450. var _this = this;
  15451. if (this.isSupported) {
  15452. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15453. var generateBlobUrl = function () {
  15454. var blobTextureURL;
  15455. if (blob) {
  15456. var URL = window.URL || window.webkitURL;
  15457. try {
  15458. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15459. }
  15460. catch (ex) {
  15461. blobTextureURL = URL.createObjectURL(blob);
  15462. }
  15463. }
  15464. image.src = blobTextureURL;
  15465. };
  15466. if (Database.isUASupportingBlobStorage) {
  15467. var xhr = new XMLHttpRequest(), blob;
  15468. xhr.open("GET", url, true);
  15469. xhr.responseType = "blob";
  15470. xhr.addEventListener("load", function () {
  15471. if (xhr.status === 200) {
  15472. // Blob as response (XHR2)
  15473. blob = xhr.response;
  15474. var transaction = _this.db.transaction(["textures"], "readwrite");
  15475. // the transaction could abort because of a QuotaExceededError error
  15476. transaction.onabort = function (event) {
  15477. try {
  15478. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15479. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15480. this.hasReachedQuota = true;
  15481. }
  15482. }
  15483. catch (ex) {
  15484. }
  15485. generateBlobUrl();
  15486. };
  15487. transaction.oncomplete = function (event) {
  15488. generateBlobUrl();
  15489. };
  15490. var newTexture = { textureUrl: url, data: blob };
  15491. try {
  15492. // Put the blob into the dabase
  15493. var addRequest = transaction.objectStore("textures").put(newTexture);
  15494. addRequest.onsuccess = function (event) {
  15495. };
  15496. addRequest.onerror = function (event) {
  15497. generateBlobUrl();
  15498. };
  15499. }
  15500. catch (ex) {
  15501. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15502. if (ex.code === 25) {
  15503. Database.isUASupportingBlobStorage = false;
  15504. }
  15505. image.src = url;
  15506. }
  15507. }
  15508. else {
  15509. image.src = url;
  15510. }
  15511. }, false);
  15512. xhr.addEventListener("error", function (event) {
  15513. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15514. image.src = url;
  15515. }, false);
  15516. xhr.send();
  15517. }
  15518. else {
  15519. image.src = url;
  15520. }
  15521. }
  15522. else {
  15523. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15524. image.src = url;
  15525. }
  15526. };
  15527. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15528. var _this = this;
  15529. var updateVersion = function (event) {
  15530. // the version is not yet in the DB or we need to update it
  15531. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15532. };
  15533. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15534. };
  15535. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15536. var _this = this;
  15537. if (this.isSupported) {
  15538. var version;
  15539. try {
  15540. var transaction = this.db.transaction(["versions"]);
  15541. transaction.oncomplete = function (event) {
  15542. if (version) {
  15543. // If the version in the JSON file is > than the version in DB
  15544. if (_this.manifestVersionFound > version.data) {
  15545. _this.mustUpdateRessources = true;
  15546. updateInDBCallback();
  15547. }
  15548. else {
  15549. callback(version.data);
  15550. }
  15551. }
  15552. else {
  15553. _this.mustUpdateRessources = true;
  15554. updateInDBCallback();
  15555. }
  15556. };
  15557. transaction.onabort = function (event) {
  15558. callback(-1);
  15559. };
  15560. var getRequest = transaction.objectStore("versions").get(url);
  15561. getRequest.onsuccess = function (event) {
  15562. version = (event.target).result;
  15563. };
  15564. getRequest.onerror = function (event) {
  15565. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15566. callback(-1);
  15567. };
  15568. }
  15569. catch (ex) {
  15570. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15571. callback(-1);
  15572. }
  15573. }
  15574. else {
  15575. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15576. callback(-1);
  15577. }
  15578. };
  15579. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15580. var _this = this;
  15581. if (this.isSupported && !this.hasReachedQuota) {
  15582. try {
  15583. // Open a transaction to the database
  15584. var transaction = this.db.transaction(["versions"], "readwrite");
  15585. // the transaction could abort because of a QuotaExceededError error
  15586. transaction.onabort = function (event) {
  15587. try {
  15588. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15589. _this.hasReachedQuota = true;
  15590. }
  15591. }
  15592. catch (ex) {
  15593. }
  15594. callback(-1);
  15595. };
  15596. transaction.oncomplete = function (event) {
  15597. callback(_this.manifestVersionFound);
  15598. };
  15599. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15600. // Put the scene into the database
  15601. var addRequest = transaction.objectStore("versions").put(newVersion);
  15602. addRequest.onsuccess = function (event) {
  15603. };
  15604. addRequest.onerror = function (event) {
  15605. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15606. };
  15607. }
  15608. catch (ex) {
  15609. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15610. callback(-1);
  15611. }
  15612. }
  15613. else {
  15614. callback(-1);
  15615. }
  15616. };
  15617. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15618. var _this = this;
  15619. var completeUrl = Database.ReturnFullUrlLocation(url);
  15620. var saveAndLoadFile = function (event) {
  15621. // the scene is not yet in the DB, let's try to save it
  15622. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15623. };
  15624. this._checkVersionFromDB(completeUrl, function (version) {
  15625. if (version !== -1) {
  15626. if (!_this.mustUpdateRessources) {
  15627. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15628. }
  15629. else {
  15630. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15631. }
  15632. }
  15633. else {
  15634. errorCallback();
  15635. }
  15636. });
  15637. };
  15638. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15639. if (this.isSupported) {
  15640. var targetStore;
  15641. if (url.indexOf(".babylon") !== -1) {
  15642. targetStore = "scenes";
  15643. }
  15644. else {
  15645. targetStore = "textures";
  15646. }
  15647. var file;
  15648. var transaction = this.db.transaction([targetStore]);
  15649. transaction.oncomplete = function (event) {
  15650. if (file) {
  15651. callback(file.data);
  15652. }
  15653. else {
  15654. notInDBCallback();
  15655. }
  15656. };
  15657. transaction.onabort = function (event) {
  15658. notInDBCallback();
  15659. };
  15660. var getRequest = transaction.objectStore(targetStore).get(url);
  15661. getRequest.onsuccess = function (event) {
  15662. file = (event.target).result;
  15663. };
  15664. getRequest.onerror = function (event) {
  15665. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15666. notInDBCallback();
  15667. };
  15668. }
  15669. else {
  15670. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15671. callback();
  15672. }
  15673. };
  15674. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15675. var _this = this;
  15676. if (this.isSupported) {
  15677. var targetStore;
  15678. if (url.indexOf(".babylon") !== -1) {
  15679. targetStore = "scenes";
  15680. }
  15681. else {
  15682. targetStore = "textures";
  15683. }
  15684. // Create XHR
  15685. var xhr = new XMLHttpRequest(), fileData;
  15686. xhr.open("GET", url, true);
  15687. if (useArrayBuffer) {
  15688. xhr.responseType = "arraybuffer";
  15689. }
  15690. xhr.onprogress = progressCallback;
  15691. xhr.addEventListener("load", function () {
  15692. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15693. // Blob as response (XHR2)
  15694. //fileData = xhr.responseText;
  15695. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15696. if (!_this.hasReachedQuota) {
  15697. // Open a transaction to the database
  15698. var transaction = _this.db.transaction([targetStore], "readwrite");
  15699. // the transaction could abort because of a QuotaExceededError error
  15700. transaction.onabort = function (event) {
  15701. try {
  15702. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15703. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15704. this.hasReachedQuota = true;
  15705. }
  15706. }
  15707. catch (ex) {
  15708. }
  15709. callback(fileData);
  15710. };
  15711. transaction.oncomplete = function (event) {
  15712. callback(fileData);
  15713. };
  15714. var newFile;
  15715. if (targetStore === "scenes") {
  15716. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15717. }
  15718. else {
  15719. newFile = { textureUrl: url, data: fileData };
  15720. }
  15721. try {
  15722. // Put the scene into the database
  15723. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15724. addRequest.onsuccess = function (event) {
  15725. };
  15726. addRequest.onerror = function (event) {
  15727. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15728. };
  15729. }
  15730. catch (ex) {
  15731. callback(fileData);
  15732. }
  15733. }
  15734. else {
  15735. callback(fileData);
  15736. }
  15737. }
  15738. else {
  15739. callback();
  15740. }
  15741. }, false);
  15742. xhr.addEventListener("error", function (event) {
  15743. BABYLON.Tools.Error("error on XHR request.");
  15744. callback();
  15745. }, false);
  15746. xhr.send();
  15747. }
  15748. else {
  15749. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15750. callback();
  15751. }
  15752. };
  15753. Database.isUASupportingBlobStorage = true;
  15754. Database.parseURL = function (url) {
  15755. var a = document.createElement('a');
  15756. a.href = url;
  15757. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15758. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15759. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15760. return absLocation;
  15761. };
  15762. Database.ReturnFullUrlLocation = function (url) {
  15763. if (url.indexOf("http:/") === -1) {
  15764. return (BABYLON.Database.parseURL(window.location.href) + url);
  15765. }
  15766. else {
  15767. return url;
  15768. }
  15769. };
  15770. return Database;
  15771. })();
  15772. BABYLON.Database = Database;
  15773. })(BABYLON || (BABYLON = {}));
  15774. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15775. (function (BABYLON) {
  15776. var SpriteManager = (function () {
  15777. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15779. this.name = name;
  15780. this.cellSize = cellSize;
  15781. this.sprites = new Array();
  15782. this.renderingGroupId = 0;
  15783. this.fogEnabled = true;
  15784. this._vertexDeclaration = [4, 4, 4, 4];
  15785. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15786. this._capacity = capacity;
  15787. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15788. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15789. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15790. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15791. this._scene = scene;
  15792. this._scene.spriteManagers.push(this);
  15793. // VBO
  15794. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15795. var indices = [];
  15796. var index = 0;
  15797. for (var count = 0; count < capacity; count++) {
  15798. indices.push(index);
  15799. indices.push(index + 1);
  15800. indices.push(index + 2);
  15801. indices.push(index);
  15802. indices.push(index + 2);
  15803. indices.push(index + 3);
  15804. index += 4;
  15805. }
  15806. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15807. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15808. // Effects
  15809. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15810. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15811. }
  15812. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15813. var arrayOffset = index * 16;
  15814. if (offsetX === 0)
  15815. offsetX = this._epsilon;
  15816. else if (offsetX === 1)
  15817. offsetX = 1 - this._epsilon;
  15818. if (offsetY === 0)
  15819. offsetY = this._epsilon;
  15820. else if (offsetY === 1)
  15821. offsetY = 1 - this._epsilon;
  15822. this._vertices[arrayOffset] = sprite.position.x;
  15823. this._vertices[arrayOffset + 1] = sprite.position.y;
  15824. this._vertices[arrayOffset + 2] = sprite.position.z;
  15825. this._vertices[arrayOffset + 3] = sprite.angle;
  15826. this._vertices[arrayOffset + 4] = sprite.width;
  15827. this._vertices[arrayOffset + 5] = sprite.height;
  15828. this._vertices[arrayOffset + 6] = offsetX;
  15829. this._vertices[arrayOffset + 7] = offsetY;
  15830. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  15831. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  15832. var offset = (sprite.cellIndex / rowSize) >> 0;
  15833. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  15834. this._vertices[arrayOffset + 11] = offset;
  15835. // Color
  15836. this._vertices[arrayOffset + 12] = sprite.color.r;
  15837. this._vertices[arrayOffset + 13] = sprite.color.g;
  15838. this._vertices[arrayOffset + 14] = sprite.color.b;
  15839. this._vertices[arrayOffset + 15] = sprite.color.a;
  15840. };
  15841. SpriteManager.prototype.render = function () {
  15842. // Check
  15843. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15844. return;
  15845. var engine = this._scene.getEngine();
  15846. var baseSize = this._spriteTexture.getBaseSize();
  15847. // Sprites
  15848. var deltaTime = engine.getDeltaTime();
  15849. var max = Math.min(this._capacity, this.sprites.length);
  15850. var rowSize = baseSize.width / this.cellSize;
  15851. var offset = 0;
  15852. for (var index = 0; index < max; index++) {
  15853. var sprite = this.sprites[index];
  15854. if (!sprite) {
  15855. continue;
  15856. }
  15857. sprite._animate(deltaTime);
  15858. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15859. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15860. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15861. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15862. }
  15863. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15864. // Render
  15865. var effect = this._effectBase;
  15866. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15867. effect = this._effectFog;
  15868. }
  15869. engine.enableEffect(effect);
  15870. var viewMatrix = this._scene.getViewMatrix();
  15871. effect.setTexture("diffuseSampler", this._spriteTexture);
  15872. effect.setMatrix("view", viewMatrix);
  15873. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15874. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15875. // Fog
  15876. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15877. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15878. effect.setColor3("vFogColor", this._scene.fogColor);
  15879. }
  15880. // VBOs
  15881. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15882. // Draw order
  15883. effect.setBool("alphaTest", true);
  15884. engine.setColorWrite(false);
  15885. engine.draw(true, 0, max * 6);
  15886. engine.setColorWrite(true);
  15887. effect.setBool("alphaTest", false);
  15888. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15889. engine.draw(true, 0, max * 6);
  15890. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15891. };
  15892. SpriteManager.prototype.dispose = function () {
  15893. if (this._vertexBuffer) {
  15894. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15895. this._vertexBuffer = null;
  15896. }
  15897. if (this._indexBuffer) {
  15898. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15899. this._indexBuffer = null;
  15900. }
  15901. if (this._spriteTexture) {
  15902. this._spriteTexture.dispose();
  15903. this._spriteTexture = null;
  15904. }
  15905. // Remove from scene
  15906. var index = this._scene.spriteManagers.indexOf(this);
  15907. this._scene.spriteManagers.splice(index, 1);
  15908. // Callback
  15909. if (this.onDispose) {
  15910. this.onDispose();
  15911. }
  15912. };
  15913. return SpriteManager;
  15914. })();
  15915. BABYLON.SpriteManager = SpriteManager;
  15916. })(BABYLON || (BABYLON = {}));
  15917. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15918. (function (BABYLON) {
  15919. var Sprite = (function () {
  15920. function Sprite(name, manager) {
  15921. this.name = name;
  15922. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15923. this.width = 1.0;
  15924. this.height = 1.0;
  15925. this.angle = 0;
  15926. this.cellIndex = 0;
  15927. this.invertU = 0;
  15928. this.invertV = 0;
  15929. this.animations = new Array();
  15930. this._animationStarted = false;
  15931. this._loopAnimation = false;
  15932. this._fromIndex = 0;
  15933. this._toIndex = 0;
  15934. this._delay = 0;
  15935. this._direction = 1;
  15936. this._frameCount = 0;
  15937. this._time = 0;
  15938. this._manager = manager;
  15939. this._manager.sprites.push(this);
  15940. this.position = BABYLON.Vector3.Zero();
  15941. }
  15942. Object.defineProperty(Sprite.prototype, "size", {
  15943. get: function () {
  15944. return this.width;
  15945. },
  15946. set: function (value) {
  15947. this.width = value;
  15948. this.height = value;
  15949. },
  15950. enumerable: true,
  15951. configurable: true
  15952. });
  15953. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15954. this._fromIndex = from;
  15955. this._toIndex = to;
  15956. this._loopAnimation = loop;
  15957. this._delay = delay;
  15958. this._animationStarted = true;
  15959. this._direction = from < to ? 1 : -1;
  15960. this.cellIndex = from;
  15961. this._time = 0;
  15962. };
  15963. Sprite.prototype.stopAnimation = function () {
  15964. this._animationStarted = false;
  15965. };
  15966. Sprite.prototype._animate = function (deltaTime) {
  15967. if (!this._animationStarted)
  15968. return;
  15969. this._time += deltaTime;
  15970. if (this._time > this._delay) {
  15971. this._time = this._time % this._delay;
  15972. this.cellIndex += this._direction;
  15973. if (this.cellIndex == this._toIndex) {
  15974. if (this._loopAnimation) {
  15975. this.cellIndex = this._fromIndex;
  15976. }
  15977. else {
  15978. this._animationStarted = false;
  15979. if (this.disposeWhenFinishedAnimating) {
  15980. this.dispose();
  15981. }
  15982. }
  15983. }
  15984. }
  15985. };
  15986. Sprite.prototype.dispose = function () {
  15987. for (var i = 0; i < this._manager.sprites.length; i++) {
  15988. if (this._manager.sprites[i] == this) {
  15989. this._manager.sprites.splice(i, 1);
  15990. }
  15991. }
  15992. };
  15993. return Sprite;
  15994. })();
  15995. BABYLON.Sprite = Sprite;
  15996. })(BABYLON || (BABYLON = {}));
  15997. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15998. (function (BABYLON) {
  15999. var Layer = (function () {
  16000. function Layer(name, imgUrl, scene, isBackground, color) {
  16001. this.name = name;
  16002. this._vertexDeclaration = [2];
  16003. this._vertexStrideSize = 2 * 4;
  16004. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16005. this.isBackground = isBackground === undefined ? true : isBackground;
  16006. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16007. this._scene = scene;
  16008. this._scene.layers.push(this);
  16009. // VBO
  16010. var vertices = [];
  16011. vertices.push(1, 1);
  16012. vertices.push(-1, 1);
  16013. vertices.push(-1, -1);
  16014. vertices.push(1, -1);
  16015. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16016. // Indices
  16017. var indices = [];
  16018. indices.push(0);
  16019. indices.push(1);
  16020. indices.push(2);
  16021. indices.push(0);
  16022. indices.push(2);
  16023. indices.push(3);
  16024. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16025. // Effects
  16026. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16027. }
  16028. Layer.prototype.render = function () {
  16029. // Check
  16030. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16031. return;
  16032. var engine = this._scene.getEngine();
  16033. // Render
  16034. engine.enableEffect(this._effect);
  16035. engine.setState(false);
  16036. // Texture
  16037. this._effect.setTexture("textureSampler", this.texture);
  16038. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16039. // Color
  16040. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16041. // VBOs
  16042. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16043. // Draw order
  16044. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16045. engine.draw(true, 0, 6);
  16046. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16047. };
  16048. Layer.prototype.dispose = function () {
  16049. if (this._vertexBuffer) {
  16050. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16051. this._vertexBuffer = null;
  16052. }
  16053. if (this._indexBuffer) {
  16054. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16055. this._indexBuffer = null;
  16056. }
  16057. if (this.texture) {
  16058. this.texture.dispose();
  16059. this.texture = null;
  16060. }
  16061. // Remove from scene
  16062. var index = this._scene.layers.indexOf(this);
  16063. this._scene.layers.splice(index, 1);
  16064. // Callback
  16065. if (this.onDispose) {
  16066. this.onDispose();
  16067. }
  16068. };
  16069. return Layer;
  16070. })();
  16071. BABYLON.Layer = Layer;
  16072. })(BABYLON || (BABYLON = {}));
  16073. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16074. (function (BABYLON) {
  16075. var Particle = (function () {
  16076. function Particle() {
  16077. this.position = BABYLON.Vector3.Zero();
  16078. this.direction = BABYLON.Vector3.Zero();
  16079. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16080. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16081. this.lifeTime = 1.0;
  16082. this.age = 0;
  16083. this.size = 0;
  16084. this.angle = 0;
  16085. this.angularSpeed = 0;
  16086. }
  16087. Particle.prototype.copyTo = function (other) {
  16088. other.position.copyFrom(this.position);
  16089. other.direction.copyFrom(this.direction);
  16090. other.color.copyFrom(this.color);
  16091. other.colorStep.copyFrom(this.colorStep);
  16092. other.lifeTime = this.lifeTime;
  16093. other.age = this.age;
  16094. other.size = this.size;
  16095. other.angle = this.angle;
  16096. other.angularSpeed = this.angularSpeed;
  16097. };
  16098. return Particle;
  16099. })();
  16100. BABYLON.Particle = Particle;
  16101. })(BABYLON || (BABYLON = {}));
  16102. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16103. (function (BABYLON) {
  16104. var randomNumber = function (min, max) {
  16105. if (min === max) {
  16106. return (min);
  16107. }
  16108. var random = Math.random();
  16109. return ((random * (max - min)) + min);
  16110. };
  16111. var ParticleSystem = (function () {
  16112. function ParticleSystem(name, capacity, scene, customEffect) {
  16113. var _this = this;
  16114. this.name = name;
  16115. this.renderingGroupId = 0;
  16116. this.emitter = null;
  16117. this.emitRate = 10;
  16118. this.manualEmitCount = -1;
  16119. this.updateSpeed = 0.01;
  16120. this.targetStopDuration = 0;
  16121. this.disposeOnStop = false;
  16122. this.minEmitPower = 1;
  16123. this.maxEmitPower = 1;
  16124. this.minLifeTime = 1;
  16125. this.maxLifeTime = 1;
  16126. this.minSize = 1;
  16127. this.maxSize = 1;
  16128. this.minAngularSpeed = 0;
  16129. this.maxAngularSpeed = 0;
  16130. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16131. this.forceDepthWrite = false;
  16132. this.gravity = BABYLON.Vector3.Zero();
  16133. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16134. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16135. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16136. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16137. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16138. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16139. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16140. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16141. this.particles = new Array();
  16142. this._vertexDeclaration = [3, 4, 4];
  16143. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16144. this._stockParticles = new Array();
  16145. this._newPartsExcess = 0;
  16146. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16147. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16148. this._scaledDirection = BABYLON.Vector3.Zero();
  16149. this._scaledGravity = BABYLON.Vector3.Zero();
  16150. this._currentRenderId = -1;
  16151. this._started = false;
  16152. this._stopped = false;
  16153. this._actualFrame = 0;
  16154. this.id = name;
  16155. this._capacity = capacity;
  16156. this._scene = scene;
  16157. this._customEffect = customEffect;
  16158. scene.particleSystems.push(this);
  16159. // VBO
  16160. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16161. var indices = [];
  16162. var index = 0;
  16163. for (var count = 0; count < capacity; count++) {
  16164. indices.push(index);
  16165. indices.push(index + 1);
  16166. indices.push(index + 2);
  16167. indices.push(index);
  16168. indices.push(index + 2);
  16169. indices.push(index + 3);
  16170. index += 4;
  16171. }
  16172. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16173. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16174. // Default behaviors
  16175. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16176. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16177. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16178. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16179. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16180. };
  16181. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16182. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16183. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16184. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16185. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16186. };
  16187. this.updateFunction = function (particles) {
  16188. for (var index = 0; index < particles.length; index++) {
  16189. var particle = particles[index];
  16190. particle.age += _this._scaledUpdateSpeed;
  16191. if (particle.age >= particle.lifeTime) {
  16192. _this.recycleParticle(particle);
  16193. index--;
  16194. continue;
  16195. }
  16196. else {
  16197. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16198. particle.color.addInPlace(_this._scaledColorStep);
  16199. if (particle.color.a < 0)
  16200. particle.color.a = 0;
  16201. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16202. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16203. particle.position.addInPlace(_this._scaledDirection);
  16204. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16205. particle.direction.addInPlace(_this._scaledGravity);
  16206. }
  16207. }
  16208. };
  16209. }
  16210. ParticleSystem.prototype.recycleParticle = function (particle) {
  16211. var lastParticle = this.particles.pop();
  16212. if (lastParticle !== particle) {
  16213. lastParticle.copyTo(particle);
  16214. this._stockParticles.push(lastParticle);
  16215. }
  16216. };
  16217. ParticleSystem.prototype.getCapacity = function () {
  16218. return this._capacity;
  16219. };
  16220. ParticleSystem.prototype.isAlive = function () {
  16221. return this._alive;
  16222. };
  16223. ParticleSystem.prototype.isStarted = function () {
  16224. return this._started;
  16225. };
  16226. ParticleSystem.prototype.start = function () {
  16227. this._started = true;
  16228. this._stopped = false;
  16229. this._actualFrame = 0;
  16230. };
  16231. ParticleSystem.prototype.stop = function () {
  16232. this._stopped = true;
  16233. };
  16234. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16235. var offset = index * 11;
  16236. this._vertices[offset] = particle.position.x;
  16237. this._vertices[offset + 1] = particle.position.y;
  16238. this._vertices[offset + 2] = particle.position.z;
  16239. this._vertices[offset + 3] = particle.color.r;
  16240. this._vertices[offset + 4] = particle.color.g;
  16241. this._vertices[offset + 5] = particle.color.b;
  16242. this._vertices[offset + 6] = particle.color.a;
  16243. this._vertices[offset + 7] = particle.angle;
  16244. this._vertices[offset + 8] = particle.size;
  16245. this._vertices[offset + 9] = offsetX;
  16246. this._vertices[offset + 10] = offsetY;
  16247. };
  16248. ParticleSystem.prototype._update = function (newParticles) {
  16249. // Update current
  16250. this._alive = this.particles.length > 0;
  16251. this.updateFunction(this.particles);
  16252. // Add new ones
  16253. var worldMatrix;
  16254. if (this.emitter.position) {
  16255. worldMatrix = this.emitter.getWorldMatrix();
  16256. }
  16257. else {
  16258. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16259. }
  16260. for (var index = 0; index < newParticles; index++) {
  16261. if (this.particles.length === this._capacity) {
  16262. break;
  16263. }
  16264. if (this._stockParticles.length !== 0) {
  16265. var particle = this._stockParticles.pop();
  16266. particle.age = 0;
  16267. }
  16268. else {
  16269. particle = new BABYLON.Particle();
  16270. }
  16271. this.particles.push(particle);
  16272. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16273. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16274. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16275. particle.size = randomNumber(this.minSize, this.maxSize);
  16276. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16277. this.startPositionFunction(worldMatrix, particle.position);
  16278. var step = randomNumber(0, 1.0);
  16279. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16280. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16281. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16282. }
  16283. };
  16284. ParticleSystem.prototype._getEffect = function () {
  16285. if (this._customEffect) {
  16286. return this._customEffect;
  16287. }
  16288. ;
  16289. var defines = [];
  16290. if (this._scene.clipPlane) {
  16291. defines.push("#define CLIPPLANE");
  16292. }
  16293. // Effect
  16294. var join = defines.join("\n");
  16295. if (this._cachedDefines !== join) {
  16296. this._cachedDefines = join;
  16297. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16298. }
  16299. return this._effect;
  16300. };
  16301. ParticleSystem.prototype.animate = function () {
  16302. if (!this._started)
  16303. return;
  16304. var effect = this._getEffect();
  16305. // Check
  16306. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16307. return;
  16308. if (this._currentRenderId === this._scene.getRenderId()) {
  16309. return;
  16310. }
  16311. this._currentRenderId = this._scene.getRenderId();
  16312. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16313. // determine the number of particles we need to create
  16314. var emitCout;
  16315. if (this.manualEmitCount > -1) {
  16316. emitCout = this.manualEmitCount;
  16317. this.manualEmitCount = 0;
  16318. }
  16319. else {
  16320. emitCout = this.emitRate;
  16321. }
  16322. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16323. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16324. if (this._newPartsExcess > 1.0) {
  16325. newParticles += this._newPartsExcess >> 0;
  16326. this._newPartsExcess -= this._newPartsExcess >> 0;
  16327. }
  16328. this._alive = false;
  16329. if (!this._stopped) {
  16330. this._actualFrame += this._scaledUpdateSpeed;
  16331. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16332. this.stop();
  16333. }
  16334. else {
  16335. newParticles = 0;
  16336. }
  16337. this._update(newParticles);
  16338. // Stopped?
  16339. if (this._stopped) {
  16340. if (!this._alive) {
  16341. this._started = false;
  16342. if (this.disposeOnStop) {
  16343. this._scene._toBeDisposed.push(this);
  16344. }
  16345. }
  16346. }
  16347. // Update VBO
  16348. var offset = 0;
  16349. for (var index = 0; index < this.particles.length; index++) {
  16350. var particle = this.particles[index];
  16351. this._appendParticleVertex(offset++, particle, 0, 0);
  16352. this._appendParticleVertex(offset++, particle, 1, 0);
  16353. this._appendParticleVertex(offset++, particle, 1, 1);
  16354. this._appendParticleVertex(offset++, particle, 0, 1);
  16355. }
  16356. var engine = this._scene.getEngine();
  16357. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16358. };
  16359. ParticleSystem.prototype.render = function () {
  16360. var effect = this._getEffect();
  16361. // Check
  16362. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16363. return 0;
  16364. var engine = this._scene.getEngine();
  16365. // Render
  16366. engine.enableEffect(effect);
  16367. engine.setState(false);
  16368. var viewMatrix = this._scene.getViewMatrix();
  16369. effect.setTexture("diffuseSampler", this.particleTexture);
  16370. effect.setMatrix("view", viewMatrix);
  16371. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16372. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16373. if (this._scene.clipPlane) {
  16374. var clipPlane = this._scene.clipPlane;
  16375. var invView = viewMatrix.clone();
  16376. invView.invert();
  16377. effect.setMatrix("invView", invView);
  16378. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16379. }
  16380. // VBOs
  16381. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16382. // Draw order
  16383. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16384. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16385. }
  16386. else {
  16387. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16388. }
  16389. if (this.forceDepthWrite) {
  16390. engine.setDepthWrite(true);
  16391. }
  16392. engine.draw(true, 0, this.particles.length * 6);
  16393. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16394. return this.particles.length;
  16395. };
  16396. ParticleSystem.prototype.dispose = function () {
  16397. if (this._vertexBuffer) {
  16398. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16399. this._vertexBuffer = null;
  16400. }
  16401. if (this._indexBuffer) {
  16402. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16403. this._indexBuffer = null;
  16404. }
  16405. if (this.particleTexture) {
  16406. this.particleTexture.dispose();
  16407. this.particleTexture = null;
  16408. }
  16409. // Remove from scene
  16410. var index = this._scene.particleSystems.indexOf(this);
  16411. this._scene.particleSystems.splice(index, 1);
  16412. // Callback
  16413. if (this.onDispose) {
  16414. this.onDispose();
  16415. }
  16416. };
  16417. // Clone
  16418. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16419. var result = new ParticleSystem(name, this._capacity, this._scene);
  16420. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16421. if (newEmitter === undefined) {
  16422. newEmitter = this.emitter;
  16423. }
  16424. result.emitter = newEmitter;
  16425. if (this.particleTexture) {
  16426. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16427. }
  16428. result.start();
  16429. return result;
  16430. };
  16431. // Statics
  16432. ParticleSystem.BLENDMODE_ONEONE = 0;
  16433. ParticleSystem.BLENDMODE_STANDARD = 1;
  16434. return ParticleSystem;
  16435. })();
  16436. BABYLON.ParticleSystem = ParticleSystem;
  16437. })(BABYLON || (BABYLON = {}));
  16438. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16439. (function (BABYLON) {
  16440. var Animation = (function () {
  16441. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16442. this.name = name;
  16443. this.targetProperty = targetProperty;
  16444. this.framePerSecond = framePerSecond;
  16445. this.dataType = dataType;
  16446. this.loopMode = loopMode;
  16447. this._offsetsCache = {};
  16448. this._highLimitsCache = {};
  16449. this._stopped = false;
  16450. this.targetPropertyPath = targetProperty.split(".");
  16451. this.dataType = dataType;
  16452. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16453. }
  16454. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16455. var dataType = undefined;
  16456. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16457. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16458. }
  16459. else if (from instanceof BABYLON.Quaternion) {
  16460. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16461. }
  16462. else if (from instanceof BABYLON.Vector3) {
  16463. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16464. }
  16465. else if (from instanceof BABYLON.Vector2) {
  16466. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16467. }
  16468. else if (from instanceof BABYLON.Color3) {
  16469. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16470. }
  16471. if (dataType == undefined) {
  16472. return null;
  16473. }
  16474. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16475. var keys = [];
  16476. keys.push({ frame: 0, value: from });
  16477. keys.push({ frame: totalFrame, value: to });
  16478. animation.setKeys(keys);
  16479. mesh.animations.push(animation);
  16480. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16481. };
  16482. // Methods
  16483. Animation.prototype.isStopped = function () {
  16484. return this._stopped;
  16485. };
  16486. Animation.prototype.getKeys = function () {
  16487. return this._keys;
  16488. };
  16489. Animation.prototype.getEasingFunction = function () {
  16490. return this._easingFunction;
  16491. };
  16492. Animation.prototype.setEasingFunction = function (easingFunction) {
  16493. this._easingFunction = easingFunction;
  16494. };
  16495. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16496. return startValue + (endValue - startValue) * gradient;
  16497. };
  16498. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16499. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16500. };
  16501. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16502. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16503. };
  16504. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16505. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16506. };
  16507. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16508. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16509. };
  16510. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16511. var startScale = new BABYLON.Vector3(0, 0, 0);
  16512. var startRotation = new BABYLON.Quaternion();
  16513. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16514. startValue.decompose(startScale, startRotation, startTranslation);
  16515. var endScale = new BABYLON.Vector3(0, 0, 0);
  16516. var endRotation = new BABYLON.Quaternion();
  16517. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16518. endValue.decompose(endScale, endRotation, endTranslation);
  16519. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16520. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16521. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16522. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16523. return result;
  16524. };
  16525. Animation.prototype.clone = function () {
  16526. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16527. clone.setKeys(this._keys);
  16528. return clone;
  16529. };
  16530. Animation.prototype.setKeys = function (values) {
  16531. this._keys = values.slice(0);
  16532. this._offsetsCache = {};
  16533. this._highLimitsCache = {};
  16534. };
  16535. Animation.prototype._getKeyValue = function (value) {
  16536. if (typeof value === "function") {
  16537. return value();
  16538. }
  16539. return value;
  16540. };
  16541. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16542. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16543. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16544. }
  16545. this.currentFrame = currentFrame;
  16546. // Try to get a hash to find the right key
  16547. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16548. if (this._keys[startKey].frame >= currentFrame) {
  16549. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16550. startKey--;
  16551. }
  16552. }
  16553. for (var key = startKey; key < this._keys.length; key++) {
  16554. if (this._keys[key + 1].frame >= currentFrame) {
  16555. var startValue = this._getKeyValue(this._keys[key].value);
  16556. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16557. // gradient : percent of currentFrame between the frame inf and the frame sup
  16558. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16559. // check for easingFunction and correction of gradient
  16560. if (this._easingFunction != null) {
  16561. gradient = this._easingFunction.ease(gradient);
  16562. }
  16563. switch (this.dataType) {
  16564. case Animation.ANIMATIONTYPE_FLOAT:
  16565. switch (loopMode) {
  16566. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16567. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16568. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16569. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16570. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16571. }
  16572. break;
  16573. case Animation.ANIMATIONTYPE_QUATERNION:
  16574. var quaternion = null;
  16575. switch (loopMode) {
  16576. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16577. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16578. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16579. break;
  16580. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16581. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16582. break;
  16583. }
  16584. return quaternion;
  16585. case Animation.ANIMATIONTYPE_VECTOR3:
  16586. switch (loopMode) {
  16587. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16588. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16589. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16590. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16591. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16592. }
  16593. case Animation.ANIMATIONTYPE_VECTOR2:
  16594. switch (loopMode) {
  16595. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16596. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16597. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16598. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16599. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16600. }
  16601. case Animation.ANIMATIONTYPE_COLOR3:
  16602. switch (loopMode) {
  16603. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16604. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16605. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16606. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16607. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16608. }
  16609. case Animation.ANIMATIONTYPE_MATRIX:
  16610. switch (loopMode) {
  16611. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16612. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16613. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16614. return startValue;
  16615. }
  16616. default:
  16617. break;
  16618. }
  16619. break;
  16620. }
  16621. }
  16622. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16623. };
  16624. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16625. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16626. this._stopped = true;
  16627. return false;
  16628. }
  16629. var returnValue = true;
  16630. // Adding a start key at frame 0 if missing
  16631. if (this._keys[0].frame !== 0) {
  16632. var newKey = { frame: 0, value: this._keys[0].value };
  16633. this._keys.splice(0, 0, newKey);
  16634. }
  16635. // Check limits
  16636. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16637. from = this._keys[0].frame;
  16638. }
  16639. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16640. to = this._keys[this._keys.length - 1].frame;
  16641. }
  16642. // Compute ratio
  16643. var range = to - from;
  16644. var offsetValue;
  16645. // ratio represents the frame delta between from and to
  16646. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16647. var highLimitValue = 0;
  16648. if (ratio > range && !loop) {
  16649. returnValue = false;
  16650. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16651. }
  16652. else {
  16653. // Get max value if required
  16654. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16655. var keyOffset = to.toString() + from.toString();
  16656. if (!this._offsetsCache[keyOffset]) {
  16657. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16658. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16659. switch (this.dataType) {
  16660. case Animation.ANIMATIONTYPE_FLOAT:
  16661. this._offsetsCache[keyOffset] = toValue - fromValue;
  16662. break;
  16663. case Animation.ANIMATIONTYPE_QUATERNION:
  16664. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16665. break;
  16666. case Animation.ANIMATIONTYPE_VECTOR3:
  16667. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16668. case Animation.ANIMATIONTYPE_VECTOR2:
  16669. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16670. case Animation.ANIMATIONTYPE_COLOR3:
  16671. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16672. default:
  16673. break;
  16674. }
  16675. this._highLimitsCache[keyOffset] = toValue;
  16676. }
  16677. highLimitValue = this._highLimitsCache[keyOffset];
  16678. offsetValue = this._offsetsCache[keyOffset];
  16679. }
  16680. }
  16681. if (offsetValue === undefined) {
  16682. switch (this.dataType) {
  16683. case Animation.ANIMATIONTYPE_FLOAT:
  16684. offsetValue = 0;
  16685. break;
  16686. case Animation.ANIMATIONTYPE_QUATERNION:
  16687. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16688. break;
  16689. case Animation.ANIMATIONTYPE_VECTOR3:
  16690. offsetValue = BABYLON.Vector3.Zero();
  16691. break;
  16692. case Animation.ANIMATIONTYPE_VECTOR2:
  16693. offsetValue = BABYLON.Vector2.Zero();
  16694. break;
  16695. case Animation.ANIMATIONTYPE_COLOR3:
  16696. offsetValue = BABYLON.Color3.Black();
  16697. }
  16698. }
  16699. // Compute value
  16700. var repeatCount = (ratio / range) >> 0;
  16701. var currentFrame = returnValue ? from + ratio % range : to;
  16702. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16703. // Set value
  16704. if (this.targetPropertyPath.length > 1) {
  16705. var property = this._target[this.targetPropertyPath[0]];
  16706. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16707. property = property[this.targetPropertyPath[index]];
  16708. }
  16709. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16710. }
  16711. else {
  16712. this._target[this.targetPropertyPath[0]] = currentValue;
  16713. }
  16714. if (this._target.markAsDirty) {
  16715. this._target.markAsDirty(this.targetProperty);
  16716. }
  16717. if (!returnValue) {
  16718. this._stopped = true;
  16719. }
  16720. return returnValue;
  16721. };
  16722. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16723. get: function () {
  16724. return Animation._ANIMATIONTYPE_FLOAT;
  16725. },
  16726. enumerable: true,
  16727. configurable: true
  16728. });
  16729. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16730. get: function () {
  16731. return Animation._ANIMATIONTYPE_VECTOR3;
  16732. },
  16733. enumerable: true,
  16734. configurable: true
  16735. });
  16736. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16737. get: function () {
  16738. return Animation._ANIMATIONTYPE_VECTOR2;
  16739. },
  16740. enumerable: true,
  16741. configurable: true
  16742. });
  16743. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16744. get: function () {
  16745. return Animation._ANIMATIONTYPE_QUATERNION;
  16746. },
  16747. enumerable: true,
  16748. configurable: true
  16749. });
  16750. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16751. get: function () {
  16752. return Animation._ANIMATIONTYPE_MATRIX;
  16753. },
  16754. enumerable: true,
  16755. configurable: true
  16756. });
  16757. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16758. get: function () {
  16759. return Animation._ANIMATIONTYPE_COLOR3;
  16760. },
  16761. enumerable: true,
  16762. configurable: true
  16763. });
  16764. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16765. get: function () {
  16766. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16767. },
  16768. enumerable: true,
  16769. configurable: true
  16770. });
  16771. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16772. get: function () {
  16773. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16774. },
  16775. enumerable: true,
  16776. configurable: true
  16777. });
  16778. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16779. get: function () {
  16780. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. // Statics
  16786. Animation._ANIMATIONTYPE_FLOAT = 0;
  16787. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16788. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16789. Animation._ANIMATIONTYPE_MATRIX = 3;
  16790. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16791. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16792. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16793. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16794. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16795. return Animation;
  16796. })();
  16797. BABYLON.Animation = Animation;
  16798. })(BABYLON || (BABYLON = {}));
  16799. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16800. (function (BABYLON) {
  16801. var Animatable = (function () {
  16802. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16803. if (fromFrame === void 0) { fromFrame = 0; }
  16804. if (toFrame === void 0) { toFrame = 100; }
  16805. if (loopAnimation === void 0) { loopAnimation = false; }
  16806. if (speedRatio === void 0) { speedRatio = 1.0; }
  16807. this.target = target;
  16808. this.fromFrame = fromFrame;
  16809. this.toFrame = toFrame;
  16810. this.loopAnimation = loopAnimation;
  16811. this.speedRatio = speedRatio;
  16812. this.onAnimationEnd = onAnimationEnd;
  16813. this._animations = new Array();
  16814. this._paused = false;
  16815. this.animationStarted = false;
  16816. if (animations) {
  16817. this.appendAnimations(target, animations);
  16818. }
  16819. this._scene = scene;
  16820. scene._activeAnimatables.push(this);
  16821. }
  16822. // Methods
  16823. Animatable.prototype.appendAnimations = function (target, animations) {
  16824. for (var index = 0; index < animations.length; index++) {
  16825. var animation = animations[index];
  16826. animation._target = target;
  16827. this._animations.push(animation);
  16828. }
  16829. };
  16830. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16831. var animations = this._animations;
  16832. for (var index = 0; index < animations.length; index++) {
  16833. if (animations[index].targetProperty === property) {
  16834. return animations[index];
  16835. }
  16836. }
  16837. return null;
  16838. };
  16839. Animatable.prototype.pause = function () {
  16840. if (this._paused) {
  16841. return;
  16842. }
  16843. this._paused = true;
  16844. };
  16845. Animatable.prototype.restart = function () {
  16846. this._paused = false;
  16847. };
  16848. Animatable.prototype.stop = function () {
  16849. var index = this._scene._activeAnimatables.indexOf(this);
  16850. if (index > -1) {
  16851. this._scene._activeAnimatables.splice(index, 1);
  16852. }
  16853. if (this.onAnimationEnd) {
  16854. this.onAnimationEnd();
  16855. }
  16856. };
  16857. Animatable.prototype._animate = function (delay) {
  16858. if (this._paused) {
  16859. if (!this._pausedDelay) {
  16860. this._pausedDelay = delay;
  16861. }
  16862. return true;
  16863. }
  16864. if (!this._localDelayOffset) {
  16865. this._localDelayOffset = delay;
  16866. }
  16867. else if (this._pausedDelay) {
  16868. this._localDelayOffset += delay - this._pausedDelay;
  16869. this._pausedDelay = null;
  16870. }
  16871. // Animating
  16872. var running = false;
  16873. var animations = this._animations;
  16874. for (var index = 0; index < animations.length; index++) {
  16875. var animation = animations[index];
  16876. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16877. running = running || isRunning;
  16878. }
  16879. if (!running) {
  16880. // Remove from active animatables
  16881. index = this._scene._activeAnimatables.indexOf(this);
  16882. this._scene._activeAnimatables.splice(index, 1);
  16883. }
  16884. if (!running && this.onAnimationEnd) {
  16885. this.onAnimationEnd();
  16886. }
  16887. return running;
  16888. };
  16889. return Animatable;
  16890. })();
  16891. BABYLON.Animatable = Animatable;
  16892. })(BABYLON || (BABYLON = {}));
  16893. //# sourceMappingURL=babylon.animatable.js.map
  16894. var BABYLON;
  16895. (function (BABYLON) {
  16896. var EasingFunction = (function () {
  16897. function EasingFunction() {
  16898. // Properties
  16899. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16900. }
  16901. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16902. get: function () {
  16903. return EasingFunction._EASINGMODE_EASEIN;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16909. get: function () {
  16910. return EasingFunction._EASINGMODE_EASEOUT;
  16911. },
  16912. enumerable: true,
  16913. configurable: true
  16914. });
  16915. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16916. get: function () {
  16917. return EasingFunction._EASINGMODE_EASEINOUT;
  16918. },
  16919. enumerable: true,
  16920. configurable: true
  16921. });
  16922. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16923. var n = Math.min(Math.max(easingMode, 0), 2);
  16924. this._easingMode = n;
  16925. };
  16926. EasingFunction.prototype.getEasingMode = function () {
  16927. return this._easingMode;
  16928. };
  16929. EasingFunction.prototype.easeInCore = function (gradient) {
  16930. throw new Error('You must implement this method');
  16931. };
  16932. EasingFunction.prototype.ease = function (gradient) {
  16933. switch (this._easingMode) {
  16934. case EasingFunction.EASINGMODE_EASEIN:
  16935. return this.easeInCore(gradient);
  16936. case EasingFunction.EASINGMODE_EASEOUT:
  16937. return (1 - this.easeInCore(1 - gradient));
  16938. }
  16939. if (gradient >= 0.5) {
  16940. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16941. }
  16942. return (this.easeInCore(gradient * 2) * 0.5);
  16943. };
  16944. //Statics
  16945. EasingFunction._EASINGMODE_EASEIN = 0;
  16946. EasingFunction._EASINGMODE_EASEOUT = 1;
  16947. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16948. return EasingFunction;
  16949. })();
  16950. BABYLON.EasingFunction = EasingFunction;
  16951. var CircleEase = (function (_super) {
  16952. __extends(CircleEase, _super);
  16953. function CircleEase() {
  16954. _super.apply(this, arguments);
  16955. }
  16956. CircleEase.prototype.easeInCore = function (gradient) {
  16957. gradient = Math.max(0, Math.min(1, gradient));
  16958. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16959. };
  16960. return CircleEase;
  16961. })(EasingFunction);
  16962. BABYLON.CircleEase = CircleEase;
  16963. var BackEase = (function (_super) {
  16964. __extends(BackEase, _super);
  16965. function BackEase(amplitude) {
  16966. if (amplitude === void 0) { amplitude = 1; }
  16967. _super.call(this);
  16968. this.amplitude = amplitude;
  16969. }
  16970. BackEase.prototype.easeInCore = function (gradient) {
  16971. var num = Math.max(0, this.amplitude);
  16972. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16973. };
  16974. return BackEase;
  16975. })(EasingFunction);
  16976. BABYLON.BackEase = BackEase;
  16977. var BounceEase = (function (_super) {
  16978. __extends(BounceEase, _super);
  16979. function BounceEase(bounces, bounciness) {
  16980. if (bounces === void 0) { bounces = 3; }
  16981. if (bounciness === void 0) { bounciness = 2; }
  16982. _super.call(this);
  16983. this.bounces = bounces;
  16984. this.bounciness = bounciness;
  16985. }
  16986. BounceEase.prototype.easeInCore = function (gradient) {
  16987. var y = Math.max(0.0, this.bounces);
  16988. var bounciness = this.bounciness;
  16989. if (bounciness <= 1.0) {
  16990. bounciness = 1.001;
  16991. }
  16992. var num9 = Math.pow(bounciness, y);
  16993. var num5 = 1.0 - bounciness;
  16994. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16995. var num15 = gradient * num4;
  16996. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16997. var num3 = Math.floor(num65);
  16998. var num13 = num3 + 1.0;
  16999. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17000. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17001. var num7 = (num8 + num12) * 0.5;
  17002. var num6 = gradient - num7;
  17003. var num2 = num7 - num8;
  17004. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17005. };
  17006. return BounceEase;
  17007. })(EasingFunction);
  17008. BABYLON.BounceEase = BounceEase;
  17009. var CubicEase = (function (_super) {
  17010. __extends(CubicEase, _super);
  17011. function CubicEase() {
  17012. _super.apply(this, arguments);
  17013. }
  17014. CubicEase.prototype.easeInCore = function (gradient) {
  17015. return (gradient * gradient * gradient);
  17016. };
  17017. return CubicEase;
  17018. })(EasingFunction);
  17019. BABYLON.CubicEase = CubicEase;
  17020. var ElasticEase = (function (_super) {
  17021. __extends(ElasticEase, _super);
  17022. function ElasticEase(oscillations, springiness) {
  17023. if (oscillations === void 0) { oscillations = 3; }
  17024. if (springiness === void 0) { springiness = 3; }
  17025. _super.call(this);
  17026. this.oscillations = oscillations;
  17027. this.springiness = springiness;
  17028. }
  17029. ElasticEase.prototype.easeInCore = function (gradient) {
  17030. var num2;
  17031. var num3 = Math.max(0.0, this.oscillations);
  17032. var num = Math.max(0.0, this.springiness);
  17033. if (num == 0) {
  17034. num2 = gradient;
  17035. }
  17036. else {
  17037. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17038. }
  17039. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17040. };
  17041. return ElasticEase;
  17042. })(EasingFunction);
  17043. BABYLON.ElasticEase = ElasticEase;
  17044. var ExponentialEase = (function (_super) {
  17045. __extends(ExponentialEase, _super);
  17046. function ExponentialEase(exponent) {
  17047. if (exponent === void 0) { exponent = 2; }
  17048. _super.call(this);
  17049. this.exponent = exponent;
  17050. }
  17051. ExponentialEase.prototype.easeInCore = function (gradient) {
  17052. if (this.exponent <= 0) {
  17053. return gradient;
  17054. }
  17055. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17056. };
  17057. return ExponentialEase;
  17058. })(EasingFunction);
  17059. BABYLON.ExponentialEase = ExponentialEase;
  17060. var PowerEase = (function (_super) {
  17061. __extends(PowerEase, _super);
  17062. function PowerEase(power) {
  17063. if (power === void 0) { power = 2; }
  17064. _super.call(this);
  17065. this.power = power;
  17066. }
  17067. PowerEase.prototype.easeInCore = function (gradient) {
  17068. var y = Math.max(0.0, this.power);
  17069. return Math.pow(gradient, y);
  17070. };
  17071. return PowerEase;
  17072. })(EasingFunction);
  17073. BABYLON.PowerEase = PowerEase;
  17074. var QuadraticEase = (function (_super) {
  17075. __extends(QuadraticEase, _super);
  17076. function QuadraticEase() {
  17077. _super.apply(this, arguments);
  17078. }
  17079. QuadraticEase.prototype.easeInCore = function (gradient) {
  17080. return (gradient * gradient);
  17081. };
  17082. return QuadraticEase;
  17083. })(EasingFunction);
  17084. BABYLON.QuadraticEase = QuadraticEase;
  17085. var QuarticEase = (function (_super) {
  17086. __extends(QuarticEase, _super);
  17087. function QuarticEase() {
  17088. _super.apply(this, arguments);
  17089. }
  17090. QuarticEase.prototype.easeInCore = function (gradient) {
  17091. return (gradient * gradient * gradient * gradient);
  17092. };
  17093. return QuarticEase;
  17094. })(EasingFunction);
  17095. BABYLON.QuarticEase = QuarticEase;
  17096. var QuinticEase = (function (_super) {
  17097. __extends(QuinticEase, _super);
  17098. function QuinticEase() {
  17099. _super.apply(this, arguments);
  17100. }
  17101. QuinticEase.prototype.easeInCore = function (gradient) {
  17102. return (gradient * gradient * gradient * gradient * gradient);
  17103. };
  17104. return QuinticEase;
  17105. })(EasingFunction);
  17106. BABYLON.QuinticEase = QuinticEase;
  17107. var SineEase = (function (_super) {
  17108. __extends(SineEase, _super);
  17109. function SineEase() {
  17110. _super.apply(this, arguments);
  17111. }
  17112. SineEase.prototype.easeInCore = function (gradient) {
  17113. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17114. };
  17115. return SineEase;
  17116. })(EasingFunction);
  17117. BABYLON.SineEase = SineEase;
  17118. var BezierCurveEase = (function (_super) {
  17119. __extends(BezierCurveEase, _super);
  17120. function BezierCurveEase(x1, y1, x2, y2) {
  17121. if (x1 === void 0) { x1 = 0; }
  17122. if (y1 === void 0) { y1 = 0; }
  17123. if (x2 === void 0) { x2 = 1; }
  17124. if (y2 === void 0) { y2 = 1; }
  17125. _super.call(this);
  17126. this.x1 = x1;
  17127. this.y1 = y1;
  17128. this.x2 = x2;
  17129. this.y2 = y2;
  17130. }
  17131. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17132. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17133. };
  17134. return BezierCurveEase;
  17135. })(EasingFunction);
  17136. BABYLON.BezierCurveEase = BezierCurveEase;
  17137. })(BABYLON || (BABYLON = {}));
  17138. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17139. (function (BABYLON) {
  17140. var Octree = (function () {
  17141. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17142. if (maxDepth === void 0) { maxDepth = 2; }
  17143. this.maxDepth = maxDepth;
  17144. this.dynamicContent = new Array();
  17145. this._maxBlockCapacity = maxBlockCapacity || 64;
  17146. this._selectionContent = new BABYLON.SmartArray(1024);
  17147. this._creationFunc = creationFunc;
  17148. }
  17149. // Methods
  17150. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17151. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17152. };
  17153. Octree.prototype.addMesh = function (entry) {
  17154. for (var index = 0; index < this.blocks.length; index++) {
  17155. var block = this.blocks[index];
  17156. block.addEntry(entry);
  17157. }
  17158. };
  17159. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17160. this._selectionContent.reset();
  17161. for (var index = 0; index < this.blocks.length; index++) {
  17162. var block = this.blocks[index];
  17163. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17164. }
  17165. if (allowDuplicate) {
  17166. this._selectionContent.concat(this.dynamicContent);
  17167. }
  17168. else {
  17169. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17170. }
  17171. return this._selectionContent;
  17172. };
  17173. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17174. this._selectionContent.reset();
  17175. for (var index = 0; index < this.blocks.length; index++) {
  17176. var block = this.blocks[index];
  17177. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17178. }
  17179. if (allowDuplicate) {
  17180. this._selectionContent.concat(this.dynamicContent);
  17181. }
  17182. else {
  17183. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17184. }
  17185. return this._selectionContent;
  17186. };
  17187. Octree.prototype.intersectsRay = function (ray) {
  17188. this._selectionContent.reset();
  17189. for (var index = 0; index < this.blocks.length; index++) {
  17190. var block = this.blocks[index];
  17191. block.intersectsRay(ray, this._selectionContent);
  17192. }
  17193. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17194. return this._selectionContent;
  17195. };
  17196. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17197. target.blocks = new Array();
  17198. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17199. for (var x = 0; x < 2; x++) {
  17200. for (var y = 0; y < 2; y++) {
  17201. for (var z = 0; z < 2; z++) {
  17202. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17203. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17204. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17205. block.addEntries(entries);
  17206. target.blocks.push(block);
  17207. }
  17208. }
  17209. }
  17210. };
  17211. Octree.CreationFuncForMeshes = function (entry, block) {
  17212. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17213. block.entries.push(entry);
  17214. }
  17215. };
  17216. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17217. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17218. block.entries.push(entry);
  17219. }
  17220. };
  17221. return Octree;
  17222. })();
  17223. BABYLON.Octree = Octree;
  17224. })(BABYLON || (BABYLON = {}));
  17225. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17226. (function (BABYLON) {
  17227. var OctreeBlock = (function () {
  17228. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17229. this.entries = new Array();
  17230. this._boundingVectors = new Array();
  17231. this._capacity = capacity;
  17232. this._depth = depth;
  17233. this._maxDepth = maxDepth;
  17234. this._creationFunc = creationFunc;
  17235. this._minPoint = minPoint;
  17236. this._maxPoint = maxPoint;
  17237. this._boundingVectors.push(minPoint.clone());
  17238. this._boundingVectors.push(maxPoint.clone());
  17239. this._boundingVectors.push(minPoint.clone());
  17240. this._boundingVectors[2].x = maxPoint.x;
  17241. this._boundingVectors.push(minPoint.clone());
  17242. this._boundingVectors[3].y = maxPoint.y;
  17243. this._boundingVectors.push(minPoint.clone());
  17244. this._boundingVectors[4].z = maxPoint.z;
  17245. this._boundingVectors.push(maxPoint.clone());
  17246. this._boundingVectors[5].z = minPoint.z;
  17247. this._boundingVectors.push(maxPoint.clone());
  17248. this._boundingVectors[6].x = minPoint.x;
  17249. this._boundingVectors.push(maxPoint.clone());
  17250. this._boundingVectors[7].y = minPoint.y;
  17251. }
  17252. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17253. // Property
  17254. get: function () {
  17255. return this._capacity;
  17256. },
  17257. enumerable: true,
  17258. configurable: true
  17259. });
  17260. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17261. get: function () {
  17262. return this._minPoint;
  17263. },
  17264. enumerable: true,
  17265. configurable: true
  17266. });
  17267. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17268. get: function () {
  17269. return this._maxPoint;
  17270. },
  17271. enumerable: true,
  17272. configurable: true
  17273. });
  17274. // Methods
  17275. OctreeBlock.prototype.addEntry = function (entry) {
  17276. if (this.blocks) {
  17277. for (var index = 0; index < this.blocks.length; index++) {
  17278. var block = this.blocks[index];
  17279. block.addEntry(entry);
  17280. }
  17281. return;
  17282. }
  17283. this._creationFunc(entry, this);
  17284. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17285. this.createInnerBlocks();
  17286. }
  17287. };
  17288. OctreeBlock.prototype.addEntries = function (entries) {
  17289. for (var index = 0; index < entries.length; index++) {
  17290. var mesh = entries[index];
  17291. this.addEntry(mesh);
  17292. }
  17293. };
  17294. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17295. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17296. if (this.blocks) {
  17297. for (var index = 0; index < this.blocks.length; index++) {
  17298. var block = this.blocks[index];
  17299. block.select(frustumPlanes, selection, allowDuplicate);
  17300. }
  17301. return;
  17302. }
  17303. if (allowDuplicate) {
  17304. selection.concat(this.entries);
  17305. }
  17306. else {
  17307. selection.concatWithNoDuplicate(this.entries);
  17308. }
  17309. }
  17310. };
  17311. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17312. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17313. if (this.blocks) {
  17314. for (var index = 0; index < this.blocks.length; index++) {
  17315. var block = this.blocks[index];
  17316. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17317. }
  17318. return;
  17319. }
  17320. if (allowDuplicate) {
  17321. selection.concat(this.entries);
  17322. }
  17323. else {
  17324. selection.concatWithNoDuplicate(this.entries);
  17325. }
  17326. }
  17327. };
  17328. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17329. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17330. if (this.blocks) {
  17331. for (var index = 0; index < this.blocks.length; index++) {
  17332. var block = this.blocks[index];
  17333. block.intersectsRay(ray, selection);
  17334. }
  17335. return;
  17336. }
  17337. selection.concatWithNoDuplicate(this.entries);
  17338. }
  17339. };
  17340. OctreeBlock.prototype.createInnerBlocks = function () {
  17341. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17342. };
  17343. return OctreeBlock;
  17344. })();
  17345. BABYLON.OctreeBlock = OctreeBlock;
  17346. })(BABYLON || (BABYLON = {}));
  17347. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17348. (function (BABYLON) {
  17349. var Bone = (function () {
  17350. function Bone(name, skeleton, parentBone, matrix) {
  17351. this.name = name;
  17352. this.children = new Array();
  17353. this.animations = new Array();
  17354. this._worldTransform = new BABYLON.Matrix();
  17355. this._absoluteTransform = new BABYLON.Matrix();
  17356. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17357. this._skeleton = skeleton;
  17358. this._matrix = matrix;
  17359. this._baseMatrix = matrix;
  17360. skeleton.bones.push(this);
  17361. if (parentBone) {
  17362. this._parent = parentBone;
  17363. parentBone.children.push(this);
  17364. }
  17365. else {
  17366. this._parent = null;
  17367. }
  17368. this._updateDifferenceMatrix();
  17369. }
  17370. // Members
  17371. Bone.prototype.getParent = function () {
  17372. return this._parent;
  17373. };
  17374. Bone.prototype.getLocalMatrix = function () {
  17375. return this._matrix;
  17376. };
  17377. Bone.prototype.getBaseMatrix = function () {
  17378. return this._baseMatrix;
  17379. };
  17380. Bone.prototype.getWorldMatrix = function () {
  17381. return this._worldTransform;
  17382. };
  17383. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17384. return this._invertedAbsoluteTransform;
  17385. };
  17386. Bone.prototype.getAbsoluteMatrix = function () {
  17387. var matrix = this._matrix.clone();
  17388. var parent = this._parent;
  17389. while (parent) {
  17390. matrix = matrix.multiply(parent.getLocalMatrix());
  17391. parent = parent.getParent();
  17392. }
  17393. return matrix;
  17394. };
  17395. // Methods
  17396. Bone.prototype.updateMatrix = function (matrix) {
  17397. this._matrix = matrix;
  17398. this._skeleton._markAsDirty();
  17399. this._updateDifferenceMatrix();
  17400. };
  17401. Bone.prototype._updateDifferenceMatrix = function () {
  17402. if (this._parent) {
  17403. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17404. }
  17405. else {
  17406. this._absoluteTransform.copyFrom(this._matrix);
  17407. }
  17408. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17409. for (var index = 0; index < this.children.length; index++) {
  17410. this.children[index]._updateDifferenceMatrix();
  17411. }
  17412. };
  17413. Bone.prototype.markAsDirty = function () {
  17414. this._skeleton._markAsDirty();
  17415. };
  17416. return Bone;
  17417. })();
  17418. BABYLON.Bone = Bone;
  17419. })(BABYLON || (BABYLON = {}));
  17420. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17421. (function (BABYLON) {
  17422. var Skeleton = (function () {
  17423. function Skeleton(name, id, scene) {
  17424. this.name = name;
  17425. this.id = id;
  17426. this.bones = new Array();
  17427. this._isDirty = true;
  17428. this._identity = BABYLON.Matrix.Identity();
  17429. this.bones = [];
  17430. this._scene = scene;
  17431. scene.skeletons.push(this);
  17432. this.prepare();
  17433. //make sure it will recalculate the matrix next time prepare is called.
  17434. this._isDirty = true;
  17435. }
  17436. // Members
  17437. Skeleton.prototype.getTransformMatrices = function () {
  17438. return this._transformMatrices;
  17439. };
  17440. // Methods
  17441. Skeleton.prototype._markAsDirty = function () {
  17442. this._isDirty = true;
  17443. };
  17444. Skeleton.prototype.prepare = function () {
  17445. if (!this._isDirty) {
  17446. return;
  17447. }
  17448. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17449. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17450. }
  17451. for (var index = 0; index < this.bones.length; index++) {
  17452. var bone = this.bones[index];
  17453. var parentBone = bone.getParent();
  17454. if (parentBone) {
  17455. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17456. }
  17457. else {
  17458. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17459. }
  17460. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17461. }
  17462. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17463. this._isDirty = false;
  17464. this._scene._activeBones += this.bones.length;
  17465. };
  17466. Skeleton.prototype.getAnimatables = function () {
  17467. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17468. this._animatables = [];
  17469. for (var index = 0; index < this.bones.length; index++) {
  17470. this._animatables.push(this.bones[index]);
  17471. }
  17472. }
  17473. return this._animatables;
  17474. };
  17475. Skeleton.prototype.clone = function (name, id) {
  17476. var result = new Skeleton(name, id || name, this._scene);
  17477. for (var index = 0; index < this.bones.length; index++) {
  17478. var source = this.bones[index];
  17479. var parentBone = null;
  17480. if (source.getParent()) {
  17481. var parentIndex = this.bones.indexOf(source.getParent());
  17482. parentBone = result.bones[parentIndex];
  17483. }
  17484. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17485. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17486. }
  17487. return result;
  17488. };
  17489. return Skeleton;
  17490. })();
  17491. BABYLON.Skeleton = Skeleton;
  17492. })(BABYLON || (BABYLON = {}));
  17493. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17494. (function (BABYLON) {
  17495. var PostProcess = (function () {
  17496. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17498. this.name = name;
  17499. this.width = -1;
  17500. this.height = -1;
  17501. this._reusable = false;
  17502. this._textures = new BABYLON.SmartArray(2);
  17503. this._currentRenderTextureInd = 0;
  17504. if (camera != null) {
  17505. this._camera = camera;
  17506. this._scene = camera.getScene();
  17507. camera.attachPostProcess(this);
  17508. this._engine = this._scene.getEngine();
  17509. }
  17510. else {
  17511. this._engine = engine;
  17512. }
  17513. this._renderRatio = ratio;
  17514. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17515. this._reusable = reusable || false;
  17516. samplers = samplers || [];
  17517. samplers.push("textureSampler");
  17518. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17519. }
  17520. PostProcess.prototype.isReusable = function () {
  17521. return this._reusable;
  17522. };
  17523. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17524. camera = camera || this._camera;
  17525. var scene = camera.getScene();
  17526. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17527. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17528. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17529. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17530. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17531. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17532. if (this._textures.length > 0) {
  17533. for (var i = 0; i < this._textures.length; i++) {
  17534. this._engine._releaseTexture(this._textures.data[i]);
  17535. }
  17536. this._textures.reset();
  17537. }
  17538. this.width = desiredWidth;
  17539. this.height = desiredHeight;
  17540. 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 }));
  17541. if (this._reusable) {
  17542. 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 }));
  17543. }
  17544. if (this.onSizeChanged) {
  17545. this.onSizeChanged();
  17546. }
  17547. }
  17548. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17549. if (this.onActivate) {
  17550. this.onActivate(camera);
  17551. }
  17552. // Clear
  17553. if (this.clearColor) {
  17554. this._engine.clear(this.clearColor, true, true);
  17555. }
  17556. else {
  17557. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17558. }
  17559. if (this._reusable) {
  17560. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17561. }
  17562. };
  17563. PostProcess.prototype.apply = function () {
  17564. // Check
  17565. if (!this._effect.isReady())
  17566. return null;
  17567. // States
  17568. this._engine.enableEffect(this._effect);
  17569. this._engine.setState(false);
  17570. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17571. this._engine.setDepthBuffer(false);
  17572. this._engine.setDepthWrite(false);
  17573. // Texture
  17574. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17575. // Parameters
  17576. if (this.onApply) {
  17577. this.onApply(this._effect);
  17578. }
  17579. return this._effect;
  17580. };
  17581. PostProcess.prototype.dispose = function (camera) {
  17582. camera = camera || this._camera;
  17583. if (this._textures.length > 0) {
  17584. for (var i = 0; i < this._textures.length; i++) {
  17585. this._engine._releaseTexture(this._textures.data[i]);
  17586. }
  17587. this._textures.reset();
  17588. }
  17589. if (!camera) {
  17590. return;
  17591. }
  17592. camera.detachPostProcess(this);
  17593. var index = camera._postProcesses.indexOf(this);
  17594. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17595. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17596. }
  17597. };
  17598. return PostProcess;
  17599. })();
  17600. BABYLON.PostProcess = PostProcess;
  17601. })(BABYLON || (BABYLON = {}));
  17602. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17603. (function (BABYLON) {
  17604. var PostProcessManager = (function () {
  17605. function PostProcessManager(scene) {
  17606. this._vertexDeclaration = [2];
  17607. this._vertexStrideSize = 2 * 4;
  17608. this._scene = scene;
  17609. }
  17610. PostProcessManager.prototype._prepareBuffers = function () {
  17611. if (this._vertexBuffer) {
  17612. return;
  17613. }
  17614. // VBO
  17615. var vertices = [];
  17616. vertices.push(1, 1);
  17617. vertices.push(-1, 1);
  17618. vertices.push(-1, -1);
  17619. vertices.push(1, -1);
  17620. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17621. // Indices
  17622. var indices = [];
  17623. indices.push(0);
  17624. indices.push(1);
  17625. indices.push(2);
  17626. indices.push(0);
  17627. indices.push(2);
  17628. indices.push(3);
  17629. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17630. };
  17631. // Methods
  17632. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17633. var postProcesses = this._scene.activeCamera._postProcesses;
  17634. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17635. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17636. return false;
  17637. }
  17638. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17639. return true;
  17640. };
  17641. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17642. var engine = this._scene.getEngine();
  17643. for (var index = 0; index < postProcesses.length; index++) {
  17644. if (index < postProcesses.length - 1) {
  17645. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17646. }
  17647. else {
  17648. if (targetTexture) {
  17649. engine.bindFramebuffer(targetTexture);
  17650. }
  17651. else {
  17652. engine.restoreDefaultFramebuffer();
  17653. }
  17654. }
  17655. var pp = postProcesses[index];
  17656. var effect = pp.apply();
  17657. if (effect) {
  17658. if (pp.onBeforeRender) {
  17659. pp.onBeforeRender(effect);
  17660. }
  17661. // VBOs
  17662. this._prepareBuffers();
  17663. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17664. // Draw order
  17665. engine.draw(true, 0, 6);
  17666. }
  17667. }
  17668. // Restore depth buffer
  17669. engine.setDepthBuffer(true);
  17670. engine.setDepthWrite(true);
  17671. };
  17672. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17673. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17674. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17675. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17676. return;
  17677. }
  17678. var engine = this._scene.getEngine();
  17679. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17680. if (index < postProcessesTakenIndices.length - 1) {
  17681. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17682. }
  17683. else {
  17684. if (targetTexture) {
  17685. engine.bindFramebuffer(targetTexture);
  17686. }
  17687. else {
  17688. engine.restoreDefaultFramebuffer();
  17689. }
  17690. }
  17691. if (doNotPresent) {
  17692. break;
  17693. }
  17694. var pp = postProcesses[postProcessesTakenIndices[index]];
  17695. var effect = pp.apply();
  17696. if (effect) {
  17697. if (pp.onBeforeRender) {
  17698. pp.onBeforeRender(effect);
  17699. }
  17700. // VBOs
  17701. this._prepareBuffers();
  17702. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17703. // Draw order
  17704. engine.draw(true, 0, 6);
  17705. }
  17706. }
  17707. // Restore depth buffer
  17708. engine.setDepthBuffer(true);
  17709. engine.setDepthWrite(true);
  17710. };
  17711. PostProcessManager.prototype.dispose = function () {
  17712. if (this._vertexBuffer) {
  17713. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17714. this._vertexBuffer = null;
  17715. }
  17716. if (this._indexBuffer) {
  17717. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17718. this._indexBuffer = null;
  17719. }
  17720. };
  17721. return PostProcessManager;
  17722. })();
  17723. BABYLON.PostProcessManager = PostProcessManager;
  17724. })(BABYLON || (BABYLON = {}));
  17725. //# sourceMappingURL=babylon.postProcessManager.js.map
  17726. var BABYLON;
  17727. (function (BABYLON) {
  17728. var PassPostProcess = (function (_super) {
  17729. __extends(PassPostProcess, _super);
  17730. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17731. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17732. }
  17733. return PassPostProcess;
  17734. })(BABYLON.PostProcess);
  17735. BABYLON.PassPostProcess = PassPostProcess;
  17736. })(BABYLON || (BABYLON = {}));
  17737. //# sourceMappingURL=babylon.passPostProcess.js.map
  17738. var BABYLON;
  17739. (function (BABYLON) {
  17740. var BlurPostProcess = (function (_super) {
  17741. __extends(BlurPostProcess, _super);
  17742. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17743. var _this = this;
  17744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17745. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17746. this.direction = direction;
  17747. this.blurWidth = blurWidth;
  17748. this.onApply = function (effect) {
  17749. effect.setFloat2("screenSize", _this.width, _this.height);
  17750. effect.setVector2("direction", _this.direction);
  17751. effect.setFloat("blurWidth", _this.blurWidth);
  17752. };
  17753. }
  17754. return BlurPostProcess;
  17755. })(BABYLON.PostProcess);
  17756. BABYLON.BlurPostProcess = BlurPostProcess;
  17757. })(BABYLON || (BABYLON = {}));
  17758. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17759. var BABYLON;
  17760. (function (BABYLON) {
  17761. var FilterPostProcess = (function (_super) {
  17762. __extends(FilterPostProcess, _super);
  17763. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17764. var _this = this;
  17765. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17766. this.kernelMatrix = kernelMatrix;
  17767. this.onApply = function (effect) {
  17768. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17769. };
  17770. }
  17771. return FilterPostProcess;
  17772. })(BABYLON.PostProcess);
  17773. BABYLON.FilterPostProcess = FilterPostProcess;
  17774. })(BABYLON || (BABYLON = {}));
  17775. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17776. var BABYLON;
  17777. (function (BABYLON) {
  17778. var RefractionPostProcess = (function (_super) {
  17779. __extends(RefractionPostProcess, _super);
  17780. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17781. var _this = this;
  17782. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17783. this.color = color;
  17784. this.depth = depth;
  17785. this.colorLevel = colorLevel;
  17786. this.onActivate = function (cam) {
  17787. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17788. };
  17789. this.onApply = function (effect) {
  17790. effect.setColor3("baseColor", _this.color);
  17791. effect.setFloat("depth", _this.depth);
  17792. effect.setFloat("colorLevel", _this.colorLevel);
  17793. effect.setTexture("refractionSampler", _this._refRexture);
  17794. };
  17795. }
  17796. // Methods
  17797. RefractionPostProcess.prototype.dispose = function (camera) {
  17798. if (this._refRexture) {
  17799. this._refRexture.dispose();
  17800. }
  17801. _super.prototype.dispose.call(this, camera);
  17802. };
  17803. return RefractionPostProcess;
  17804. })(BABYLON.PostProcess);
  17805. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17806. })(BABYLON || (BABYLON = {}));
  17807. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17808. var BABYLON;
  17809. (function (BABYLON) {
  17810. var BlackAndWhitePostProcess = (function (_super) {
  17811. __extends(BlackAndWhitePostProcess, _super);
  17812. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17813. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17814. }
  17815. return BlackAndWhitePostProcess;
  17816. })(BABYLON.PostProcess);
  17817. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17818. })(BABYLON || (BABYLON = {}));
  17819. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17820. var BABYLON;
  17821. (function (BABYLON) {
  17822. var ConvolutionPostProcess = (function (_super) {
  17823. __extends(ConvolutionPostProcess, _super);
  17824. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17825. var _this = this;
  17826. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17827. this.kernel = kernel;
  17828. this.onApply = function (effect) {
  17829. effect.setFloat2("screenSize", _this.width, _this.height);
  17830. effect.setArray("kernel", _this.kernel);
  17831. };
  17832. }
  17833. // Statics
  17834. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17835. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17836. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17837. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17838. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17839. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17840. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17841. return ConvolutionPostProcess;
  17842. })(BABYLON.PostProcess);
  17843. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17844. })(BABYLON || (BABYLON = {}));
  17845. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17846. var BABYLON;
  17847. (function (BABYLON) {
  17848. var FxaaPostProcess = (function (_super) {
  17849. __extends(FxaaPostProcess, _super);
  17850. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17851. var _this = this;
  17852. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17853. this.onSizeChanged = function () {
  17854. _this.texelWidth = 1.0 / _this.width;
  17855. _this.texelHeight = 1.0 / _this.height;
  17856. };
  17857. this.onApply = function (effect) {
  17858. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17859. };
  17860. }
  17861. return FxaaPostProcess;
  17862. })(BABYLON.PostProcess);
  17863. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17864. })(BABYLON || (BABYLON = {}));
  17865. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17866. (function (BABYLON) {
  17867. var LensFlare = (function () {
  17868. function LensFlare(size, position, color, imgUrl, system) {
  17869. this.size = size;
  17870. this.position = position;
  17871. this.dispose = function () {
  17872. if (this.texture) {
  17873. this.texture.dispose();
  17874. }
  17875. // Remove from scene
  17876. var index = this._system.lensFlares.indexOf(this);
  17877. this._system.lensFlares.splice(index, 1);
  17878. };
  17879. this.color = color || new BABYLON.Color3(1, 1, 1);
  17880. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17881. this._system = system;
  17882. system.lensFlares.push(this);
  17883. }
  17884. return LensFlare;
  17885. })();
  17886. BABYLON.LensFlare = LensFlare;
  17887. })(BABYLON || (BABYLON = {}));
  17888. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17889. (function (BABYLON) {
  17890. var LensFlareSystem = (function () {
  17891. function LensFlareSystem(name, emitter, scene) {
  17892. this.name = name;
  17893. this.lensFlares = new Array();
  17894. this.borderLimit = 300;
  17895. this._vertexDeclaration = [2];
  17896. this._vertexStrideSize = 2 * 4;
  17897. this._isEnabled = true;
  17898. this._scene = scene;
  17899. this._emitter = emitter;
  17900. scene.lensFlareSystems.push(this);
  17901. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17902. // VBO
  17903. var vertices = [];
  17904. vertices.push(1, 1);
  17905. vertices.push(-1, 1);
  17906. vertices.push(-1, -1);
  17907. vertices.push(1, -1);
  17908. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17909. // Indices
  17910. var indices = [];
  17911. indices.push(0);
  17912. indices.push(1);
  17913. indices.push(2);
  17914. indices.push(0);
  17915. indices.push(2);
  17916. indices.push(3);
  17917. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17918. // Effects
  17919. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17920. }
  17921. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17922. get: function () {
  17923. return this._isEnabled;
  17924. },
  17925. set: function (value) {
  17926. this._isEnabled = value;
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. LensFlareSystem.prototype.getScene = function () {
  17932. return this._scene;
  17933. };
  17934. LensFlareSystem.prototype.getEmitter = function () {
  17935. return this._emitter;
  17936. };
  17937. LensFlareSystem.prototype.getEmitterPosition = function () {
  17938. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17939. };
  17940. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17941. var position = this.getEmitterPosition();
  17942. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17943. this._positionX = position.x;
  17944. this._positionY = position.y;
  17945. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17946. if (position.z > 0) {
  17947. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17948. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17949. return true;
  17950. }
  17951. }
  17952. return false;
  17953. };
  17954. LensFlareSystem.prototype._isVisible = function () {
  17955. if (!this._isEnabled) {
  17956. return false;
  17957. }
  17958. var emitterPosition = this.getEmitterPosition();
  17959. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17960. var distance = direction.length();
  17961. direction.normalize();
  17962. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17963. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17964. return !pickInfo.hit || pickInfo.distance > distance;
  17965. };
  17966. LensFlareSystem.prototype.render = function () {
  17967. if (!this._effect.isReady())
  17968. return false;
  17969. var engine = this._scene.getEngine();
  17970. var viewport = this._scene.activeCamera.viewport;
  17971. var globalViewport = viewport.toGlobal(engine);
  17972. // Position
  17973. if (!this.computeEffectivePosition(globalViewport)) {
  17974. return false;
  17975. }
  17976. // Visibility
  17977. if (!this._isVisible()) {
  17978. return false;
  17979. }
  17980. // Intensity
  17981. var awayX;
  17982. var awayY;
  17983. if (this._positionX < this.borderLimit + globalViewport.x) {
  17984. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17985. }
  17986. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17987. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17988. }
  17989. else {
  17990. awayX = 0;
  17991. }
  17992. if (this._positionY < this.borderLimit + globalViewport.y) {
  17993. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17994. }
  17995. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17996. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17997. }
  17998. else {
  17999. awayY = 0;
  18000. }
  18001. var away = (awayX > awayY) ? awayX : awayY;
  18002. if (away > this.borderLimit) {
  18003. away = this.borderLimit;
  18004. }
  18005. var intensity = 1.0 - (away / this.borderLimit);
  18006. if (intensity < 0) {
  18007. return false;
  18008. }
  18009. if (intensity > 1.0) {
  18010. intensity = 1.0;
  18011. }
  18012. // Position
  18013. var centerX = globalViewport.x + globalViewport.width / 2;
  18014. var centerY = globalViewport.y + globalViewport.height / 2;
  18015. var distX = centerX - this._positionX;
  18016. var distY = centerY - this._positionY;
  18017. // Effects
  18018. engine.enableEffect(this._effect);
  18019. engine.setState(false);
  18020. engine.setDepthBuffer(false);
  18021. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18022. // VBOs
  18023. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18024. for (var index = 0; index < this.lensFlares.length; index++) {
  18025. var flare = this.lensFlares[index];
  18026. var x = centerX - (distX * flare.position);
  18027. var y = centerY - (distY * flare.position);
  18028. var cw = flare.size;
  18029. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18030. var cx = 2 * (x / globalViewport.width) - 1.0;
  18031. var cy = 1.0 - 2 * (y / globalViewport.height);
  18032. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18033. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18034. // Texture
  18035. this._effect.setTexture("textureSampler", flare.texture);
  18036. // Color
  18037. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18038. // Draw order
  18039. engine.draw(true, 0, 6);
  18040. }
  18041. engine.setDepthBuffer(true);
  18042. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18043. return true;
  18044. };
  18045. LensFlareSystem.prototype.dispose = function () {
  18046. if (this._vertexBuffer) {
  18047. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18048. this._vertexBuffer = null;
  18049. }
  18050. if (this._indexBuffer) {
  18051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18052. this._indexBuffer = null;
  18053. }
  18054. while (this.lensFlares.length) {
  18055. this.lensFlares[0].dispose();
  18056. }
  18057. // Remove from scene
  18058. var index = this._scene.lensFlareSystems.indexOf(this);
  18059. this._scene.lensFlareSystems.splice(index, 1);
  18060. };
  18061. return LensFlareSystem;
  18062. })();
  18063. BABYLON.LensFlareSystem = LensFlareSystem;
  18064. })(BABYLON || (BABYLON = {}));
  18065. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18066. (function (BABYLON) {
  18067. var IntersectionInfo = (function () {
  18068. function IntersectionInfo(bu, bv, distance) {
  18069. this.bu = bu;
  18070. this.bv = bv;
  18071. this.distance = distance;
  18072. this.faceId = 0;
  18073. this.subMeshId = 0;
  18074. }
  18075. return IntersectionInfo;
  18076. })();
  18077. BABYLON.IntersectionInfo = IntersectionInfo;
  18078. var PickingInfo = (function () {
  18079. function PickingInfo() {
  18080. this.hit = false;
  18081. this.distance = 0;
  18082. this.pickedPoint = null;
  18083. this.pickedMesh = null;
  18084. this.bu = 0;
  18085. this.bv = 0;
  18086. this.faceId = -1;
  18087. this.subMeshId = 0;
  18088. }
  18089. // Methods
  18090. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18091. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18092. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18093. return null;
  18094. }
  18095. var indices = this.pickedMesh.getIndices();
  18096. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18097. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18098. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18099. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18100. normal0 = normal0.scale(this.bu);
  18101. normal1 = normal1.scale(this.bv);
  18102. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18103. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18104. if (useWorldCoordinates) {
  18105. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18106. }
  18107. return result;
  18108. };
  18109. PickingInfo.prototype.getTextureCoordinates = function () {
  18110. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18111. return null;
  18112. }
  18113. var indices = this.pickedMesh.getIndices();
  18114. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18115. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18116. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18117. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18118. uv0 = uv0.scale(this.bu);
  18119. uv1 = uv1.scale(this.bv);
  18120. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18121. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18122. };
  18123. return PickingInfo;
  18124. })();
  18125. BABYLON.PickingInfo = PickingInfo;
  18126. })(BABYLON || (BABYLON = {}));
  18127. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18128. (function (BABYLON) {
  18129. var FilesInput = (function () {
  18130. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18131. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18132. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18133. this._engine = p_engine;
  18134. this._canvas = p_canvas;
  18135. this._currentScene = p_scene;
  18136. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18137. this._progressCallback = p_progressCallback;
  18138. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18139. this._textureLoadingCallback = p_textureLoadingCallback;
  18140. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18141. }
  18142. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18143. var _this = this;
  18144. if (p_elementToMonitor) {
  18145. this._elementToMonitor = p_elementToMonitor;
  18146. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18147. _this.drag(e);
  18148. }, false);
  18149. this._elementToMonitor.addEventListener("dragover", function (e) {
  18150. _this.drag(e);
  18151. }, false);
  18152. this._elementToMonitor.addEventListener("drop", function (e) {
  18153. _this.drop(e);
  18154. }, false);
  18155. }
  18156. };
  18157. FilesInput.prototype.renderFunction = function () {
  18158. if (this._additionnalRenderLoopLogicCallback) {
  18159. this._additionnalRenderLoopLogicCallback();
  18160. }
  18161. if (this._currentScene) {
  18162. if (this._textureLoadingCallback) {
  18163. var remaining = this._currentScene.getWaitingItemsCount();
  18164. if (remaining > 0) {
  18165. this._textureLoadingCallback(remaining);
  18166. }
  18167. }
  18168. this._currentScene.render();
  18169. }
  18170. };
  18171. FilesInput.prototype.drag = function (e) {
  18172. e.stopPropagation();
  18173. e.preventDefault();
  18174. };
  18175. FilesInput.prototype.drop = function (eventDrop) {
  18176. eventDrop.stopPropagation();
  18177. eventDrop.preventDefault();
  18178. this.loadFiles(eventDrop);
  18179. };
  18180. FilesInput.prototype.loadFiles = function (event) {
  18181. if (this._startingProcessingFilesCallback)
  18182. this._startingProcessingFilesCallback();
  18183. // Handling data transfer via drag'n'drop
  18184. if (event && event.dataTransfer && event.dataTransfer.files) {
  18185. this._filesToLoad = event.dataTransfer.files;
  18186. }
  18187. // Handling files from input files
  18188. if (event && event.target && event.target.files) {
  18189. this._filesToLoad = event.target.files;
  18190. }
  18191. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18192. for (var i = 0; i < this._filesToLoad.length; i++) {
  18193. switch (this._filesToLoad[i].type) {
  18194. case "image/jpeg":
  18195. case "image/png":
  18196. case "image/bmp":
  18197. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18198. break;
  18199. case "image/targa":
  18200. case "image/vnd.ms-dds":
  18201. case "audio/wav":
  18202. case "audio/x-wav":
  18203. case "audio/mp3":
  18204. case "audio/mpeg":
  18205. case "audio/mpeg3":
  18206. case "audio/x-mpeg-3":
  18207. case "audio/ogg":
  18208. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18209. break;
  18210. default:
  18211. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  18212. this._sceneFileToLoad = this._filesToLoad[i];
  18213. }
  18214. break;
  18215. }
  18216. }
  18217. this.reload();
  18218. }
  18219. };
  18220. FilesInput.prototype.reload = function () {
  18221. var _this = this;
  18222. var that = this;
  18223. // If a ".babylon" file has been provided
  18224. if (this._sceneFileToLoad) {
  18225. if (this._currentScene) {
  18226. this._engine.stopRenderLoop();
  18227. this._currentScene.dispose();
  18228. }
  18229. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18230. that._currentScene = newScene;
  18231. // Wait for textures and shaders to be ready
  18232. that._currentScene.executeWhenReady(function () {
  18233. // Attach camera to canvas inputs
  18234. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18235. that._currentScene.createDefaultCameraOrLight();
  18236. }
  18237. that._currentScene.activeCamera.attachControl(that._canvas);
  18238. if (that._sceneLoadedCallback) {
  18239. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18240. }
  18241. that._engine.runRenderLoop(function () {
  18242. that.renderFunction();
  18243. });
  18244. });
  18245. }, function (progress) {
  18246. if (_this._progressCallback) {
  18247. _this._progressCallback(progress);
  18248. }
  18249. });
  18250. }
  18251. else {
  18252. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18253. }
  18254. };
  18255. FilesInput.FilesTextures = new Array();
  18256. FilesInput.FilesToLoad = new Array();
  18257. return FilesInput;
  18258. })();
  18259. BABYLON.FilesInput = FilesInput;
  18260. })(BABYLON || (BABYLON = {}));
  18261. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18262. (function (BABYLON) {
  18263. var OimoJSPlugin = (function () {
  18264. function OimoJSPlugin() {
  18265. this._registeredMeshes = [];
  18266. /**
  18267. * Update the body position according to the mesh position
  18268. * @param mesh
  18269. */
  18270. this.updateBodyPosition = function (mesh) {
  18271. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18272. var registeredMesh = this._registeredMeshes[index];
  18273. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18274. var body = registeredMesh.body.body;
  18275. mesh.computeWorldMatrix(true);
  18276. var center = mesh.getBoundingInfo().boundingBox.center;
  18277. body.setPosition(center.x, center.y, center.z);
  18278. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18279. return;
  18280. }
  18281. // Case where the parent has been updated
  18282. if (registeredMesh.mesh.parent === mesh) {
  18283. mesh.computeWorldMatrix(true);
  18284. registeredMesh.mesh.computeWorldMatrix(true);
  18285. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18286. var absoluteRotation = mesh.rotation;
  18287. body = registeredMesh.body.body;
  18288. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18289. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18290. return;
  18291. }
  18292. }
  18293. };
  18294. }
  18295. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18296. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18297. };
  18298. OimoJSPlugin.prototype.initialize = function (iterations) {
  18299. this._world = new OIMO.World();
  18300. this._world.clear();
  18301. };
  18302. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18303. this._world.gravity = gravity;
  18304. };
  18305. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18306. var body = null;
  18307. this.unregisterMesh(mesh);
  18308. mesh.computeWorldMatrix(true);
  18309. var initialRotation = null;
  18310. if (mesh.rotationQuaternion) {
  18311. initialRotation = mesh.rotationQuaternion.clone();
  18312. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18313. mesh.computeWorldMatrix(true);
  18314. }
  18315. var bbox = mesh.getBoundingInfo().boundingBox;
  18316. // The delta between the mesh position and the mesh bounding box center
  18317. var deltaPosition = mesh.position.subtract(bbox.center);
  18318. // Transform delta position with the rotation
  18319. if (initialRotation) {
  18320. var m = new BABYLON.Matrix();
  18321. initialRotation.toRotationMatrix(m);
  18322. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18323. }
  18324. switch (impostor) {
  18325. case BABYLON.PhysicsEngine.SphereImpostor:
  18326. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18327. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18328. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18329. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18330. body = new OIMO.Body({
  18331. type: 'sphere',
  18332. size: [size],
  18333. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18334. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18335. move: options.mass != 0,
  18336. config: [options.mass, options.friction, options.restitution],
  18337. world: this._world
  18338. });
  18339. break;
  18340. case BABYLON.PhysicsEngine.PlaneImpostor:
  18341. case BABYLON.PhysicsEngine.CylinderImpostor:
  18342. case BABYLON.PhysicsEngine.BoxImpostor:
  18343. var min = bbox.minimumWorld;
  18344. var max = bbox.maximumWorld;
  18345. var box = max.subtract(min);
  18346. var sizeX = this._checkWithEpsilon(box.x);
  18347. var sizeY = this._checkWithEpsilon(box.y);
  18348. var sizeZ = this._checkWithEpsilon(box.z);
  18349. body = new OIMO.Body({
  18350. type: 'box',
  18351. size: [sizeX, sizeY, sizeZ],
  18352. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18353. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18354. move: options.mass != 0,
  18355. config: [options.mass, options.friction, options.restitution],
  18356. world: this._world
  18357. });
  18358. break;
  18359. }
  18360. //If quaternion was set as the rotation of the object
  18361. if (initialRotation) {
  18362. //We have to access the rigid body's properties to set the quaternion.
  18363. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18364. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18365. //update the internal rotation matrix
  18366. body.body.syncShapes();
  18367. }
  18368. this._registeredMeshes.push({
  18369. mesh: mesh,
  18370. body: body,
  18371. delta: deltaPosition
  18372. });
  18373. return body;
  18374. };
  18375. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18376. var types = [], sizes = [], positions = [], rotations = [];
  18377. var initialMesh = parts[0].mesh;
  18378. for (var index = 0; index < parts.length; index++) {
  18379. var part = parts[index];
  18380. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18381. types.push(bodyParameters.type);
  18382. sizes.push.apply(sizes, bodyParameters.size);
  18383. positions.push.apply(positions, bodyParameters.pos);
  18384. rotations.push.apply(rotations, bodyParameters.rot);
  18385. }
  18386. var body = new OIMO.Body({
  18387. type: types,
  18388. size: sizes,
  18389. pos: positions,
  18390. rot: rotations,
  18391. move: options.mass != 0,
  18392. config: [options.mass, options.friction, options.restitution],
  18393. world: this._world
  18394. });
  18395. this._registeredMeshes.push({
  18396. mesh: initialMesh,
  18397. body: body
  18398. });
  18399. return body;
  18400. };
  18401. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18402. var bodyParameters = null;
  18403. var mesh = part.mesh;
  18404. // We need the bounding box/sphere info to compute the physics body
  18405. mesh.computeWorldMatrix();
  18406. switch (part.impostor) {
  18407. case BABYLON.PhysicsEngine.SphereImpostor:
  18408. var bbox = mesh.getBoundingInfo().boundingBox;
  18409. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18410. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18411. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18412. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18413. bodyParameters = {
  18414. type: 'sphere',
  18415. /* bug with oimo : sphere needs 3 sizes in this case */
  18416. size: [size, -1, -1],
  18417. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18418. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18419. };
  18420. break;
  18421. case BABYLON.PhysicsEngine.PlaneImpostor:
  18422. case BABYLON.PhysicsEngine.BoxImpostor:
  18423. bbox = mesh.getBoundingInfo().boundingBox;
  18424. var min = bbox.minimumWorld;
  18425. var max = bbox.maximumWorld;
  18426. var box = max.subtract(min);
  18427. var sizeX = this._checkWithEpsilon(box.x);
  18428. var sizeY = this._checkWithEpsilon(box.y);
  18429. var sizeZ = this._checkWithEpsilon(box.z);
  18430. var relativePosition = mesh.position;
  18431. bodyParameters = {
  18432. type: 'box',
  18433. size: [sizeX, sizeY, sizeZ],
  18434. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18435. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18436. };
  18437. break;
  18438. }
  18439. return bodyParameters;
  18440. };
  18441. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18442. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18443. var registeredMesh = this._registeredMeshes[index];
  18444. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18445. if (registeredMesh.body) {
  18446. this._world.removeRigidBody(registeredMesh.body.body);
  18447. this._unbindBody(registeredMesh.body);
  18448. }
  18449. this._registeredMeshes.splice(index, 1);
  18450. return;
  18451. }
  18452. }
  18453. };
  18454. OimoJSPlugin.prototype._unbindBody = function (body) {
  18455. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18456. var registeredMesh = this._registeredMeshes[index];
  18457. if (registeredMesh.body === body) {
  18458. registeredMesh.body = null;
  18459. }
  18460. }
  18461. };
  18462. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18463. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18464. var registeredMesh = this._registeredMeshes[index];
  18465. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18466. // Get object mass to have a behaviour similar to cannon.js
  18467. var mass = registeredMesh.body.body.massInfo.mass;
  18468. // The force is scaled with the mass of object
  18469. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18470. return;
  18471. }
  18472. }
  18473. };
  18474. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18475. var body1 = null, body2 = null;
  18476. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18477. var registeredMesh = this._registeredMeshes[index];
  18478. if (registeredMesh.mesh === mesh1) {
  18479. body1 = registeredMesh.body.body;
  18480. }
  18481. else if (registeredMesh.mesh === mesh2) {
  18482. body2 = registeredMesh.body.body;
  18483. }
  18484. }
  18485. if (!body1 || !body2) {
  18486. return false;
  18487. }
  18488. if (!options) {
  18489. options = {};
  18490. }
  18491. new OIMO.Link({
  18492. type: options.type,
  18493. body1: body1,
  18494. body2: body2,
  18495. min: options.min,
  18496. max: options.max,
  18497. axe1: options.axe1,
  18498. axe2: options.axe2,
  18499. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18500. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18501. collision: options.collision,
  18502. spring: options.spring,
  18503. world: this._world
  18504. });
  18505. return true;
  18506. };
  18507. OimoJSPlugin.prototype.dispose = function () {
  18508. this._world.clear();
  18509. while (this._registeredMeshes.length) {
  18510. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18511. }
  18512. };
  18513. OimoJSPlugin.prototype.isSupported = function () {
  18514. return OIMO !== undefined;
  18515. };
  18516. OimoJSPlugin.prototype._getLastShape = function (body) {
  18517. var lastShape = body.shapes;
  18518. while (lastShape.next) {
  18519. lastShape = lastShape.next;
  18520. }
  18521. return lastShape;
  18522. };
  18523. OimoJSPlugin.prototype.runOneStep = function (time) {
  18524. this._world.step();
  18525. // Update the position of all registered meshes
  18526. var i = this._registeredMeshes.length;
  18527. var m;
  18528. while (i--) {
  18529. var body = this._registeredMeshes[i].body.body;
  18530. var mesh = this._registeredMeshes[i].mesh;
  18531. var delta = this._registeredMeshes[i].delta;
  18532. if (!body.sleeping) {
  18533. if (body.shapes.next) {
  18534. var parentShape = this._getLastShape(body);
  18535. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18536. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18537. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18538. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18539. if (!mesh.rotationQuaternion) {
  18540. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18541. }
  18542. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18543. mesh.computeWorldMatrix();
  18544. }
  18545. else {
  18546. m = body.getMatrix();
  18547. mtx = BABYLON.Matrix.FromArray(m);
  18548. // Body position
  18549. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18550. if (!delta) {
  18551. mesh.position.x = bodyX;
  18552. mesh.position.y = bodyY;
  18553. mesh.position.z = bodyZ;
  18554. }
  18555. else {
  18556. mesh.position.x = bodyX + delta.x;
  18557. mesh.position.y = bodyY + delta.y;
  18558. mesh.position.z = bodyZ + delta.z;
  18559. }
  18560. if (!mesh.rotationQuaternion) {
  18561. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18562. }
  18563. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18564. mesh.computeWorldMatrix();
  18565. }
  18566. }
  18567. }
  18568. };
  18569. return OimoJSPlugin;
  18570. })();
  18571. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18572. })(BABYLON || (BABYLON = {}));
  18573. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18574. (function (BABYLON) {
  18575. var PhysicsEngine = (function () {
  18576. function PhysicsEngine(plugin) {
  18577. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18578. }
  18579. PhysicsEngine.prototype._initialize = function (gravity) {
  18580. this._currentPlugin.initialize();
  18581. this._setGravity(gravity);
  18582. };
  18583. PhysicsEngine.prototype._runOneStep = function (delta) {
  18584. if (delta > 0.1) {
  18585. delta = 0.1;
  18586. }
  18587. else if (delta <= 0) {
  18588. delta = 1.0 / 60.0;
  18589. }
  18590. this._currentPlugin.runOneStep(delta);
  18591. };
  18592. PhysicsEngine.prototype._setGravity = function (gravity) {
  18593. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18594. this._currentPlugin.setGravity(this.gravity);
  18595. };
  18596. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18597. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18598. };
  18599. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18600. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18601. };
  18602. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18603. this._currentPlugin.unregisterMesh(mesh);
  18604. };
  18605. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18606. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18607. };
  18608. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18609. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18610. };
  18611. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18612. this._currentPlugin.updateBodyPosition(mesh);
  18613. };
  18614. PhysicsEngine.prototype.dispose = function () {
  18615. this._currentPlugin.dispose();
  18616. };
  18617. PhysicsEngine.prototype.isSupported = function () {
  18618. return this._currentPlugin.isSupported();
  18619. };
  18620. // Statics
  18621. PhysicsEngine.NoImpostor = 0;
  18622. PhysicsEngine.SphereImpostor = 1;
  18623. PhysicsEngine.BoxImpostor = 2;
  18624. PhysicsEngine.PlaneImpostor = 3;
  18625. PhysicsEngine.MeshImpostor = 4;
  18626. PhysicsEngine.CapsuleImpostor = 5;
  18627. PhysicsEngine.ConeImpostor = 6;
  18628. PhysicsEngine.CylinderImpostor = 7;
  18629. PhysicsEngine.ConvexHullImpostor = 8;
  18630. PhysicsEngine.Epsilon = 0.001;
  18631. return PhysicsEngine;
  18632. })();
  18633. BABYLON.PhysicsEngine = PhysicsEngine;
  18634. })(BABYLON || (BABYLON = {}));
  18635. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18636. (function (BABYLON) {
  18637. var serializeLight = function (light) {
  18638. var serializationObject = {};
  18639. serializationObject.name = light.name;
  18640. serializationObject.id = light.id;
  18641. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18642. if (light instanceof BABYLON.PointLight) {
  18643. serializationObject.type = 0;
  18644. serializationObject.position = light.position.asArray();
  18645. }
  18646. else if (light instanceof BABYLON.DirectionalLight) {
  18647. serializationObject.type = 1;
  18648. var directionalLight = light;
  18649. serializationObject.position = directionalLight.position.asArray();
  18650. serializationObject.direction = directionalLight.direction.asArray();
  18651. }
  18652. else if (light instanceof BABYLON.SpotLight) {
  18653. serializationObject.type = 2;
  18654. var spotLight = light;
  18655. serializationObject.position = spotLight.position.asArray();
  18656. serializationObject.direction = spotLight.position.asArray();
  18657. serializationObject.angle = spotLight.angle;
  18658. serializationObject.exponent = spotLight.exponent;
  18659. }
  18660. else if (light instanceof BABYLON.HemisphericLight) {
  18661. serializationObject.type = 3;
  18662. var hemisphericLight = light;
  18663. serializationObject.direction = hemisphericLight.direction.asArray();
  18664. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18665. }
  18666. if (light.intensity) {
  18667. serializationObject.intensity = light.intensity;
  18668. }
  18669. serializationObject.range = light.range;
  18670. serializationObject.diffuse = light.diffuse.asArray();
  18671. serializationObject.specular = light.specular.asArray();
  18672. return serializationObject;
  18673. };
  18674. var serializeFresnelParameter = function (fresnelParameter) {
  18675. var serializationObject = {};
  18676. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18677. serializationObject.leftColor = fresnelParameter.leftColor;
  18678. serializationObject.rightColor = fresnelParameter.rightColor;
  18679. serializationObject.bias = fresnelParameter.bias;
  18680. serializationObject.power = fresnelParameter.power;
  18681. return serializationObject;
  18682. };
  18683. var appendAnimations = function (source, destination) {
  18684. if (source.animations) {
  18685. destination.animations = [];
  18686. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18687. var animation = source.animations[animationIndex];
  18688. destination.animations.push(serializeAnimation(animation));
  18689. }
  18690. }
  18691. };
  18692. var serializeCamera = function (camera) {
  18693. var serializationObject = {};
  18694. serializationObject.name = camera.name;
  18695. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18696. serializationObject.id = camera.id;
  18697. serializationObject.position = camera.position.asArray();
  18698. // Parent
  18699. if (camera.parent) {
  18700. serializationObject.parentId = camera.parent.id;
  18701. }
  18702. serializationObject.fov = camera.fov;
  18703. serializationObject.minZ = camera.minZ;
  18704. serializationObject.maxZ = camera.maxZ;
  18705. serializationObject.inertia = camera.inertia;
  18706. //setting the type
  18707. if (camera instanceof BABYLON.FreeCamera) {
  18708. serializationObject.type = "FreeCamera";
  18709. }
  18710. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18711. serializationObject.type = "ArcRotateCamera";
  18712. }
  18713. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18714. serializationObject.type = "AnaglyphArcRotateCamera";
  18715. }
  18716. else if (camera instanceof BABYLON.GamepadCamera) {
  18717. serializationObject.type = "GamepadCamera";
  18718. }
  18719. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18720. serializationObject.type = "AnaglyphFreeCamera";
  18721. }
  18722. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18723. serializationObject.type = "DeviceOrientationCamera";
  18724. }
  18725. else if (camera instanceof BABYLON.FollowCamera) {
  18726. serializationObject.type = "FollowCamera";
  18727. }
  18728. else if (camera instanceof BABYLON.OculusCamera) {
  18729. serializationObject.type = "OculusCamera";
  18730. }
  18731. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18732. serializationObject.type = "OculusGamepadCamera";
  18733. }
  18734. else if (camera instanceof BABYLON.TouchCamera) {
  18735. serializationObject.type = "TouchCamera";
  18736. }
  18737. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18738. serializationObject.type = "VirtualJoysticksCamera";
  18739. }
  18740. else if (camera instanceof BABYLON.WebVRCamera) {
  18741. serializationObject.type = "WebVRCamera";
  18742. }
  18743. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18744. serializationObject.type = "VRDeviceOrientationCamera";
  18745. }
  18746. //special properties of specific cameras
  18747. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18748. var arcCamera = camera;
  18749. serializationObject.alpha = arcCamera.alpha;
  18750. serializationObject.beta = arcCamera.beta;
  18751. serializationObject.radius = arcCamera.radius;
  18752. if (arcCamera.target && arcCamera.target.id) {
  18753. serializationObject.lockedTargetId = arcCamera.target.id;
  18754. }
  18755. }
  18756. else if (camera instanceof BABYLON.FollowCamera) {
  18757. var followCam = camera;
  18758. serializationObject.radius = followCam.radius;
  18759. serializationObject.heightOffset = followCam.heightOffset;
  18760. serializationObject.rotationOffset = followCam.rotationOffset;
  18761. }
  18762. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18763. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18764. if (camera['_eyeSpace'] !== undefined) {
  18765. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18766. }
  18767. }
  18768. //general properties that not all cameras have. The [] is due to typescript's type safety
  18769. if (camera['speed'] !== undefined) {
  18770. serializationObject.speed = camera['speed'];
  18771. }
  18772. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18773. serializationObject.target = camera['target'].asArray();
  18774. }
  18775. // Target
  18776. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18777. serializationObject.rotation = camera['rotation'].asArray();
  18778. }
  18779. // Locked target
  18780. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18781. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18782. }
  18783. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18784. serializationObject.applyGravity = camera['applyGravity'] || false;
  18785. if (camera['ellipsoid']) {
  18786. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18787. }
  18788. // Animations
  18789. appendAnimations(camera, serializationObject);
  18790. // Layer mask
  18791. serializationObject.layerMask = camera.layerMask;
  18792. return serializationObject;
  18793. };
  18794. var serializeAnimation = function (animation) {
  18795. var serializationObject = {};
  18796. serializationObject.name = animation.name;
  18797. serializationObject.property = animation.targetProperty;
  18798. serializationObject.framePerSecond = animation.framePerSecond;
  18799. serializationObject.dataType = animation.dataType;
  18800. serializationObject.loopBehavior = animation.loopMode;
  18801. var dataType = animation.dataType;
  18802. serializationObject.keys = [];
  18803. var keys = animation.getKeys();
  18804. for (var index = 0; index < keys.length; index++) {
  18805. var animationKey = keys[index];
  18806. var key = {};
  18807. key.frame = animationKey.frame;
  18808. switch (dataType) {
  18809. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18810. key.values = [animationKey.value];
  18811. break;
  18812. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18813. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18814. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18815. key.values = animationKey.value.asArray();
  18816. break;
  18817. }
  18818. serializationObject.keys.push(key);
  18819. }
  18820. return serializationObject;
  18821. };
  18822. var serializeMultiMaterial = function (material) {
  18823. var serializationObject = {};
  18824. serializationObject.name = material.name;
  18825. serializationObject.id = material.id;
  18826. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18827. serializationObject.materials = [];
  18828. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18829. var subMat = material.subMaterials[matIndex];
  18830. if (subMat) {
  18831. serializationObject.materials.push(subMat.id);
  18832. }
  18833. else {
  18834. serializationObject.materials.push(null);
  18835. }
  18836. }
  18837. return serializationObject;
  18838. };
  18839. var serializeMaterial = function (material) {
  18840. var serializationObject = {};
  18841. serializationObject.name = material.name;
  18842. serializationObject.ambient = material.ambientColor.asArray();
  18843. serializationObject.diffuse = material.diffuseColor.asArray();
  18844. serializationObject.specular = material.specularColor.asArray();
  18845. serializationObject.specularPower = material.specularPower;
  18846. serializationObject.emissive = material.emissiveColor.asArray();
  18847. serializationObject.alpha = material.alpha;
  18848. serializationObject.id = material.id;
  18849. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18850. serializationObject.backFaceCulling = material.backFaceCulling;
  18851. if (material.diffuseTexture) {
  18852. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18853. }
  18854. if (material.diffuseFresnelParameters) {
  18855. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18856. }
  18857. if (material.ambientTexture) {
  18858. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18859. }
  18860. if (material.opacityTexture) {
  18861. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18862. }
  18863. if (material.opacityFresnelParameters) {
  18864. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18865. }
  18866. if (material.reflectionTexture) {
  18867. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18868. }
  18869. if (material.reflectionFresnelParameters) {
  18870. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18871. }
  18872. if (material.emissiveTexture) {
  18873. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18874. }
  18875. if (material.emissiveFresnelParameters) {
  18876. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18877. }
  18878. if (material.specularTexture) {
  18879. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18880. }
  18881. if (material.bumpTexture) {
  18882. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18883. }
  18884. return serializationObject;
  18885. };
  18886. var serializeTexture = function (texture) {
  18887. var serializationObject = {};
  18888. if (!texture.name) {
  18889. return null;
  18890. }
  18891. if (texture instanceof BABYLON.CubeTexture) {
  18892. serializationObject.name = texture.name;
  18893. serializationObject.hasAlpha = texture.hasAlpha;
  18894. serializationObject.level = texture.level;
  18895. serializationObject.coordinatesMode = texture.coordinatesMode;
  18896. return serializationObject;
  18897. }
  18898. if (texture instanceof BABYLON.MirrorTexture) {
  18899. var mirrorTexture = texture;
  18900. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18901. serializationObject.renderList = [];
  18902. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18903. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18904. }
  18905. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18906. }
  18907. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18908. var renderTargetTexture = texture;
  18909. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18910. serializationObject.renderList = [];
  18911. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18912. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18913. }
  18914. }
  18915. var regularTexture = texture;
  18916. serializationObject.name = texture.name;
  18917. serializationObject.hasAlpha = texture.hasAlpha;
  18918. serializationObject.level = texture.level;
  18919. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18920. serializationObject.coordinatesMode = texture.coordinatesMode;
  18921. serializationObject.uOffset = regularTexture.uOffset;
  18922. serializationObject.vOffset = regularTexture.vOffset;
  18923. serializationObject.uScale = regularTexture.uScale;
  18924. serializationObject.vScale = regularTexture.vScale;
  18925. serializationObject.uAng = regularTexture.uAng;
  18926. serializationObject.vAng = regularTexture.vAng;
  18927. serializationObject.wAng = regularTexture.wAng;
  18928. serializationObject.wrapU = texture.wrapU;
  18929. serializationObject.wrapV = texture.wrapV;
  18930. // Animations
  18931. appendAnimations(texture, serializationObject);
  18932. return serializationObject;
  18933. };
  18934. var serializeSkeleton = function (skeleton) {
  18935. var serializationObject = {};
  18936. serializationObject.name = skeleton.name;
  18937. serializationObject.id = skeleton.id;
  18938. serializationObject.bones = [];
  18939. for (var index = 0; index < skeleton.bones.length; index++) {
  18940. var bone = skeleton.bones[index];
  18941. var serializedBone = {
  18942. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18943. name: bone.name,
  18944. matrix: bone.getLocalMatrix().toArray()
  18945. };
  18946. serializationObject.bones.push(serializedBone);
  18947. if (bone.animations && bone.animations.length > 0) {
  18948. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18949. }
  18950. }
  18951. return serializationObject;
  18952. };
  18953. var serializeParticleSystem = function (particleSystem) {
  18954. var serializationObject = {};
  18955. serializationObject.emitterId = particleSystem.emitter.id;
  18956. serializationObject.capacity = particleSystem.getCapacity();
  18957. if (particleSystem.particleTexture) {
  18958. serializationObject.textureName = particleSystem.particleTexture.name;
  18959. }
  18960. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18961. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18962. serializationObject.minSize = particleSystem.minSize;
  18963. serializationObject.maxSize = particleSystem.maxSize;
  18964. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18965. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18966. serializationObject.emitRate = particleSystem.emitRate;
  18967. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18968. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18969. serializationObject.gravity = particleSystem.gravity.asArray();
  18970. serializationObject.direction1 = particleSystem.direction1.asArray();
  18971. serializationObject.direction2 = particleSystem.direction2.asArray();
  18972. serializationObject.color1 = particleSystem.color1.asArray();
  18973. serializationObject.color2 = particleSystem.color2.asArray();
  18974. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18975. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18976. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18977. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18978. serializationObject.blendMode = particleSystem.blendMode;
  18979. return serializationObject;
  18980. };
  18981. var serializeLensFlareSystem = function (lensFlareSystem) {
  18982. var serializationObject = {};
  18983. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18984. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18985. serializationObject.flares = [];
  18986. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18987. var flare = lensFlareSystem.lensFlares[index];
  18988. serializationObject.flares.push({
  18989. size: flare.size,
  18990. position: flare.position,
  18991. color: flare.color.asArray(),
  18992. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18993. });
  18994. }
  18995. return serializationObject;
  18996. };
  18997. var serializeShadowGenerator = function (light) {
  18998. var serializationObject = {};
  18999. var shadowGenerator = light.getShadowGenerator();
  19000. serializationObject.lightId = light.id;
  19001. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19002. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19003. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19004. serializationObject.renderList = [];
  19005. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19006. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19007. serializationObject.renderList.push(mesh.id);
  19008. }
  19009. return serializationObject;
  19010. };
  19011. var serializedGeometries = [];
  19012. var serializeGeometry = function (geometry, serializationGeometries) {
  19013. if (serializedGeometries[geometry.id]) {
  19014. return;
  19015. }
  19016. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19017. serializationGeometries.boxes.push(serializeBox(geometry));
  19018. }
  19019. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19020. serializationGeometries.spheres.push(serializeSphere(geometry));
  19021. }
  19022. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19023. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19024. }
  19025. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19026. serializationGeometries.toruses.push(serializeTorus(geometry));
  19027. }
  19028. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19029. serializationGeometries.grounds.push(serializeGround(geometry));
  19030. }
  19031. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19032. serializationGeometries.planes.push(serializePlane(geometry));
  19033. }
  19034. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19035. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19036. }
  19037. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19038. throw new Error("Unknow primitive type");
  19039. }
  19040. else {
  19041. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19042. }
  19043. serializedGeometries[geometry.id] = true;
  19044. };
  19045. var serializeGeometryBase = function (geometry) {
  19046. var serializationObject = {};
  19047. serializationObject.id = geometry.id;
  19048. if (BABYLON.Tags.HasTags(geometry)) {
  19049. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19050. }
  19051. return serializationObject;
  19052. };
  19053. var serializeVertexData = function (vertexData) {
  19054. var serializationObject = serializeGeometryBase(vertexData);
  19055. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19056. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19057. }
  19058. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19059. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19060. }
  19061. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19062. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19063. }
  19064. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19065. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19066. }
  19067. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19068. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19069. }
  19070. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19071. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19072. serializationObject.matricesIndices._isExpanded = true;
  19073. }
  19074. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19075. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19076. }
  19077. serializationObject.indices = vertexData.getIndices();
  19078. return serializationObject;
  19079. };
  19080. var serializePrimitive = function (primitive) {
  19081. var serializationObject = serializeGeometryBase(primitive);
  19082. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19083. return serializationObject;
  19084. };
  19085. var serializeBox = function (box) {
  19086. var serializationObject = serializePrimitive(box);
  19087. serializationObject.size = box.size;
  19088. return serializationObject;
  19089. };
  19090. var serializeSphere = function (sphere) {
  19091. var serializationObject = serializePrimitive(sphere);
  19092. serializationObject.segments = sphere.segments;
  19093. serializationObject.diameter = sphere.diameter;
  19094. return serializationObject;
  19095. };
  19096. var serializeCylinder = function (cylinder) {
  19097. var serializationObject = serializePrimitive(cylinder);
  19098. serializationObject.height = cylinder.height;
  19099. serializationObject.diameterTop = cylinder.diameterTop;
  19100. serializationObject.diameterBottom = cylinder.diameterBottom;
  19101. serializationObject.tessellation = cylinder.tessellation;
  19102. return serializationObject;
  19103. };
  19104. var serializeTorus = function (torus) {
  19105. var serializationObject = serializePrimitive(torus);
  19106. serializationObject.diameter = torus.diameter;
  19107. serializationObject.thickness = torus.thickness;
  19108. serializationObject.tessellation = torus.tessellation;
  19109. return serializationObject;
  19110. };
  19111. var serializeGround = function (ground) {
  19112. var serializationObject = serializePrimitive(ground);
  19113. serializationObject.width = ground.width;
  19114. serializationObject.height = ground.height;
  19115. serializationObject.subdivisions = ground.subdivisions;
  19116. return serializationObject;
  19117. };
  19118. var serializePlane = function (plane) {
  19119. var serializationObject = serializePrimitive(plane);
  19120. serializationObject.size = plane.size;
  19121. return serializationObject;
  19122. };
  19123. var serializeTorusKnot = function (torusKnot) {
  19124. var serializationObject = serializePrimitive(torusKnot);
  19125. serializationObject.radius = torusKnot.radius;
  19126. serializationObject.tube = torusKnot.tube;
  19127. serializationObject.radialSegments = torusKnot.radialSegments;
  19128. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19129. serializationObject.p = torusKnot.p;
  19130. serializationObject.q = torusKnot.q;
  19131. return serializationObject;
  19132. };
  19133. var serializeMesh = function (mesh, serializationScene) {
  19134. var serializationObject = {};
  19135. serializationObject.name = mesh.name;
  19136. serializationObject.id = mesh.id;
  19137. if (BABYLON.Tags.HasTags(mesh)) {
  19138. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19139. }
  19140. serializationObject.position = mesh.position.asArray();
  19141. if (mesh.rotationQuaternion) {
  19142. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19143. }
  19144. else if (mesh.rotation) {
  19145. serializationObject.rotation = mesh.rotation.asArray();
  19146. }
  19147. serializationObject.scaling = mesh.scaling.asArray();
  19148. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19149. serializationObject.isEnabled = mesh.isEnabled();
  19150. serializationObject.isVisible = mesh.isVisible;
  19151. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19152. serializationObject.pickable = mesh.isPickable;
  19153. serializationObject.receiveShadows = mesh.receiveShadows;
  19154. serializationObject.billboardMode = mesh.billboardMode;
  19155. serializationObject.visibility = mesh.visibility;
  19156. serializationObject.checkCollisions = mesh.checkCollisions;
  19157. // Parent
  19158. if (mesh.parent) {
  19159. serializationObject.parentId = mesh.parent.id;
  19160. }
  19161. // Geometry
  19162. var geometry = mesh._geometry;
  19163. if (geometry) {
  19164. var geometryId = geometry.id;
  19165. serializationObject.geometryId = geometryId;
  19166. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19167. // 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
  19168. serializeGeometry(geometry, serializationScene.geometries);
  19169. }
  19170. // SubMeshes
  19171. serializationObject.subMeshes = [];
  19172. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19173. var subMesh = mesh.subMeshes[subIndex];
  19174. serializationObject.subMeshes.push({
  19175. materialIndex: subMesh.materialIndex,
  19176. verticesStart: subMesh.verticesStart,
  19177. verticesCount: subMesh.verticesCount,
  19178. indexStart: subMesh.indexStart,
  19179. indexCount: subMesh.indexCount
  19180. });
  19181. }
  19182. }
  19183. // Material
  19184. if (mesh.material) {
  19185. serializationObject.materialId = mesh.material.id;
  19186. }
  19187. else {
  19188. mesh.material = null;
  19189. }
  19190. // Skeleton
  19191. if (mesh.skeleton) {
  19192. serializationObject.skeletonId = mesh.skeleton.id;
  19193. }
  19194. // Physics
  19195. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19196. serializationObject.physicsMass = mesh.getPhysicsMass();
  19197. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19198. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19199. switch (mesh.getPhysicsImpostor()) {
  19200. case BABYLON.PhysicsEngine.BoxImpostor:
  19201. serializationObject.physicsImpostor = 1;
  19202. break;
  19203. case BABYLON.PhysicsEngine.SphereImpostor:
  19204. serializationObject.physicsImpostor = 2;
  19205. break;
  19206. }
  19207. }
  19208. // Instances
  19209. serializationObject.instances = [];
  19210. for (var index = 0; index < mesh.instances.length; index++) {
  19211. var instance = mesh.instances[index];
  19212. var serializationInstance = {
  19213. name: instance.name,
  19214. position: instance.position,
  19215. rotation: instance.rotation,
  19216. rotationQuaternion: instance.rotationQuaternion,
  19217. scaling: instance.scaling
  19218. };
  19219. serializationObject.instances.push(serializationInstance);
  19220. // Animations
  19221. appendAnimations(instance, serializationInstance);
  19222. }
  19223. // Animations
  19224. appendAnimations(mesh, serializationObject);
  19225. // Layer mask
  19226. serializationObject.layerMask = mesh.layerMask;
  19227. return serializationObject;
  19228. };
  19229. var SceneSerializer = (function () {
  19230. function SceneSerializer() {
  19231. }
  19232. SceneSerializer.Serialize = function (scene) {
  19233. var serializationObject = {};
  19234. // Scene
  19235. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19236. serializationObject.autoClear = scene.autoClear;
  19237. serializationObject.clearColor = scene.clearColor.asArray();
  19238. serializationObject.ambientColor = scene.ambientColor.asArray();
  19239. serializationObject.gravity = scene.gravity.asArray();
  19240. // Fog
  19241. if (scene.fogMode && scene.fogMode !== 0) {
  19242. serializationObject.fogMode = scene.fogMode;
  19243. serializationObject.fogColor = scene.fogColor.asArray();
  19244. serializationObject.fogStart = scene.fogStart;
  19245. serializationObject.fogEnd = scene.fogEnd;
  19246. serializationObject.fogDensity = scene.fogDensity;
  19247. }
  19248. // Lights
  19249. serializationObject.lights = [];
  19250. for (var index = 0; index < scene.lights.length; index++) {
  19251. var light = scene.lights[index];
  19252. serializationObject.lights.push(serializeLight(light));
  19253. }
  19254. // Cameras
  19255. serializationObject.cameras = [];
  19256. for (index = 0; index < scene.cameras.length; index++) {
  19257. var camera = scene.cameras[index];
  19258. serializationObject.cameras.push(serializeCamera(camera));
  19259. }
  19260. if (scene.activeCamera) {
  19261. serializationObject.activeCameraID = scene.activeCamera.id;
  19262. }
  19263. // Materials
  19264. serializationObject.materials = [];
  19265. serializationObject.multiMaterials = [];
  19266. for (index = 0; index < scene.materials.length; index++) {
  19267. var material = scene.materials[index];
  19268. if (material instanceof BABYLON.StandardMaterial) {
  19269. serializationObject.materials.push(serializeMaterial(material));
  19270. }
  19271. else if (material instanceof BABYLON.MultiMaterial) {
  19272. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19273. }
  19274. }
  19275. // Skeletons
  19276. serializationObject.skeletons = [];
  19277. for (index = 0; index < scene.skeletons.length; index++) {
  19278. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19279. }
  19280. // Geometries
  19281. serializationObject.geometries = {};
  19282. serializationObject.geometries.boxes = [];
  19283. serializationObject.geometries.spheres = [];
  19284. serializationObject.geometries.cylinders = [];
  19285. serializationObject.geometries.toruses = [];
  19286. serializationObject.geometries.grounds = [];
  19287. serializationObject.geometries.planes = [];
  19288. serializationObject.geometries.torusKnots = [];
  19289. serializationObject.geometries.vertexData = [];
  19290. serializedGeometries = [];
  19291. var geometries = scene.getGeometries();
  19292. for (index = 0; index < geometries.length; index++) {
  19293. var geometry = geometries[index];
  19294. if (geometry.isReady()) {
  19295. serializeGeometry(geometry, serializationObject.geometries);
  19296. }
  19297. }
  19298. // Meshes
  19299. serializationObject.meshes = [];
  19300. for (index = 0; index < scene.meshes.length; index++) {
  19301. var abstractMesh = scene.meshes[index];
  19302. if (abstractMesh instanceof BABYLON.Mesh) {
  19303. var mesh = abstractMesh;
  19304. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19305. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19306. }
  19307. }
  19308. }
  19309. // Particles Systems
  19310. serializationObject.particleSystems = [];
  19311. for (index = 0; index < scene.particleSystems.length; index++) {
  19312. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19313. }
  19314. // Lens flares
  19315. serializationObject.lensFlareSystems = [];
  19316. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19317. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19318. }
  19319. // Shadows
  19320. serializationObject.shadowGenerators = [];
  19321. for (index = 0; index < scene.lights.length; index++) {
  19322. light = scene.lights[index];
  19323. if (light.getShadowGenerator()) {
  19324. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19325. }
  19326. }
  19327. return serializationObject;
  19328. };
  19329. return SceneSerializer;
  19330. })();
  19331. BABYLON.SceneSerializer = SceneSerializer;
  19332. })(BABYLON || (BABYLON = {}));
  19333. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19334. (function (BABYLON) {
  19335. var SceneLoader = (function () {
  19336. function SceneLoader() {
  19337. }
  19338. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19339. get: function () {
  19340. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19341. },
  19342. set: function (value) {
  19343. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19349. get: function () {
  19350. return SceneLoader._ShowLoadingScreen;
  19351. },
  19352. set: function (value) {
  19353. SceneLoader._ShowLoadingScreen = value;
  19354. },
  19355. enumerable: true,
  19356. configurable: true
  19357. });
  19358. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19359. var dotPosition = sceneFilename.lastIndexOf(".");
  19360. var queryStringPosition = sceneFilename.indexOf("?");
  19361. if (queryStringPosition === -1) {
  19362. queryStringPosition = sceneFilename.length;
  19363. }
  19364. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19365. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19366. var plugin = this._registeredPlugins[index];
  19367. if (plugin.extensions.indexOf(extension) !== -1) {
  19368. return plugin;
  19369. }
  19370. }
  19371. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19372. };
  19373. // Public functions
  19374. SceneLoader.RegisterPlugin = function (plugin) {
  19375. plugin.extensions = plugin.extensions.toLowerCase();
  19376. SceneLoader._registeredPlugins.push(plugin);
  19377. };
  19378. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19379. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19380. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19381. return;
  19382. }
  19383. var manifestChecked = function (success) {
  19384. scene.database = database;
  19385. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19386. var importMeshFromData = function (data) {
  19387. var meshes = [];
  19388. var particleSystems = [];
  19389. var skeletons = [];
  19390. try {
  19391. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19392. if (onerror) {
  19393. onerror(scene, 'unable to load the scene');
  19394. }
  19395. return;
  19396. }
  19397. }
  19398. catch (e) {
  19399. if (onerror) {
  19400. onerror(scene, e);
  19401. }
  19402. return;
  19403. }
  19404. if (onsuccess) {
  19405. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19406. onsuccess(meshes, particleSystems, skeletons);
  19407. }
  19408. };
  19409. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19410. // Direct load
  19411. importMeshFromData(sceneFilename.substr(5));
  19412. return;
  19413. }
  19414. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19415. importMeshFromData(data);
  19416. }, progressCallBack, database);
  19417. };
  19418. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19419. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19420. };
  19421. /**
  19422. * Load a scene
  19423. * @param rootUrl a string that defines the root url for scene and resources
  19424. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19425. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19426. */
  19427. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19428. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19429. };
  19430. /**
  19431. * Append a scene
  19432. * @param rootUrl a string that defines the root url for scene and resources
  19433. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19434. * @param scene is the instance of BABYLON.Scene to append to
  19435. */
  19436. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19437. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19438. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19439. return;
  19440. }
  19441. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19442. var database;
  19443. if (SceneLoader.ShowLoadingScreen) {
  19444. scene.getEngine().displayLoadingUI();
  19445. }
  19446. var loadSceneFromData = function (data) {
  19447. scene.database = database;
  19448. if (!plugin.load(scene, data, rootUrl)) {
  19449. if (onerror) {
  19450. onerror(scene);
  19451. }
  19452. scene.getEngine().hideLoadingUI();
  19453. return;
  19454. }
  19455. if (onsuccess) {
  19456. onsuccess(scene);
  19457. }
  19458. if (SceneLoader.ShowLoadingScreen) {
  19459. scene.executeWhenReady(function () {
  19460. scene.getEngine().hideLoadingUI();
  19461. });
  19462. }
  19463. };
  19464. var manifestChecked = function (success) {
  19465. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19466. };
  19467. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19468. // Direct load
  19469. loadSceneFromData(sceneFilename.substr(5));
  19470. return;
  19471. }
  19472. if (rootUrl.indexOf("file:") === -1) {
  19473. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19474. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19475. }
  19476. else {
  19477. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19478. }
  19479. };
  19480. // Flags
  19481. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19482. SceneLoader._ShowLoadingScreen = true;
  19483. // Members
  19484. SceneLoader._registeredPlugins = new Array();
  19485. return SceneLoader;
  19486. })();
  19487. BABYLON.SceneLoader = SceneLoader;
  19488. ;
  19489. })(BABYLON || (BABYLON = {}));
  19490. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19491. (function (BABYLON) {
  19492. var Internals;
  19493. (function (Internals) {
  19494. var checkColors4 = function (colors, count) {
  19495. // Check if color3 was used
  19496. if (colors.length === count * 3) {
  19497. var colors4 = [];
  19498. for (var index = 0; index < colors.length; index += 3) {
  19499. var newIndex = (index / 3) * 4;
  19500. colors4[newIndex] = colors[index];
  19501. colors4[newIndex + 1] = colors[index + 1];
  19502. colors4[newIndex + 2] = colors[index + 2];
  19503. colors4[newIndex + 3] = 1.0;
  19504. }
  19505. return colors4;
  19506. }
  19507. return colors;
  19508. };
  19509. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19510. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19511. texture.name = parsedTexture.name;
  19512. texture.hasAlpha = parsedTexture.hasAlpha;
  19513. texture.level = parsedTexture.level;
  19514. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19515. return texture;
  19516. };
  19517. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19518. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19519. return null;
  19520. }
  19521. if (parsedTexture.isCube) {
  19522. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19523. }
  19524. var texture;
  19525. if (parsedTexture.mirrorPlane) {
  19526. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19527. texture._waitingRenderList = parsedTexture.renderList;
  19528. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19529. }
  19530. else if (parsedTexture.isRenderTarget) {
  19531. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19532. texture._waitingRenderList = parsedTexture.renderList;
  19533. }
  19534. else {
  19535. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19536. }
  19537. texture.name = parsedTexture.name;
  19538. texture.hasAlpha = parsedTexture.hasAlpha;
  19539. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19540. texture.level = parsedTexture.level;
  19541. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19542. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19543. texture.uOffset = parsedTexture.uOffset;
  19544. texture.vOffset = parsedTexture.vOffset;
  19545. texture.uScale = parsedTexture.uScale;
  19546. texture.vScale = parsedTexture.vScale;
  19547. texture.uAng = parsedTexture.uAng;
  19548. texture.vAng = parsedTexture.vAng;
  19549. texture.wAng = parsedTexture.wAng;
  19550. texture.wrapU = parsedTexture.wrapU;
  19551. texture.wrapV = parsedTexture.wrapV;
  19552. // Animations
  19553. if (parsedTexture.animations) {
  19554. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19555. var parsedAnimation = parsedTexture.animations[animationIndex];
  19556. texture.animations.push(parseAnimation(parsedAnimation));
  19557. }
  19558. }
  19559. return texture;
  19560. };
  19561. var parseSkeleton = function (parsedSkeleton, scene) {
  19562. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19563. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19564. var parsedBone = parsedSkeleton.bones[index];
  19565. var parentBone = null;
  19566. if (parsedBone.parentBoneIndex > -1) {
  19567. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19568. }
  19569. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19570. if (parsedBone.animation) {
  19571. bone.animations.push(parseAnimation(parsedBone.animation));
  19572. }
  19573. }
  19574. return skeleton;
  19575. };
  19576. var parseFresnelParameters = function (parsedFresnelParameters) {
  19577. var fresnelParameters = new BABYLON.FresnelParameters();
  19578. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19579. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19580. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19581. fresnelParameters.bias = parsedFresnelParameters.bias;
  19582. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19583. return fresnelParameters;
  19584. };
  19585. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19586. var material;
  19587. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19588. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19589. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19590. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19591. material.specularPower = parsedMaterial.specularPower;
  19592. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19593. material.alpha = parsedMaterial.alpha;
  19594. material.id = parsedMaterial.id;
  19595. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19596. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19597. material.wireframe = parsedMaterial.wireframe;
  19598. if (parsedMaterial.diffuseTexture) {
  19599. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19600. }
  19601. if (parsedMaterial.diffuseFresnelParameters) {
  19602. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19603. }
  19604. if (parsedMaterial.ambientTexture) {
  19605. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19606. }
  19607. if (parsedMaterial.opacityTexture) {
  19608. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19609. }
  19610. if (parsedMaterial.opacityFresnelParameters) {
  19611. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19612. }
  19613. if (parsedMaterial.reflectionTexture) {
  19614. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19615. }
  19616. if (parsedMaterial.reflectionFresnelParameters) {
  19617. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19618. }
  19619. if (parsedMaterial.emissiveTexture) {
  19620. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19621. }
  19622. if (parsedMaterial.emissiveFresnelParameters) {
  19623. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19624. }
  19625. if (parsedMaterial.specularTexture) {
  19626. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19627. }
  19628. if (parsedMaterial.bumpTexture) {
  19629. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19630. }
  19631. return material;
  19632. };
  19633. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19634. for (var index = 0; index < parsedData.materials.length; index++) {
  19635. var parsedMaterial = parsedData.materials[index];
  19636. if (parsedMaterial.id === id) {
  19637. return parseMaterial(parsedMaterial, scene, rootUrl);
  19638. }
  19639. }
  19640. return null;
  19641. };
  19642. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19643. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19644. multiMaterial.id = parsedMultiMaterial.id;
  19645. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19646. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19647. var subMatId = parsedMultiMaterial.materials[matIndex];
  19648. if (subMatId) {
  19649. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19650. }
  19651. else {
  19652. multiMaterial.subMaterials.push(null);
  19653. }
  19654. }
  19655. return multiMaterial;
  19656. };
  19657. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19658. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19659. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19660. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19661. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19662. var parsedFlare = parsedLensFlareSystem.flares[index];
  19663. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19664. }
  19665. return lensFlareSystem;
  19666. };
  19667. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19668. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19669. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19670. if (parsedParticleSystem.textureName) {
  19671. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19672. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19673. }
  19674. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19675. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19676. particleSystem.minSize = parsedParticleSystem.minSize;
  19677. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19678. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19679. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19680. particleSystem.emitter = emitter;
  19681. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19682. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19683. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19684. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19685. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19686. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19687. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19688. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19689. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19690. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19691. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19692. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19693. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19694. particleSystem.start();
  19695. return particleSystem;
  19696. };
  19697. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19698. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19699. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19700. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19701. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19702. shadowGenerator.getShadowMap().renderList.push(mesh);
  19703. }
  19704. if (parsedShadowGenerator.usePoissonSampling) {
  19705. shadowGenerator.usePoissonSampling = true;
  19706. }
  19707. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19708. shadowGenerator.useVarianceShadowMap = true;
  19709. }
  19710. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19711. shadowGenerator.useBlurVarianceShadowMap = true;
  19712. if (parsedShadowGenerator.blurScale) {
  19713. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19714. }
  19715. if (parsedShadowGenerator.blurBoxOffset) {
  19716. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19717. }
  19718. }
  19719. if (parsedShadowGenerator.bias !== undefined) {
  19720. shadowGenerator.bias = parsedShadowGenerator.bias;
  19721. }
  19722. return shadowGenerator;
  19723. };
  19724. var parseAnimation = function (parsedAnimation) {
  19725. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19726. var dataType = parsedAnimation.dataType;
  19727. var keys = [];
  19728. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19729. var key = parsedAnimation.keys[index];
  19730. var data;
  19731. switch (dataType) {
  19732. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19733. data = key.values[0];
  19734. break;
  19735. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19736. data = BABYLON.Quaternion.FromArray(key.values);
  19737. break;
  19738. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19739. data = BABYLON.Matrix.FromArray(key.values);
  19740. break;
  19741. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19742. default:
  19743. data = BABYLON.Vector3.FromArray(key.values);
  19744. break;
  19745. }
  19746. keys.push({
  19747. frame: key.frame,
  19748. value: data
  19749. });
  19750. }
  19751. animation.setKeys(keys);
  19752. return animation;
  19753. };
  19754. var parseLight = function (parsedLight, scene) {
  19755. var light;
  19756. switch (parsedLight.type) {
  19757. case 0:
  19758. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19759. break;
  19760. case 1:
  19761. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19762. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19763. break;
  19764. case 2:
  19765. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19766. break;
  19767. case 3:
  19768. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19769. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19770. break;
  19771. }
  19772. light.id = parsedLight.id;
  19773. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19774. if (parsedLight.intensity !== undefined) {
  19775. light.intensity = parsedLight.intensity;
  19776. }
  19777. if (parsedLight.range) {
  19778. light.range = parsedLight.range;
  19779. }
  19780. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19781. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19782. if (parsedLight.excludedMeshesIds) {
  19783. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19784. }
  19785. // Parent
  19786. if (parsedLight.parentId) {
  19787. light._waitingParentId = parsedLight.parentId;
  19788. }
  19789. if (parsedLight.includedOnlyMeshesIds) {
  19790. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19791. }
  19792. // Animations
  19793. if (parsedLight.animations) {
  19794. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19795. var parsedAnimation = parsedLight.animations[animationIndex];
  19796. light.animations.push(parseAnimation(parsedAnimation));
  19797. }
  19798. }
  19799. if (parsedLight.autoAnimate) {
  19800. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19801. }
  19802. };
  19803. var parseCamera = function (parsedCamera, scene) {
  19804. var camera;
  19805. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19806. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19807. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19808. var alpha = parsedCamera.alpha;
  19809. var beta = parsedCamera.beta;
  19810. var radius = parsedCamera.radius;
  19811. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19812. var eye_space = parsedCamera.eye_space;
  19813. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19814. }
  19815. else {
  19816. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19817. }
  19818. }
  19819. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19820. eye_space = parsedCamera.eye_space;
  19821. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19822. }
  19823. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19824. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19825. }
  19826. else if (parsedCamera.type === "FollowCamera") {
  19827. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19828. camera.heightOffset = parsedCamera.heightOffset;
  19829. camera.radius = parsedCamera.radius;
  19830. camera.rotationOffset = parsedCamera.rotationOffset;
  19831. if (lockedTargetMesh)
  19832. camera.target = lockedTargetMesh;
  19833. }
  19834. else if (parsedCamera.type === "GamepadCamera") {
  19835. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19836. }
  19837. else if (parsedCamera.type === "OculusCamera") {
  19838. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19839. }
  19840. else if (parsedCamera.type === "OculusGamepadCamera") {
  19841. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19842. }
  19843. else if (parsedCamera.type === "TouchCamera") {
  19844. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19845. }
  19846. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19847. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19848. }
  19849. else if (parsedCamera.type === "WebVRCamera") {
  19850. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19851. }
  19852. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19853. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19854. }
  19855. else {
  19856. // Free Camera is the default value
  19857. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19858. }
  19859. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19860. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19861. camera.lockedTarget = lockedTargetMesh;
  19862. }
  19863. camera.id = parsedCamera.id;
  19864. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19865. // Parent
  19866. if (parsedCamera.parentId) {
  19867. camera._waitingParentId = parsedCamera.parentId;
  19868. }
  19869. // Target
  19870. if (parsedCamera.target) {
  19871. if (camera.setTarget) {
  19872. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19873. }
  19874. else {
  19875. //For ArcRotate
  19876. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19877. }
  19878. }
  19879. else {
  19880. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19881. }
  19882. camera.fov = parsedCamera.fov;
  19883. camera.minZ = parsedCamera.minZ;
  19884. camera.maxZ = parsedCamera.maxZ;
  19885. camera.speed = parsedCamera.speed;
  19886. camera.inertia = parsedCamera.inertia;
  19887. camera.checkCollisions = parsedCamera.checkCollisions;
  19888. camera.applyGravity = parsedCamera.applyGravity;
  19889. if (parsedCamera.ellipsoid) {
  19890. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19891. }
  19892. // Animations
  19893. if (parsedCamera.animations) {
  19894. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19895. var parsedAnimation = parsedCamera.animations[animationIndex];
  19896. camera.animations.push(parseAnimation(parsedAnimation));
  19897. }
  19898. }
  19899. if (parsedCamera.autoAnimate) {
  19900. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19901. }
  19902. // Layer Mask
  19903. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19904. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19905. }
  19906. else {
  19907. camera.layerMask = 0xFFFFFFFF;
  19908. }
  19909. return camera;
  19910. };
  19911. var parseGeometry = function (parsedGeometry, scene) {
  19912. var id = parsedGeometry.id;
  19913. return scene.getGeometryByID(id);
  19914. };
  19915. var parseBox = function (parsedBox, scene) {
  19916. if (parseGeometry(parsedBox, scene)) {
  19917. return null; // null since geometry could be something else than a box...
  19918. }
  19919. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19920. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19921. scene.pushGeometry(box, true);
  19922. return box;
  19923. };
  19924. var parseSphere = function (parsedSphere, scene) {
  19925. if (parseGeometry(parsedSphere, scene)) {
  19926. return null; // null since geometry could be something else than a sphere...
  19927. }
  19928. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19929. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19930. scene.pushGeometry(sphere, true);
  19931. return sphere;
  19932. };
  19933. var parseCylinder = function (parsedCylinder, scene) {
  19934. if (parseGeometry(parsedCylinder, scene)) {
  19935. return null; // null since geometry could be something else than a cylinder...
  19936. }
  19937. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19938. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19939. scene.pushGeometry(cylinder, true);
  19940. return cylinder;
  19941. };
  19942. var parseTorus = function (parsedTorus, scene) {
  19943. if (parseGeometry(parsedTorus, scene)) {
  19944. return null; // null since geometry could be something else than a torus...
  19945. }
  19946. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19947. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19948. scene.pushGeometry(torus, true);
  19949. return torus;
  19950. };
  19951. var parseGround = function (parsedGround, scene) {
  19952. if (parseGeometry(parsedGround, scene)) {
  19953. return null; // null since geometry could be something else than a ground...
  19954. }
  19955. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19956. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19957. scene.pushGeometry(ground, true);
  19958. return ground;
  19959. };
  19960. var parsePlane = function (parsedPlane, scene) {
  19961. if (parseGeometry(parsedPlane, scene)) {
  19962. return null; // null since geometry could be something else than a plane...
  19963. }
  19964. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19965. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19966. scene.pushGeometry(plane, true);
  19967. return plane;
  19968. };
  19969. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19970. if (parseGeometry(parsedTorusKnot, scene)) {
  19971. return null; // null since geometry could be something else than a torusKnot...
  19972. }
  19973. 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);
  19974. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19975. scene.pushGeometry(torusKnot, true);
  19976. return torusKnot;
  19977. };
  19978. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19979. if (parseGeometry(parsedVertexData, scene)) {
  19980. return null; // null since geometry could be a primitive
  19981. }
  19982. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19983. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19984. if (parsedVertexData.delayLoadingFile) {
  19985. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19986. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19987. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19988. geometry._delayInfo = [];
  19989. if (parsedVertexData.hasUVs) {
  19990. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19991. }
  19992. if (parsedVertexData.hasUVs2) {
  19993. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19994. }
  19995. if (parsedVertexData.hasColors) {
  19996. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19997. }
  19998. if (parsedVertexData.hasMatricesIndices) {
  19999. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20000. }
  20001. if (parsedVertexData.hasMatricesWeights) {
  20002. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20003. }
  20004. geometry._delayLoadingFunction = importVertexData;
  20005. }
  20006. else {
  20007. importVertexData(parsedVertexData, geometry);
  20008. }
  20009. scene.pushGeometry(geometry, true);
  20010. return geometry;
  20011. };
  20012. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20013. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20014. mesh.id = parsedMesh.id;
  20015. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20016. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20017. if (parsedMesh.rotationQuaternion) {
  20018. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20019. }
  20020. else if (parsedMesh.rotation) {
  20021. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20022. }
  20023. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20024. if (parsedMesh.localMatrix) {
  20025. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20026. }
  20027. else if (parsedMesh.pivotMatrix) {
  20028. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20029. }
  20030. mesh.setEnabled(parsedMesh.isEnabled);
  20031. mesh.isVisible = parsedMesh.isVisible;
  20032. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20033. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20034. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20035. if (parsedMesh.applyFog !== undefined) {
  20036. mesh.applyFog = parsedMesh.applyFog;
  20037. }
  20038. if (parsedMesh.pickable !== undefined) {
  20039. mesh.isPickable = parsedMesh.pickable;
  20040. }
  20041. if (parsedMesh.alphaIndex !== undefined) {
  20042. mesh.alphaIndex = parsedMesh.alphaIndex;
  20043. }
  20044. mesh.receiveShadows = parsedMesh.receiveShadows;
  20045. mesh.billboardMode = parsedMesh.billboardMode;
  20046. if (parsedMesh.visibility !== undefined) {
  20047. mesh.visibility = parsedMesh.visibility;
  20048. }
  20049. mesh.checkCollisions = parsedMesh.checkCollisions;
  20050. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20051. // Parent
  20052. if (parsedMesh.parentId) {
  20053. mesh._waitingParentId = parsedMesh.parentId;
  20054. }
  20055. // Actions
  20056. if (parsedMesh.actions !== undefined) {
  20057. mesh._waitingActions = parsedMesh.actions;
  20058. }
  20059. // Geometry
  20060. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20061. if (parsedMesh.delayLoadingFile) {
  20062. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20063. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20064. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20065. if (parsedMesh._binaryInfo) {
  20066. mesh._binaryInfo = parsedMesh._binaryInfo;
  20067. }
  20068. mesh._delayInfo = [];
  20069. if (parsedMesh.hasUVs) {
  20070. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20071. }
  20072. if (parsedMesh.hasUVs2) {
  20073. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20074. }
  20075. if (parsedMesh.hasColors) {
  20076. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20077. }
  20078. if (parsedMesh.hasMatricesIndices) {
  20079. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20080. }
  20081. if (parsedMesh.hasMatricesWeights) {
  20082. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20083. }
  20084. mesh._delayLoadingFunction = importGeometry;
  20085. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20086. mesh._checkDelayState();
  20087. }
  20088. }
  20089. else {
  20090. importGeometry(parsedMesh, mesh);
  20091. }
  20092. // Material
  20093. if (parsedMesh.materialId) {
  20094. mesh.setMaterialByID(parsedMesh.materialId);
  20095. }
  20096. else {
  20097. mesh.material = null;
  20098. }
  20099. // Skeleton
  20100. if (parsedMesh.skeletonId > -1) {
  20101. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20102. }
  20103. // Physics
  20104. if (parsedMesh.physicsImpostor) {
  20105. if (!scene.isPhysicsEnabled()) {
  20106. scene.enablePhysics();
  20107. }
  20108. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20109. }
  20110. // Animations
  20111. if (parsedMesh.animations) {
  20112. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20113. var parsedAnimation = parsedMesh.animations[animationIndex];
  20114. mesh.animations.push(parseAnimation(parsedAnimation));
  20115. }
  20116. }
  20117. if (parsedMesh.autoAnimate) {
  20118. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20119. }
  20120. // Layer Mask
  20121. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20122. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20123. }
  20124. else {
  20125. mesh.layerMask = 0xFFFFFFFF;
  20126. }
  20127. // Instances
  20128. if (parsedMesh.instances) {
  20129. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20130. var parsedInstance = parsedMesh.instances[index];
  20131. var instance = mesh.createInstance(parsedInstance.name);
  20132. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20133. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20134. if (parsedInstance.rotationQuaternion) {
  20135. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20136. }
  20137. else if (parsedInstance.rotation) {
  20138. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20139. }
  20140. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20141. instance.checkCollisions = mesh.checkCollisions;
  20142. if (parsedMesh.animations) {
  20143. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20144. parsedAnimation = parsedMesh.animations[animationIndex];
  20145. instance.animations.push(parseAnimation(parsedAnimation));
  20146. }
  20147. }
  20148. }
  20149. }
  20150. return mesh;
  20151. };
  20152. var parseActions = function (parsedActions, object, scene) {
  20153. var actionManager = new BABYLON.ActionManager(scene);
  20154. if (object === null)
  20155. scene.actionManager = actionManager;
  20156. else
  20157. object.actionManager = actionManager;
  20158. // instanciate a new object
  20159. var instanciate = function (name, params) {
  20160. var newInstance = Object.create(BABYLON[name].prototype);
  20161. newInstance.constructor.apply(newInstance, params);
  20162. return newInstance;
  20163. };
  20164. var parseParameter = function (name, value, target, propertyPath) {
  20165. if (propertyPath === null) {
  20166. // String, boolean or float
  20167. var floatValue = parseFloat(value);
  20168. if (value === "true" || value === "false")
  20169. return value === "true";
  20170. else
  20171. return isNaN(floatValue) ? value : floatValue;
  20172. }
  20173. var effectiveTarget = propertyPath.split(".");
  20174. var values = value.split(",");
  20175. for (var i = 0; i < effectiveTarget.length; i++) {
  20176. target = target[effectiveTarget[i]];
  20177. }
  20178. // Return appropriate value with its type
  20179. if (target instanceof Boolean)
  20180. return values[0] === "true";
  20181. if (target instanceof String)
  20182. return values[0];
  20183. // Parameters with multiple values such as Vector3 etc.
  20184. var split = new Array();
  20185. for (var i = 0; i < values.length; i++)
  20186. split.push(parseFloat(values[i]));
  20187. if (target instanceof BABYLON.Vector3)
  20188. return BABYLON.Vector3.FromArray(split);
  20189. if (target instanceof BABYLON.Vector4)
  20190. return BABYLON.Vector4.FromArray(split);
  20191. if (target instanceof BABYLON.Color3)
  20192. return BABYLON.Color3.FromArray(split);
  20193. if (target instanceof BABYLON.Color4)
  20194. return BABYLON.Color4.FromArray(split);
  20195. return parseFloat(values[0]);
  20196. };
  20197. // traverse graph per trigger
  20198. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20199. if (combineArray === void 0) { combineArray = null; }
  20200. if (parsedAction.detached)
  20201. return;
  20202. var parameters = new Array();
  20203. var target = null;
  20204. var propertyPath = null;
  20205. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20206. // Parameters
  20207. if (parsedAction.type === 2)
  20208. parameters.push(actionManager);
  20209. else
  20210. parameters.push(trigger);
  20211. if (combine) {
  20212. var actions = new Array();
  20213. for (var j = 0; j < parsedAction.combine.length; j++) {
  20214. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20215. }
  20216. parameters.push(actions);
  20217. }
  20218. else {
  20219. for (var i = 0; i < parsedAction.properties.length; i++) {
  20220. var value = parsedAction.properties[i].value;
  20221. var name = parsedAction.properties[i].name;
  20222. if (name === "target")
  20223. value = target = scene.getNodeByName(value);
  20224. else if (name === "parent")
  20225. value = scene.getNodeByName(value);
  20226. else if (name === "sound")
  20227. value = scene.getSoundByName(value);
  20228. else if (name !== "propertyPath") {
  20229. if (parsedAction.type === 2 && name === "operator")
  20230. value = BABYLON.ValueCondition[value];
  20231. else
  20232. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20233. }
  20234. else {
  20235. propertyPath = value;
  20236. }
  20237. parameters.push(value);
  20238. }
  20239. }
  20240. parameters.push(condition);
  20241. // If interpolate value action
  20242. if (parsedAction.name === "InterpolateValueAction") {
  20243. var param = parameters[parameters.length - 2];
  20244. parameters[parameters.length - 1] = param;
  20245. parameters[parameters.length - 2] = condition;
  20246. }
  20247. // Action or condition(s) and not CombineAction
  20248. var newAction = instanciate(parsedAction.name, parameters);
  20249. if (combineArray === null) {
  20250. if (newAction instanceof BABYLON.Condition) {
  20251. condition = newAction;
  20252. newAction = action;
  20253. }
  20254. else {
  20255. condition = null;
  20256. if (action)
  20257. action.then(newAction);
  20258. else
  20259. actionManager.registerAction(newAction);
  20260. }
  20261. }
  20262. else {
  20263. combineArray.push(newAction);
  20264. }
  20265. for (var i = 0; i < parsedAction.children.length; i++)
  20266. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20267. };
  20268. for (var i = 0; i < parsedActions.children.length; i++) {
  20269. var triggerParams;
  20270. var trigger = parsedActions.children[i];
  20271. if (trigger.properties.length > 0) {
  20272. var param = trigger.properties[0].value;
  20273. var value = trigger.properties[0].targetType == null ? param : scene.getMeshByName(param);
  20274. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20275. }
  20276. else
  20277. triggerParams = BABYLON.ActionManager[trigger.name];
  20278. for (var j = 0; j < trigger.children.length; j++) {
  20279. if (!trigger.detached)
  20280. traverse(trigger.children[j], triggerParams, null, null);
  20281. }
  20282. }
  20283. };
  20284. var parseSound = function (parsedSound, scene, rootUrl) {
  20285. var soundName = parsedSound.name;
  20286. var soundUrl = rootUrl + soundName;
  20287. var options = {
  20288. autoplay: parsedSound.autoplay,
  20289. loop: parsedSound.loop,
  20290. volume: parsedSound.volume,
  20291. spatialSound: parsedSound.spatialSound,
  20292. maxDistance: parsedSound.maxDistance,
  20293. rolloffFactor: parsedSound.rolloffFactor,
  20294. refDistance: parsedSound.refDistance,
  20295. distanceModel: parsedSound.distanceModel,
  20296. playbackRate: parsedSound.playbackRate
  20297. };
  20298. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20299. scene._removePendingData(newSound);
  20300. }, options);
  20301. scene._addPendingData(newSound);
  20302. if (parsedSound.position) {
  20303. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20304. newSound.setPosition(soundPosition);
  20305. }
  20306. if (parsedSound.isDirectional) {
  20307. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20308. if (parsedSound.localDirectionToMesh) {
  20309. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20310. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20311. }
  20312. }
  20313. if (parsedSound.connectedMeshId) {
  20314. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20315. if (connectedMesh) {
  20316. newSound.attachToMesh(connectedMesh);
  20317. }
  20318. }
  20319. };
  20320. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20321. names = (names instanceof Array) ? names : [names];
  20322. for (var i in names) {
  20323. if (mesh.name === names[i]) {
  20324. hierarchyIds.push(mesh.id);
  20325. return true;
  20326. }
  20327. }
  20328. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20329. hierarchyIds.push(mesh.id);
  20330. return true;
  20331. }
  20332. return false;
  20333. };
  20334. var importVertexData = function (parsedVertexData, geometry) {
  20335. var vertexData = new BABYLON.VertexData();
  20336. // positions
  20337. var positions = parsedVertexData.positions;
  20338. if (positions) {
  20339. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20340. }
  20341. // normals
  20342. var normals = parsedVertexData.normals;
  20343. if (normals) {
  20344. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20345. }
  20346. // uvs
  20347. var uvs = parsedVertexData.uvs;
  20348. if (uvs) {
  20349. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20350. }
  20351. // uv2s
  20352. var uv2s = parsedVertexData.uv2s;
  20353. if (uv2s) {
  20354. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20355. }
  20356. // colors
  20357. var colors = parsedVertexData.colors;
  20358. if (colors) {
  20359. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20360. }
  20361. // matricesIndices
  20362. var matricesIndices = parsedVertexData.matricesIndices;
  20363. if (matricesIndices) {
  20364. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20365. }
  20366. // matricesWeights
  20367. var matricesWeights = parsedVertexData.matricesWeights;
  20368. if (matricesWeights) {
  20369. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20370. }
  20371. // indices
  20372. var indices = parsedVertexData.indices;
  20373. if (indices) {
  20374. vertexData.indices = indices;
  20375. }
  20376. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20377. };
  20378. var importGeometry = function (parsedGeometry, mesh) {
  20379. var scene = mesh.getScene();
  20380. // Geometry
  20381. var geometryId = parsedGeometry.geometryId;
  20382. if (geometryId) {
  20383. var geometry = scene.getGeometryByID(geometryId);
  20384. if (geometry) {
  20385. geometry.applyToMesh(mesh);
  20386. }
  20387. }
  20388. else if (parsedGeometry instanceof ArrayBuffer) {
  20389. var binaryInfo = mesh._binaryInfo;
  20390. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20391. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20392. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20393. }
  20394. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20395. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20396. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20397. }
  20398. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20399. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20400. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20401. }
  20402. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20403. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20404. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20405. }
  20406. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20407. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20408. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20409. }
  20410. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20411. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20412. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20413. }
  20414. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20415. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20416. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20417. }
  20418. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20419. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20420. mesh.setIndices(indicesData);
  20421. }
  20422. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20423. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20424. mesh.subMeshes = [];
  20425. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20426. var materialIndex = subMeshesData[(i * 5) + 0];
  20427. var verticesStart = subMeshesData[(i * 5) + 1];
  20428. var verticesCount = subMeshesData[(i * 5) + 2];
  20429. var indexStart = subMeshesData[(i * 5) + 3];
  20430. var indexCount = subMeshesData[(i * 5) + 4];
  20431. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20432. }
  20433. }
  20434. }
  20435. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20436. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20437. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20438. if (parsedGeometry.uvs) {
  20439. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20440. }
  20441. if (parsedGeometry.uvs2) {
  20442. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20443. }
  20444. if (parsedGeometry.colors) {
  20445. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20446. }
  20447. if (parsedGeometry.matricesIndices) {
  20448. if (!parsedGeometry.matricesIndices._isExpanded) {
  20449. var floatIndices = [];
  20450. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20451. var matricesIndex = parsedGeometry.matricesIndices[i];
  20452. floatIndices.push(matricesIndex & 0x000000FF);
  20453. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20454. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20455. floatIndices.push(matricesIndex >> 24);
  20456. }
  20457. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20458. }
  20459. else {
  20460. delete parsedGeometry.matricesIndices._isExpanded;
  20461. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20462. }
  20463. }
  20464. if (parsedGeometry.matricesWeights) {
  20465. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20466. }
  20467. mesh.setIndices(parsedGeometry.indices);
  20468. // SubMeshes
  20469. if (parsedGeometry.subMeshes) {
  20470. mesh.subMeshes = [];
  20471. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20472. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20473. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20474. }
  20475. }
  20476. }
  20477. // Flat shading
  20478. if (mesh._shouldGenerateFlatShading) {
  20479. mesh.convertToFlatShadedMesh();
  20480. delete mesh._shouldGenerateFlatShading;
  20481. }
  20482. // Update
  20483. mesh.computeWorldMatrix(true);
  20484. // Octree
  20485. if (scene._selectionOctree) {
  20486. scene._selectionOctree.addMesh(mesh);
  20487. }
  20488. };
  20489. BABYLON.SceneLoader.RegisterPlugin({
  20490. extensions: ".babylon",
  20491. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20492. var parsedData = JSON.parse(data);
  20493. var loadedSkeletonsIds = [];
  20494. var loadedMaterialsIds = [];
  20495. var hierarchyIds = [];
  20496. for (var index = 0; index < parsedData.meshes.length; index++) {
  20497. var parsedMesh = parsedData.meshes[index];
  20498. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20499. if (meshesNames instanceof Array) {
  20500. // Remove found mesh name from list.
  20501. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20502. }
  20503. // Material ?
  20504. if (parsedMesh.materialId) {
  20505. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20506. if (!materialFound) {
  20507. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20508. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20509. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20510. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20511. var subMatId = parsedMultiMaterial.materials[matIndex];
  20512. loadedMaterialsIds.push(subMatId);
  20513. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20514. }
  20515. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20516. parseMultiMaterial(parsedMultiMaterial, scene);
  20517. materialFound = true;
  20518. break;
  20519. }
  20520. }
  20521. }
  20522. if (!materialFound) {
  20523. loadedMaterialsIds.push(parsedMesh.materialId);
  20524. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20525. }
  20526. }
  20527. // Skeleton ?
  20528. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20529. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20530. if (!skeletonAlreadyLoaded) {
  20531. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20532. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20533. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20534. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20535. loadedSkeletonsIds.push(parsedSkeleton.id);
  20536. }
  20537. }
  20538. }
  20539. }
  20540. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20541. meshes.push(mesh);
  20542. }
  20543. }
  20544. for (index = 0; index < scene.meshes.length; index++) {
  20545. var currentMesh = scene.meshes[index];
  20546. if (currentMesh._waitingParentId) {
  20547. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20548. currentMesh._waitingParentId = undefined;
  20549. }
  20550. }
  20551. // Particles
  20552. if (parsedData.particleSystems) {
  20553. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20554. var parsedParticleSystem = parsedData.particleSystems[index];
  20555. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20556. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20557. }
  20558. }
  20559. }
  20560. return true;
  20561. },
  20562. load: function (scene, data, rootUrl) {
  20563. var parsedData = JSON.parse(data);
  20564. // Scene
  20565. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20566. scene.autoClear = parsedData.autoClear;
  20567. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20568. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20569. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20570. // Fog
  20571. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20572. scene.fogMode = parsedData.fogMode;
  20573. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20574. scene.fogStart = parsedData.fogStart;
  20575. scene.fogEnd = parsedData.fogEnd;
  20576. scene.fogDensity = parsedData.fogDensity;
  20577. }
  20578. for (var index = 0; index < parsedData.lights.length; index++) {
  20579. var parsedLight = parsedData.lights[index];
  20580. parseLight(parsedLight, scene);
  20581. }
  20582. // Materials
  20583. if (parsedData.materials) {
  20584. for (index = 0; index < parsedData.materials.length; index++) {
  20585. var parsedMaterial = parsedData.materials[index];
  20586. parseMaterial(parsedMaterial, scene, rootUrl);
  20587. }
  20588. }
  20589. if (parsedData.multiMaterials) {
  20590. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20591. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20592. parseMultiMaterial(parsedMultiMaterial, scene);
  20593. }
  20594. }
  20595. // Skeletons
  20596. if (parsedData.skeletons) {
  20597. for (index = 0; index < parsedData.skeletons.length; index++) {
  20598. var parsedSkeleton = parsedData.skeletons[index];
  20599. parseSkeleton(parsedSkeleton, scene);
  20600. }
  20601. }
  20602. // Geometries
  20603. var geometries = parsedData.geometries;
  20604. if (geometries) {
  20605. // Boxes
  20606. var boxes = geometries.boxes;
  20607. if (boxes) {
  20608. for (index = 0; index < boxes.length; index++) {
  20609. var parsedBox = boxes[index];
  20610. parseBox(parsedBox, scene);
  20611. }
  20612. }
  20613. // Spheres
  20614. var spheres = geometries.spheres;
  20615. if (spheres) {
  20616. for (index = 0; index < spheres.length; index++) {
  20617. var parsedSphere = spheres[index];
  20618. parseSphere(parsedSphere, scene);
  20619. }
  20620. }
  20621. // Cylinders
  20622. var cylinders = geometries.cylinders;
  20623. if (cylinders) {
  20624. for (index = 0; index < cylinders.length; index++) {
  20625. var parsedCylinder = cylinders[index];
  20626. parseCylinder(parsedCylinder, scene);
  20627. }
  20628. }
  20629. // Toruses
  20630. var toruses = geometries.toruses;
  20631. if (toruses) {
  20632. for (index = 0; index < toruses.length; index++) {
  20633. var parsedTorus = toruses[index];
  20634. parseTorus(parsedTorus, scene);
  20635. }
  20636. }
  20637. // Grounds
  20638. var grounds = geometries.grounds;
  20639. if (grounds) {
  20640. for (index = 0; index < grounds.length; index++) {
  20641. var parsedGround = grounds[index];
  20642. parseGround(parsedGround, scene);
  20643. }
  20644. }
  20645. // Planes
  20646. var planes = geometries.planes;
  20647. if (planes) {
  20648. for (index = 0; index < planes.length; index++) {
  20649. var parsedPlane = planes[index];
  20650. parsePlane(parsedPlane, scene);
  20651. }
  20652. }
  20653. // TorusKnots
  20654. var torusKnots = geometries.torusKnots;
  20655. if (torusKnots) {
  20656. for (index = 0; index < torusKnots.length; index++) {
  20657. var parsedTorusKnot = torusKnots[index];
  20658. parseTorusKnot(parsedTorusKnot, scene);
  20659. }
  20660. }
  20661. // VertexData
  20662. var vertexData = geometries.vertexData;
  20663. if (vertexData) {
  20664. for (index = 0; index < vertexData.length; index++) {
  20665. var parsedVertexData = vertexData[index];
  20666. parseVertexData(parsedVertexData, scene, rootUrl);
  20667. }
  20668. }
  20669. }
  20670. for (index = 0; index < parsedData.meshes.length; index++) {
  20671. var parsedMesh = parsedData.meshes[index];
  20672. parseMesh(parsedMesh, scene, rootUrl);
  20673. }
  20674. for (index = 0; index < parsedData.cameras.length; index++) {
  20675. var parsedCamera = parsedData.cameras[index];
  20676. parseCamera(parsedCamera, scene);
  20677. }
  20678. if (parsedData.activeCameraID) {
  20679. scene.setActiveCameraByID(parsedData.activeCameraID);
  20680. }
  20681. for (index = 0; index < scene.cameras.length; index++) {
  20682. var camera = scene.cameras[index];
  20683. if (camera._waitingParentId) {
  20684. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20685. camera._waitingParentId = undefined;
  20686. }
  20687. }
  20688. for (index = 0; index < scene.lights.length; index++) {
  20689. var light = scene.lights[index];
  20690. if (light._waitingParentId) {
  20691. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20692. light._waitingParentId = undefined;
  20693. }
  20694. }
  20695. // Sounds
  20696. if (parsedData.sounds) {
  20697. for (index = 0; index < parsedData.sounds.length; index++) {
  20698. var parsedSound = parsedData.sounds[index];
  20699. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20700. parseSound(parsedSound, scene, rootUrl);
  20701. }
  20702. else {
  20703. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20704. }
  20705. }
  20706. }
  20707. for (index = 0; index < scene.meshes.length; index++) {
  20708. var mesh = scene.meshes[index];
  20709. if (mesh._waitingParentId) {
  20710. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20711. mesh._waitingParentId = undefined;
  20712. }
  20713. if (mesh._waitingActions) {
  20714. parseActions(mesh._waitingActions, mesh, scene);
  20715. mesh._waitingActions = undefined;
  20716. }
  20717. }
  20718. // Particles Systems
  20719. if (parsedData.particleSystems) {
  20720. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20721. var parsedParticleSystem = parsedData.particleSystems[index];
  20722. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20723. }
  20724. }
  20725. // Lens flares
  20726. if (parsedData.lensFlareSystems) {
  20727. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20728. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20729. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20730. }
  20731. }
  20732. // Shadows
  20733. if (parsedData.shadowGenerators) {
  20734. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20735. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20736. parseShadowGenerator(parsedShadowGenerator, scene);
  20737. }
  20738. }
  20739. // Actions (scene)
  20740. if (parsedData.actions) {
  20741. parseActions(parsedData.actions, null, scene);
  20742. }
  20743. // Finish
  20744. return true;
  20745. }
  20746. });
  20747. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20748. })(BABYLON || (BABYLON = {}));
  20749. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20750. (function (BABYLON) {
  20751. // Unique ID when we import meshes from Babylon to CSG
  20752. var currentCSGMeshId = 0;
  20753. // # class Vertex
  20754. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20755. // one to provide additional features like texture coordinates and vertex
  20756. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20757. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20758. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20759. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20760. // is not used anywhere else.
  20761. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20762. var Vertex = (function () {
  20763. function Vertex(pos, normal, uv) {
  20764. this.pos = pos;
  20765. this.normal = normal;
  20766. this.uv = uv;
  20767. }
  20768. Vertex.prototype.clone = function () {
  20769. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20770. };
  20771. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20772. // orientation of a polygon is flipped.
  20773. Vertex.prototype.flip = function () {
  20774. this.normal = this.normal.scale(-1);
  20775. };
  20776. // Create a new vertex between this vertex and `other` by linearly
  20777. // interpolating all properties using a parameter of `t`. Subclasses should
  20778. // override this to interpolate additional properties.
  20779. Vertex.prototype.interpolate = function (other, t) {
  20780. 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));
  20781. };
  20782. return Vertex;
  20783. })();
  20784. // # class Plane
  20785. // Represents a plane in 3D space.
  20786. var Plane = (function () {
  20787. function Plane(normal, w) {
  20788. this.normal = normal;
  20789. this.w = w;
  20790. }
  20791. Plane.FromPoints = function (a, b, c) {
  20792. var v0 = c.subtract(a);
  20793. var v1 = b.subtract(a);
  20794. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20795. return null;
  20796. }
  20797. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20798. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20799. };
  20800. Plane.prototype.clone = function () {
  20801. return new Plane(this.normal.clone(), this.w);
  20802. };
  20803. Plane.prototype.flip = function () {
  20804. this.normal.scaleInPlace(-1);
  20805. this.w = -this.w;
  20806. };
  20807. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20808. // fragments in the appropriate lists. Coplanar polygons go into either
  20809. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20810. // respect to this plane. Polygons in front or in back of this plane go into
  20811. // either `front` or `back`.
  20812. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20813. var COPLANAR = 0;
  20814. var FRONT = 1;
  20815. var BACK = 2;
  20816. var SPANNING = 3;
  20817. // Classify each point as well as the entire polygon into one of the above
  20818. // four classes.
  20819. var polygonType = 0;
  20820. var types = [];
  20821. for (var i = 0; i < polygon.vertices.length; i++) {
  20822. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20823. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20824. polygonType |= type;
  20825. types.push(type);
  20826. }
  20827. switch (polygonType) {
  20828. case COPLANAR:
  20829. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20830. break;
  20831. case FRONT:
  20832. front.push(polygon);
  20833. break;
  20834. case BACK:
  20835. back.push(polygon);
  20836. break;
  20837. case SPANNING:
  20838. var f = [], b = [];
  20839. for (i = 0; i < polygon.vertices.length; i++) {
  20840. var j = (i + 1) % polygon.vertices.length;
  20841. var ti = types[i], tj = types[j];
  20842. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20843. if (ti != BACK)
  20844. f.push(vi);
  20845. if (ti != FRONT)
  20846. b.push(ti != BACK ? vi.clone() : vi);
  20847. if ((ti | tj) == SPANNING) {
  20848. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20849. var v = vi.interpolate(vj, t);
  20850. f.push(v);
  20851. b.push(v.clone());
  20852. }
  20853. }
  20854. if (f.length >= 3) {
  20855. var poly = new Polygon(f, polygon.shared);
  20856. if (poly.plane)
  20857. front.push(poly);
  20858. }
  20859. if (b.length >= 3) {
  20860. poly = new Polygon(b, polygon.shared);
  20861. if (poly.plane)
  20862. back.push(poly);
  20863. }
  20864. break;
  20865. }
  20866. };
  20867. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20868. // point is on the plane.
  20869. Plane.EPSILON = 1e-5;
  20870. return Plane;
  20871. })();
  20872. // # class Polygon
  20873. // Represents a convex polygon. The vertices used to initialize a polygon must
  20874. // be coplanar and form a convex loop.
  20875. //
  20876. // Each convex polygon has a `shared` property, which is shared between all
  20877. // polygons that are clones of each other or were split from the same polygon.
  20878. // This can be used to define per-polygon properties (such as surface color).
  20879. var Polygon = (function () {
  20880. function Polygon(vertices, shared) {
  20881. this.vertices = vertices;
  20882. this.shared = shared;
  20883. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20884. }
  20885. Polygon.prototype.clone = function () {
  20886. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20887. return new Polygon(vertices, this.shared);
  20888. };
  20889. Polygon.prototype.flip = function () {
  20890. this.vertices.reverse().map(function (v) {
  20891. v.flip();
  20892. });
  20893. this.plane.flip();
  20894. };
  20895. return Polygon;
  20896. })();
  20897. // # class Node
  20898. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20899. // by picking a polygon to split along. That polygon (and all other coplanar
  20900. // polygons) are added directly to that node and the other polygons are added to
  20901. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20902. // no distinction between internal and leaf nodes.
  20903. var Node = (function () {
  20904. function Node(polygons) {
  20905. this.plane = null;
  20906. this.front = null;
  20907. this.back = null;
  20908. this.polygons = [];
  20909. if (polygons) {
  20910. this.build(polygons);
  20911. }
  20912. }
  20913. Node.prototype.clone = function () {
  20914. var node = new Node();
  20915. node.plane = this.plane && this.plane.clone();
  20916. node.front = this.front && this.front.clone();
  20917. node.back = this.back && this.back.clone();
  20918. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20919. return node;
  20920. };
  20921. // Convert solid space to empty space and empty space to solid space.
  20922. Node.prototype.invert = function () {
  20923. for (var i = 0; i < this.polygons.length; i++) {
  20924. this.polygons[i].flip();
  20925. }
  20926. if (this.plane) {
  20927. this.plane.flip();
  20928. }
  20929. if (this.front) {
  20930. this.front.invert();
  20931. }
  20932. if (this.back) {
  20933. this.back.invert();
  20934. }
  20935. var temp = this.front;
  20936. this.front = this.back;
  20937. this.back = temp;
  20938. };
  20939. // Recursively remove all polygons in `polygons` that are inside this BSP
  20940. // tree.
  20941. Node.prototype.clipPolygons = function (polygons) {
  20942. if (!this.plane)
  20943. return polygons.slice();
  20944. var front = [], back = [];
  20945. for (var i = 0; i < polygons.length; i++) {
  20946. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20947. }
  20948. if (this.front) {
  20949. front = this.front.clipPolygons(front);
  20950. }
  20951. if (this.back) {
  20952. back = this.back.clipPolygons(back);
  20953. }
  20954. else {
  20955. back = [];
  20956. }
  20957. return front.concat(back);
  20958. };
  20959. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20960. // `bsp`.
  20961. Node.prototype.clipTo = function (bsp) {
  20962. this.polygons = bsp.clipPolygons(this.polygons);
  20963. if (this.front)
  20964. this.front.clipTo(bsp);
  20965. if (this.back)
  20966. this.back.clipTo(bsp);
  20967. };
  20968. // Return a list of all polygons in this BSP tree.
  20969. Node.prototype.allPolygons = function () {
  20970. var polygons = this.polygons.slice();
  20971. if (this.front)
  20972. polygons = polygons.concat(this.front.allPolygons());
  20973. if (this.back)
  20974. polygons = polygons.concat(this.back.allPolygons());
  20975. return polygons;
  20976. };
  20977. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20978. // new polygons are filtered down to the bottom of the tree and become new
  20979. // nodes there. Each set of polygons is partitioned using the first polygon
  20980. // (no heuristic is used to pick a good split).
  20981. Node.prototype.build = function (polygons) {
  20982. if (!polygons.length)
  20983. return;
  20984. if (!this.plane)
  20985. this.plane = polygons[0].plane.clone();
  20986. var front = [], back = [];
  20987. for (var i = 0; i < polygons.length; i++) {
  20988. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20989. }
  20990. if (front.length) {
  20991. if (!this.front)
  20992. this.front = new Node();
  20993. this.front.build(front);
  20994. }
  20995. if (back.length) {
  20996. if (!this.back)
  20997. this.back = new Node();
  20998. this.back.build(back);
  20999. }
  21000. };
  21001. return Node;
  21002. })();
  21003. var CSG = (function () {
  21004. function CSG() {
  21005. this.polygons = new Array();
  21006. }
  21007. // Convert BABYLON.Mesh to BABYLON.CSG
  21008. CSG.FromMesh = function (mesh) {
  21009. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21010. if (mesh instanceof BABYLON.Mesh) {
  21011. mesh.computeWorldMatrix(true);
  21012. var matrix = mesh.getWorldMatrix();
  21013. var meshPosition = mesh.position.clone();
  21014. var meshRotation = mesh.rotation.clone();
  21015. var meshScaling = mesh.scaling.clone();
  21016. }
  21017. else {
  21018. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21019. }
  21020. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21021. var subMeshes = mesh.subMeshes;
  21022. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21023. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21024. vertices = [];
  21025. for (var j = 0; j < 3; j++) {
  21026. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21027. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21028. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21029. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21030. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21031. vertex = new Vertex(position, normal, uv);
  21032. vertices.push(vertex);
  21033. }
  21034. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21035. // To handle the case of degenerated triangle
  21036. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21037. if (polygon.plane)
  21038. polygons.push(polygon);
  21039. }
  21040. }
  21041. var csg = CSG.FromPolygons(polygons);
  21042. csg.matrix = matrix;
  21043. csg.position = meshPosition;
  21044. csg.rotation = meshRotation;
  21045. csg.scaling = meshScaling;
  21046. currentCSGMeshId++;
  21047. return csg;
  21048. };
  21049. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21050. CSG.FromPolygons = function (polygons) {
  21051. var csg = new BABYLON.CSG();
  21052. csg.polygons = polygons;
  21053. return csg;
  21054. };
  21055. CSG.prototype.clone = function () {
  21056. var csg = new BABYLON.CSG();
  21057. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21058. csg.copyTransformAttributes(this);
  21059. return csg;
  21060. };
  21061. CSG.prototype.toPolygons = function () {
  21062. return this.polygons;
  21063. };
  21064. CSG.prototype.union = function (csg) {
  21065. var a = new Node(this.clone().polygons);
  21066. var b = new Node(csg.clone().polygons);
  21067. a.clipTo(b);
  21068. b.clipTo(a);
  21069. b.invert();
  21070. b.clipTo(a);
  21071. b.invert();
  21072. a.build(b.allPolygons());
  21073. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21074. };
  21075. CSG.prototype.unionInPlace = function (csg) {
  21076. var a = new Node(this.polygons);
  21077. var b = new Node(csg.polygons);
  21078. a.clipTo(b);
  21079. b.clipTo(a);
  21080. b.invert();
  21081. b.clipTo(a);
  21082. b.invert();
  21083. a.build(b.allPolygons());
  21084. this.polygons = a.allPolygons();
  21085. };
  21086. CSG.prototype.subtract = function (csg) {
  21087. var a = new Node(this.clone().polygons);
  21088. var b = new Node(csg.clone().polygons);
  21089. a.invert();
  21090. a.clipTo(b);
  21091. b.clipTo(a);
  21092. b.invert();
  21093. b.clipTo(a);
  21094. b.invert();
  21095. a.build(b.allPolygons());
  21096. a.invert();
  21097. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21098. };
  21099. CSG.prototype.subtractInPlace = function (csg) {
  21100. var a = new Node(this.polygons);
  21101. var b = new Node(csg.polygons);
  21102. a.invert();
  21103. a.clipTo(b);
  21104. b.clipTo(a);
  21105. b.invert();
  21106. b.clipTo(a);
  21107. b.invert();
  21108. a.build(b.allPolygons());
  21109. a.invert();
  21110. this.polygons = a.allPolygons();
  21111. };
  21112. CSG.prototype.intersect = function (csg) {
  21113. var a = new Node(this.clone().polygons);
  21114. var b = new Node(csg.clone().polygons);
  21115. a.invert();
  21116. b.clipTo(a);
  21117. b.invert();
  21118. a.clipTo(b);
  21119. b.clipTo(a);
  21120. a.build(b.allPolygons());
  21121. a.invert();
  21122. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21123. };
  21124. CSG.prototype.intersectInPlace = function (csg) {
  21125. var a = new Node(this.polygons);
  21126. var b = new Node(csg.polygons);
  21127. a.invert();
  21128. b.clipTo(a);
  21129. b.invert();
  21130. a.clipTo(b);
  21131. b.clipTo(a);
  21132. a.build(b.allPolygons());
  21133. a.invert();
  21134. this.polygons = a.allPolygons();
  21135. };
  21136. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21137. // not modified.
  21138. CSG.prototype.inverse = function () {
  21139. var csg = this.clone();
  21140. csg.inverseInPlace();
  21141. return csg;
  21142. };
  21143. CSG.prototype.inverseInPlace = function () {
  21144. this.polygons.map(function (p) {
  21145. p.flip();
  21146. });
  21147. };
  21148. // This is used to keep meshes transformations so they can be restored
  21149. // when we build back a Babylon Mesh
  21150. // NB : All CSG operations are performed in world coordinates
  21151. CSG.prototype.copyTransformAttributes = function (csg) {
  21152. this.matrix = csg.matrix;
  21153. this.position = csg.position;
  21154. this.rotation = csg.rotation;
  21155. this.scaling = csg.scaling;
  21156. return this;
  21157. };
  21158. // Build Raw mesh from CSG
  21159. // Coordinates here are in world space
  21160. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21161. var matrix = this.matrix.clone();
  21162. matrix.invert();
  21163. 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;
  21164. if (keepSubMeshes) {
  21165. // Sort Polygons, since subMeshes are indices range
  21166. polygons.sort(function (a, b) {
  21167. if (a.shared.meshId === b.shared.meshId) {
  21168. return a.shared.subMeshId - b.shared.subMeshId;
  21169. }
  21170. else {
  21171. return a.shared.meshId - b.shared.meshId;
  21172. }
  21173. });
  21174. }
  21175. for (var i = 0, il = polygons.length; i < il; i++) {
  21176. polygon = polygons[i];
  21177. // Building SubMeshes
  21178. if (!subMesh_dict[polygon.shared.meshId]) {
  21179. subMesh_dict[polygon.shared.meshId] = {};
  21180. }
  21181. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21182. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21183. indexStart: +Infinity,
  21184. indexEnd: -Infinity,
  21185. materialIndex: polygon.shared.materialIndex
  21186. };
  21187. }
  21188. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21189. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21190. polygonIndices[0] = 0;
  21191. polygonIndices[1] = j - 1;
  21192. polygonIndices[2] = j;
  21193. for (var k = 0; k < 3; k++) {
  21194. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21195. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21196. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21197. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21198. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21199. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21200. // Check if 2 points can be merged
  21201. 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)) {
  21202. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21203. uvs.push(uv.x, uv.y);
  21204. normals.push(normal.x, normal.y, normal.z);
  21205. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21206. }
  21207. indices.push(vertex_idx);
  21208. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21209. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21210. currentIndex++;
  21211. }
  21212. }
  21213. }
  21214. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21215. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21216. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21217. mesh.setIndices(indices);
  21218. if (keepSubMeshes) {
  21219. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21220. var materialIndexOffset = 0, materialMaxIndex;
  21221. mesh.subMeshes.length = 0;
  21222. for (var m in subMesh_dict) {
  21223. materialMaxIndex = -1;
  21224. for (var sm in subMesh_dict[m]) {
  21225. subMesh_obj = subMesh_dict[m][sm];
  21226. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21227. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21228. }
  21229. materialIndexOffset += ++materialMaxIndex;
  21230. }
  21231. }
  21232. return mesh;
  21233. };
  21234. // Build Mesh from CSG taking material and transforms into account
  21235. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21236. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21237. mesh.material = material;
  21238. mesh.position.copyFrom(this.position);
  21239. mesh.rotation.copyFrom(this.rotation);
  21240. mesh.scaling.copyFrom(this.scaling);
  21241. mesh.computeWorldMatrix(true);
  21242. return mesh;
  21243. };
  21244. return CSG;
  21245. })();
  21246. BABYLON.CSG = CSG;
  21247. })(BABYLON || (BABYLON = {}));
  21248. //# sourceMappingURL=babylon.csg.js.map
  21249. var BABYLON;
  21250. (function (BABYLON) {
  21251. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21252. __extends(OculusDistortionCorrectionPostProcess, _super);
  21253. //ANY
  21254. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21255. var _this = this;
  21256. _super.call(this, name, "oculusDistortionCorrection", [
  21257. 'LensCenter',
  21258. 'Scale',
  21259. 'ScaleIn',
  21260. 'HmdWarpParam'
  21261. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21262. this._isRightEye = isRightEye;
  21263. this._distortionFactors = cameraSettings.DistortionK;
  21264. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21265. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21266. this.onSizeChanged = function () {
  21267. _this.aspectRatio = _this.width * .5 / _this.height;
  21268. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21269. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21270. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21271. };
  21272. this.onApply = function (effect) {
  21273. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21274. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21275. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21276. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21277. };
  21278. }
  21279. return OculusDistortionCorrectionPostProcess;
  21280. })(BABYLON.PostProcess);
  21281. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21282. })(BABYLON || (BABYLON = {}));
  21283. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21284. // 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
  21285. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21286. var BABYLON;
  21287. (function (BABYLON) {
  21288. (function (JoystickAxis) {
  21289. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21290. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21291. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21292. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21293. var JoystickAxis = BABYLON.JoystickAxis;
  21294. var VirtualJoystick = (function () {
  21295. function VirtualJoystick(leftJoystick) {
  21296. var _this = this;
  21297. if (leftJoystick) {
  21298. this._leftJoystick = true;
  21299. }
  21300. else {
  21301. this._leftJoystick = false;
  21302. }
  21303. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21304. VirtualJoystick._globalJoystickIndex++;
  21305. // By default left & right arrow keys are moving the X
  21306. // and up & down keys are moving the Y
  21307. this._axisTargetedByLeftAndRight = 0 /* X */;
  21308. this._axisTargetedByUpAndDown = 1 /* Y */;
  21309. this.reverseLeftRight = false;
  21310. this.reverseUpDown = false;
  21311. // collections of pointers
  21312. this._touches = new BABYLON.VirtualJoystick.Collection();
  21313. this.deltaPosition = BABYLON.Vector3.Zero();
  21314. this._joystickSensibility = 25;
  21315. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21316. this._rotationSpeed = 25;
  21317. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21318. this._rotateOnAxisRelativeToMesh = false;
  21319. // injecting a canvas element on top of the canvas 3D game
  21320. if (!VirtualJoystick.vjCanvas) {
  21321. window.addEventListener("resize", function () {
  21322. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21323. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21324. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21325. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21326. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21327. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21328. }, false);
  21329. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21330. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21331. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21332. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21333. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21334. VirtualJoystick.vjCanvas.style.width = "100%";
  21335. VirtualJoystick.vjCanvas.style.height = "100%";
  21336. VirtualJoystick.vjCanvas.style.position = "absolute";
  21337. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21338. VirtualJoystick.vjCanvas.style.top = "0px";
  21339. VirtualJoystick.vjCanvas.style.left = "0px";
  21340. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21341. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21342. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21343. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21344. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21345. document.body.appendChild(VirtualJoystick.vjCanvas);
  21346. }
  21347. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21348. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21349. this.pressed = false;
  21350. // default joystick color
  21351. this._joystickColor = "cyan";
  21352. this._joystickPointerID = -1;
  21353. // current joystick position
  21354. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21355. // origin joystick position
  21356. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21357. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21358. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21359. _this._onPointerDown(evt);
  21360. }, false);
  21361. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21362. _this._onPointerMove(evt);
  21363. }, false);
  21364. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21365. _this._onPointerUp(evt);
  21366. }, false);
  21367. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21368. _this._onPointerUp(evt);
  21369. }, false);
  21370. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21371. evt.preventDefault(); // Disables system menu
  21372. }, false);
  21373. requestAnimationFrame(function () {
  21374. _this._drawVirtualJoystick();
  21375. });
  21376. }
  21377. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21378. this._joystickSensibility = newJoystickSensibility;
  21379. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21380. };
  21381. VirtualJoystick.prototype._onPointerDown = function (e) {
  21382. var positionOnScreenCondition;
  21383. e.preventDefault();
  21384. if (this._leftJoystick === true) {
  21385. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21386. }
  21387. else {
  21388. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21389. }
  21390. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21391. // First contact will be dedicated to the virtual joystick
  21392. this._joystickPointerID = e.pointerId;
  21393. this._joystickPointerStartPos.x = e.clientX;
  21394. this._joystickPointerStartPos.y = e.clientY;
  21395. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21396. this._deltaJoystickVector.x = 0;
  21397. this._deltaJoystickVector.y = 0;
  21398. this.pressed = true;
  21399. this._touches.add(e.pointerId.toString(), e);
  21400. }
  21401. else {
  21402. // You can only trigger the action buttons with a joystick declared
  21403. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21404. this._action();
  21405. this._touches.add(e.pointerId.toString(), e);
  21406. }
  21407. }
  21408. };
  21409. VirtualJoystick.prototype._onPointerMove = function (e) {
  21410. // If the current pointer is the one associated to the joystick (first touch contact)
  21411. if (this._joystickPointerID == e.pointerId) {
  21412. this._joystickPointerPos.x = e.clientX;
  21413. this._joystickPointerPos.y = e.clientY;
  21414. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21415. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21416. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21417. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21418. switch (this._axisTargetedByLeftAndRight) {
  21419. case 0 /* X */:
  21420. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21421. break;
  21422. case 1 /* Y */:
  21423. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21424. break;
  21425. case 2 /* Z */:
  21426. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21427. break;
  21428. }
  21429. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21430. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21431. switch (this._axisTargetedByUpAndDown) {
  21432. case 0 /* X */:
  21433. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21434. break;
  21435. case 1 /* Y */:
  21436. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21437. break;
  21438. case 2 /* Z */:
  21439. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21440. break;
  21441. }
  21442. }
  21443. else {
  21444. if (this._touches.item(e.pointerId.toString())) {
  21445. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21446. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21447. }
  21448. }
  21449. };
  21450. VirtualJoystick.prototype._onPointerUp = function (e) {
  21451. this._clearCanvas();
  21452. if (this._joystickPointerID == e.pointerId) {
  21453. this._joystickPointerID = -1;
  21454. this.pressed = false;
  21455. }
  21456. this._deltaJoystickVector.x = 0;
  21457. this._deltaJoystickVector.y = 0;
  21458. this._touches.remove(e.pointerId.toString());
  21459. };
  21460. /**
  21461. * Change the color of the virtual joystick
  21462. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21463. */
  21464. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21465. this._joystickColor = newColor;
  21466. };
  21467. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21468. this._action = action;
  21469. };
  21470. // Define which axis you'd like to control for left & right
  21471. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21472. switch (axis) {
  21473. case 0 /* X */:
  21474. case 1 /* Y */:
  21475. case 2 /* Z */:
  21476. this._axisTargetedByLeftAndRight = axis;
  21477. break;
  21478. default:
  21479. this._axisTargetedByLeftAndRight = 0 /* X */;
  21480. break;
  21481. }
  21482. };
  21483. // Define which axis you'd like to control for up & down
  21484. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21485. switch (axis) {
  21486. case 0 /* X */:
  21487. case 1 /* Y */:
  21488. case 2 /* Z */:
  21489. this._axisTargetedByUpAndDown = axis;
  21490. break;
  21491. default:
  21492. this._axisTargetedByUpAndDown = 1 /* Y */;
  21493. break;
  21494. }
  21495. };
  21496. VirtualJoystick.prototype._clearCanvas = function () {
  21497. if (this._leftJoystick) {
  21498. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21499. }
  21500. else {
  21501. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21502. }
  21503. };
  21504. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21505. var _this = this;
  21506. if (this.pressed) {
  21507. this._clearCanvas();
  21508. this._touches.forEach(function (touch) {
  21509. if (touch.pointerId === _this._joystickPointerID) {
  21510. VirtualJoystick.vjCanvasContext.beginPath();
  21511. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21512. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21513. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21514. VirtualJoystick.vjCanvasContext.stroke();
  21515. VirtualJoystick.vjCanvasContext.beginPath();
  21516. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21517. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21518. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21519. VirtualJoystick.vjCanvasContext.stroke();
  21520. VirtualJoystick.vjCanvasContext.beginPath();
  21521. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21522. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21523. VirtualJoystick.vjCanvasContext.stroke();
  21524. }
  21525. else {
  21526. VirtualJoystick.vjCanvasContext.beginPath();
  21527. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21528. VirtualJoystick.vjCanvasContext.beginPath();
  21529. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21530. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21531. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21532. VirtualJoystick.vjCanvasContext.stroke();
  21533. }
  21534. ;
  21535. });
  21536. }
  21537. requestAnimationFrame(function () {
  21538. _this._drawVirtualJoystick();
  21539. });
  21540. };
  21541. VirtualJoystick.prototype.releaseCanvas = function () {
  21542. if (VirtualJoystick.vjCanvas) {
  21543. document.body.removeChild(VirtualJoystick.vjCanvas);
  21544. VirtualJoystick.vjCanvas = null;
  21545. }
  21546. };
  21547. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21548. VirtualJoystick._globalJoystickIndex = 0;
  21549. return VirtualJoystick;
  21550. })();
  21551. BABYLON.VirtualJoystick = VirtualJoystick;
  21552. })(BABYLON || (BABYLON = {}));
  21553. var BABYLON;
  21554. (function (BABYLON) {
  21555. var VirtualJoystick;
  21556. (function (VirtualJoystick) {
  21557. var Collection = (function () {
  21558. function Collection() {
  21559. this._count = 0;
  21560. this._collection = new Array();
  21561. }
  21562. Collection.prototype.Count = function () {
  21563. return this._count;
  21564. };
  21565. Collection.prototype.add = function (key, item) {
  21566. if (this._collection[key] != undefined) {
  21567. return undefined;
  21568. }
  21569. this._collection[key] = item;
  21570. return ++this._count;
  21571. };
  21572. Collection.prototype.remove = function (key) {
  21573. if (this._collection[key] == undefined) {
  21574. return undefined;
  21575. }
  21576. delete this._collection[key];
  21577. return --this._count;
  21578. };
  21579. Collection.prototype.item = function (key) {
  21580. return this._collection[key];
  21581. };
  21582. Collection.prototype.forEach = function (block) {
  21583. var key;
  21584. for (key in this._collection) {
  21585. if (this._collection.hasOwnProperty(key)) {
  21586. block(this._collection[key]);
  21587. }
  21588. }
  21589. };
  21590. return Collection;
  21591. })();
  21592. VirtualJoystick.Collection = Collection;
  21593. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21594. })(BABYLON || (BABYLON = {}));
  21595. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21596. var BABYLON;
  21597. (function (BABYLON) {
  21598. var OculusRiftDevKit2013_Metric = {
  21599. HResolution: 1280,
  21600. VResolution: 800,
  21601. HScreenSize: 0.149759993,
  21602. VScreenSize: 0.0935999975,
  21603. VScreenCenter: 0.0467999987,
  21604. EyeToScreenDistance: 0.0410000011,
  21605. LensSeparationDistance: 0.0635000020,
  21606. InterpupillaryDistance: 0.0640000030,
  21607. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21608. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21609. PostProcessScaleFactor: 1.714605507808412,
  21610. LensCenterOffset: 0.151976421
  21611. };
  21612. var _OculusInnerCamera = (function (_super) {
  21613. __extends(_OculusInnerCamera, _super);
  21614. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21615. _super.call(this, name, position, scene);
  21616. this._workMatrix = new BABYLON.Matrix();
  21617. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21618. // Constants
  21619. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21620. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21621. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21622. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21623. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21624. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21625. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21626. // Postprocess
  21627. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21628. }
  21629. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21630. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21631. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21632. return this._projectionMatrix;
  21633. };
  21634. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21635. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21636. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21637. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21638. // Computing target and final matrix
  21639. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21640. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21641. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21642. return this._viewMatrix;
  21643. };
  21644. return _OculusInnerCamera;
  21645. })(BABYLON.FreeCamera);
  21646. var OculusCamera = (function (_super) {
  21647. __extends(OculusCamera, _super);
  21648. function OculusCamera(name, position, scene) {
  21649. _super.call(this, name, position, scene);
  21650. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21651. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21652. this.subCameras.push(this._leftCamera);
  21653. this.subCameras.push(this._rightCamera);
  21654. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21655. }
  21656. OculusCamera.prototype._update = function () {
  21657. this._leftCamera.position.copyFrom(this.position);
  21658. this._rightCamera.position.copyFrom(this.position);
  21659. this._updateCamera(this._leftCamera);
  21660. this._updateCamera(this._rightCamera);
  21661. _super.prototype._update.call(this);
  21662. };
  21663. OculusCamera.prototype._updateCamera = function (camera) {
  21664. camera.minZ = this.minZ;
  21665. camera.maxZ = this.maxZ;
  21666. camera.rotation.x = this.rotation.x;
  21667. camera.rotation.y = this.rotation.y;
  21668. camera.rotation.z = this.rotation.z;
  21669. };
  21670. // Oculus events
  21671. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21672. var yaw = evt.alpha / 180 * Math.PI;
  21673. var pitch = evt.beta / 180 * Math.PI;
  21674. var roll = evt.gamma / 180 * Math.PI;
  21675. if (!this._offsetOrientation) {
  21676. this._offsetOrientation = {
  21677. yaw: yaw,
  21678. pitch: pitch,
  21679. roll: roll
  21680. };
  21681. return;
  21682. }
  21683. else {
  21684. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21685. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21686. this.rotation.z += this._offsetOrientation.roll - roll;
  21687. this._offsetOrientation.yaw = yaw;
  21688. this._offsetOrientation.pitch = pitch;
  21689. this._offsetOrientation.roll = roll;
  21690. }
  21691. };
  21692. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21693. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21694. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21695. };
  21696. OculusCamera.prototype.detachControl = function (element) {
  21697. _super.prototype.detachControl.call(this, element);
  21698. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21699. };
  21700. return OculusCamera;
  21701. })(BABYLON.FreeCamera);
  21702. BABYLON.OculusCamera = OculusCamera;
  21703. })(BABYLON || (BABYLON = {}));
  21704. //# sourceMappingURL=babylon.oculusCamera.js.map
  21705. var BABYLON;
  21706. (function (BABYLON) {
  21707. var OculusRiftDevKit2013_Metric = {
  21708. HResolution: 1280,
  21709. VResolution: 800,
  21710. HScreenSize: 0.149759993,
  21711. VScreenSize: 0.0935999975,
  21712. VScreenCenter: 0.0467999987,
  21713. EyeToScreenDistance: 0.0410000011,
  21714. LensSeparationDistance: 0.0635000020,
  21715. InterpupillaryDistance: 0.0640000030,
  21716. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21717. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21718. PostProcessScaleFactor: 1.714605507808412,
  21719. LensCenterOffset: 0.151976421
  21720. };
  21721. var _OculusInnerGamepadCamera = (function (_super) {
  21722. __extends(_OculusInnerGamepadCamera, _super);
  21723. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21724. _super.call(this, name, position, scene);
  21725. this._workMatrix = new BABYLON.Matrix();
  21726. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21727. // Constants
  21728. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21729. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21730. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21731. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21732. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21733. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21734. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21735. // Postprocess
  21736. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21737. }
  21738. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21739. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21740. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21741. return this._projectionMatrix;
  21742. };
  21743. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21744. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21745. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21746. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21747. // Computing target and final matrix
  21748. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21749. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21750. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21751. return this._viewMatrix;
  21752. };
  21753. return _OculusInnerGamepadCamera;
  21754. })(BABYLON.FreeCamera);
  21755. var OculusGamepadCamera = (function (_super) {
  21756. __extends(OculusGamepadCamera, _super);
  21757. function OculusGamepadCamera(name, position, scene) {
  21758. var _this = this;
  21759. _super.call(this, name, position, scene);
  21760. this.angularSensibility = 200;
  21761. this.moveSensibility = 75;
  21762. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21763. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21764. this.subCameras.push(this._leftCamera);
  21765. this.subCameras.push(this._rightCamera);
  21766. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21767. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21768. _this._onNewGameConnected(gamepad);
  21769. });
  21770. }
  21771. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21772. // Only the first gamepad can control the camera
  21773. if (gamepad.index === 0) {
  21774. this._gamepad = gamepad;
  21775. }
  21776. };
  21777. OculusGamepadCamera.prototype._update = function () {
  21778. this._leftCamera.position.copyFrom(this.position);
  21779. this._rightCamera.position.copyFrom(this.position);
  21780. this._updateCamera(this._leftCamera);
  21781. this._updateCamera(this._rightCamera);
  21782. _super.prototype._update.call(this);
  21783. };
  21784. OculusGamepadCamera.prototype._checkInputs = function () {
  21785. if (!this._gamepad) {
  21786. return;
  21787. }
  21788. var LSValues = this._gamepad.leftStick;
  21789. var normalizedLX = LSValues.x / this.moveSensibility;
  21790. var normalizedLY = LSValues.y / this.moveSensibility;
  21791. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21792. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21793. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21794. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21795. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21796. };
  21797. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21798. camera.minZ = this.minZ;
  21799. camera.maxZ = this.maxZ;
  21800. camera.rotation.x = this.rotation.x;
  21801. camera.rotation.y = this.rotation.y;
  21802. camera.rotation.z = this.rotation.z;
  21803. };
  21804. // Oculus events
  21805. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21806. var yaw = evt.alpha / 180 * Math.PI;
  21807. var pitch = evt.beta / 180 * Math.PI;
  21808. var roll = evt.gamma / 180 * Math.PI;
  21809. if (!this._offsetOrientation) {
  21810. this._offsetOrientation = {
  21811. yaw: yaw,
  21812. pitch: pitch,
  21813. roll: roll
  21814. };
  21815. return;
  21816. }
  21817. else {
  21818. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21819. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21820. this.rotation.z += this._offsetOrientation.roll - roll;
  21821. this._offsetOrientation.yaw = yaw;
  21822. this._offsetOrientation.pitch = pitch;
  21823. this._offsetOrientation.roll = roll;
  21824. }
  21825. };
  21826. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21827. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21828. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21829. };
  21830. OculusGamepadCamera.prototype.detachControl = function (element) {
  21831. _super.prototype.detachControl.call(this, element);
  21832. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21833. };
  21834. OculusGamepadCamera.prototype.dispose = function () {
  21835. this._gamepads.dispose();
  21836. _super.prototype.dispose.call(this);
  21837. };
  21838. return OculusGamepadCamera;
  21839. })(BABYLON.FreeCamera);
  21840. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21841. })(BABYLON || (BABYLON = {}));
  21842. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21843. var BABYLON;
  21844. (function (BABYLON) {
  21845. // We're mainly based on the logic defined into the FreeCamera code
  21846. var VirtualJoysticksCamera = (function (_super) {
  21847. __extends(VirtualJoysticksCamera, _super);
  21848. function VirtualJoysticksCamera(name, position, scene) {
  21849. _super.call(this, name, position, scene);
  21850. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21851. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21852. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21853. this._leftjoystick.setJoystickSensibility(0.15);
  21854. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21855. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21856. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21857. this._rightjoystick.reverseUpDown = true;
  21858. this._rightjoystick.setJoystickSensibility(0.05);
  21859. this._rightjoystick.setJoystickColor("yellow");
  21860. }
  21861. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21862. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21863. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21864. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21865. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21866. if (!this._leftjoystick.pressed) {
  21867. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21868. }
  21869. if (!this._rightjoystick.pressed) {
  21870. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21871. }
  21872. };
  21873. VirtualJoysticksCamera.prototype.dispose = function () {
  21874. this._leftjoystick.releaseCanvas();
  21875. _super.prototype.dispose.call(this);
  21876. };
  21877. return VirtualJoysticksCamera;
  21878. })(BABYLON.FreeCamera);
  21879. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21880. })(BABYLON || (BABYLON = {}));
  21881. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21882. var BABYLON;
  21883. (function (BABYLON) {
  21884. var ShaderMaterial = (function (_super) {
  21885. __extends(ShaderMaterial, _super);
  21886. function ShaderMaterial(name, scene, shaderPath, options) {
  21887. _super.call(this, name, scene);
  21888. this._textures = new Array();
  21889. this._floats = new Array();
  21890. this._floatsArrays = {};
  21891. this._colors3 = new Array();
  21892. this._colors4 = new Array();
  21893. this._vectors2 = new Array();
  21894. this._vectors3 = new Array();
  21895. this._matrices = new Array();
  21896. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21897. this._shaderPath = shaderPath;
  21898. options.needAlphaBlending = options.needAlphaBlending || false;
  21899. options.needAlphaTesting = options.needAlphaTesting || false;
  21900. options.attributes = options.attributes || ["position", "normal", "uv"];
  21901. options.uniforms = options.uniforms || ["worldViewProjection"];
  21902. options.samplers = options.samplers || [];
  21903. this._options = options;
  21904. }
  21905. ShaderMaterial.prototype.needAlphaBlending = function () {
  21906. return this._options.needAlphaBlending;
  21907. };
  21908. ShaderMaterial.prototype.needAlphaTesting = function () {
  21909. return this._options.needAlphaTesting;
  21910. };
  21911. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21912. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21913. this._options.uniforms.push(uniformName);
  21914. }
  21915. };
  21916. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21917. if (this._options.samplers.indexOf(name) === -1) {
  21918. this._options.samplers.push(name);
  21919. }
  21920. this._textures[name] = texture;
  21921. return this;
  21922. };
  21923. ShaderMaterial.prototype.setFloat = function (name, value) {
  21924. this._checkUniform(name);
  21925. this._floats[name] = value;
  21926. return this;
  21927. };
  21928. ShaderMaterial.prototype.setFloats = function (name, value) {
  21929. this._checkUniform(name);
  21930. this._floatsArrays[name] = value;
  21931. return this;
  21932. };
  21933. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21934. this._checkUniform(name);
  21935. this._colors3[name] = value;
  21936. return this;
  21937. };
  21938. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21939. this._checkUniform(name);
  21940. this._colors4[name] = value;
  21941. return this;
  21942. };
  21943. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21944. this._checkUniform(name);
  21945. this._vectors2[name] = value;
  21946. return this;
  21947. };
  21948. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21949. this._checkUniform(name);
  21950. this._vectors3[name] = value;
  21951. return this;
  21952. };
  21953. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21954. this._checkUniform(name);
  21955. this._matrices[name] = value;
  21956. return this;
  21957. };
  21958. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  21959. var scene = this.getScene();
  21960. var engine = scene.getEngine();
  21961. if (!this.checkReadyOnEveryCall) {
  21962. if (this._renderId === scene.getRenderId()) {
  21963. return true;
  21964. }
  21965. }
  21966. // Instances
  21967. var defines = [];
  21968. var fallbacks = new BABYLON.EffectFallbacks();
  21969. if (useInstances) {
  21970. defines.push("#define INSTANCES");
  21971. }
  21972. // Bones
  21973. if (mesh && mesh.useBones) {
  21974. defines.push("#define BONES");
  21975. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  21976. defines.push("#define BONES4");
  21977. fallbacks.addFallback(0, "BONES4");
  21978. }
  21979. // Alpha test
  21980. if (engine.getAlphaTesting()) {
  21981. defines.push("#define ALPHATEST");
  21982. }
  21983. var previousEffect = this._effect;
  21984. var join = defines.join("\n");
  21985. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  21986. if (!this._effect.isReady()) {
  21987. return false;
  21988. }
  21989. if (previousEffect !== this._effect) {
  21990. scene.resetCachedMaterial();
  21991. }
  21992. this._renderId = scene.getRenderId();
  21993. return true;
  21994. };
  21995. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21996. var scene = this.getScene();
  21997. if (this._options.uniforms.indexOf("world") !== -1) {
  21998. this._effect.setMatrix("world", world);
  21999. }
  22000. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22001. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22002. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22003. }
  22004. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22005. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22006. }
  22007. };
  22008. ShaderMaterial.prototype.bind = function (world, mesh) {
  22009. // Std values
  22010. this.bindOnlyWorldMatrix(world);
  22011. if (this.getScene().getCachedMaterial() !== this) {
  22012. if (this._options.uniforms.indexOf("view") !== -1) {
  22013. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22014. }
  22015. if (this._options.uniforms.indexOf("projection") !== -1) {
  22016. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22017. }
  22018. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22019. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22020. }
  22021. // Bones
  22022. if (mesh && mesh.useBones) {
  22023. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22024. }
  22025. for (var name in this._textures) {
  22026. this._effect.setTexture(name, this._textures[name]);
  22027. }
  22028. for (name in this._floats) {
  22029. this._effect.setFloat(name, this._floats[name]);
  22030. }
  22031. for (name in this._floatsArrays) {
  22032. this._effect.setArray(name, this._floatsArrays[name]);
  22033. }
  22034. for (name in this._colors3) {
  22035. this._effect.setColor3(name, this._colors3[name]);
  22036. }
  22037. for (name in this._colors4) {
  22038. var color = this._colors4[name];
  22039. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22040. }
  22041. for (name in this._vectors2) {
  22042. this._effect.setVector2(name, this._vectors2[name]);
  22043. }
  22044. for (name in this._vectors3) {
  22045. this._effect.setVector3(name, this._vectors3[name]);
  22046. }
  22047. for (name in this._matrices) {
  22048. this._effect.setMatrix(name, this._matrices[name]);
  22049. }
  22050. }
  22051. _super.prototype.bind.call(this, world, mesh);
  22052. };
  22053. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22054. for (var name in this._textures) {
  22055. this._textures[name].dispose();
  22056. }
  22057. this._textures = [];
  22058. _super.prototype.dispose.call(this, forceDisposeEffect);
  22059. };
  22060. return ShaderMaterial;
  22061. })(BABYLON.Material);
  22062. BABYLON.ShaderMaterial = ShaderMaterial;
  22063. })(BABYLON || (BABYLON = {}));
  22064. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22065. (function (BABYLON) {
  22066. var VertexData = (function () {
  22067. function VertexData() {
  22068. }
  22069. VertexData.prototype.set = function (data, kind) {
  22070. switch (kind) {
  22071. case BABYLON.VertexBuffer.PositionKind:
  22072. this.positions = data;
  22073. break;
  22074. case BABYLON.VertexBuffer.NormalKind:
  22075. this.normals = data;
  22076. break;
  22077. case BABYLON.VertexBuffer.UVKind:
  22078. this.uvs = data;
  22079. break;
  22080. case BABYLON.VertexBuffer.UV2Kind:
  22081. this.uv2s = data;
  22082. break;
  22083. case BABYLON.VertexBuffer.ColorKind:
  22084. this.colors = data;
  22085. break;
  22086. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22087. this.matricesIndices = data;
  22088. break;
  22089. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22090. this.matricesWeights = data;
  22091. break;
  22092. }
  22093. };
  22094. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22095. this._applyTo(mesh, updatable);
  22096. };
  22097. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22098. this._applyTo(geometry, updatable);
  22099. };
  22100. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22101. this._update(mesh);
  22102. };
  22103. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22104. this._update(geometry);
  22105. };
  22106. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22107. if (this.positions) {
  22108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22109. }
  22110. if (this.normals) {
  22111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22112. }
  22113. if (this.uvs) {
  22114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22115. }
  22116. if (this.uv2s) {
  22117. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22118. }
  22119. if (this.colors) {
  22120. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22121. }
  22122. if (this.matricesIndices) {
  22123. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22124. }
  22125. if (this.matricesWeights) {
  22126. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22127. }
  22128. if (this.indices) {
  22129. meshOrGeometry.setIndices(this.indices);
  22130. }
  22131. };
  22132. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22133. if (this.positions) {
  22134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22135. }
  22136. if (this.normals) {
  22137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22138. }
  22139. if (this.uvs) {
  22140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22141. }
  22142. if (this.uv2s) {
  22143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22144. }
  22145. if (this.colors) {
  22146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22147. }
  22148. if (this.matricesIndices) {
  22149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22150. }
  22151. if (this.matricesWeights) {
  22152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22153. }
  22154. if (this.indices) {
  22155. meshOrGeometry.setIndices(this.indices);
  22156. }
  22157. };
  22158. VertexData.prototype.transform = function (matrix) {
  22159. var transformed = BABYLON.Vector3.Zero();
  22160. if (this.positions) {
  22161. var position = BABYLON.Vector3.Zero();
  22162. for (var index = 0; index < this.positions.length; index += 3) {
  22163. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22164. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22165. this.positions[index] = transformed.x;
  22166. this.positions[index + 1] = transformed.y;
  22167. this.positions[index + 2] = transformed.z;
  22168. }
  22169. }
  22170. if (this.normals) {
  22171. var normal = BABYLON.Vector3.Zero();
  22172. for (index = 0; index < this.normals.length; index += 3) {
  22173. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22174. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22175. this.normals[index] = transformed.x;
  22176. this.normals[index + 1] = transformed.y;
  22177. this.normals[index + 2] = transformed.z;
  22178. }
  22179. }
  22180. };
  22181. VertexData.prototype.merge = function (other) {
  22182. if (other.indices) {
  22183. if (!this.indices) {
  22184. this.indices = [];
  22185. }
  22186. var offset = this.positions ? this.positions.length / 3 : 0;
  22187. for (var index = 0; index < other.indices.length; index++) {
  22188. this.indices.push(other.indices[index] + offset);
  22189. }
  22190. }
  22191. if (other.positions) {
  22192. if (!this.positions) {
  22193. this.positions = [];
  22194. }
  22195. for (index = 0; index < other.positions.length; index++) {
  22196. this.positions.push(other.positions[index]);
  22197. }
  22198. }
  22199. if (other.normals) {
  22200. if (!this.normals) {
  22201. this.normals = [];
  22202. }
  22203. for (index = 0; index < other.normals.length; index++) {
  22204. this.normals.push(other.normals[index]);
  22205. }
  22206. }
  22207. if (other.uvs) {
  22208. if (!this.uvs) {
  22209. this.uvs = [];
  22210. }
  22211. for (index = 0; index < other.uvs.length; index++) {
  22212. this.uvs.push(other.uvs[index]);
  22213. }
  22214. }
  22215. if (other.uv2s) {
  22216. if (!this.uv2s) {
  22217. this.uv2s = [];
  22218. }
  22219. for (index = 0; index < other.uv2s.length; index++) {
  22220. this.uv2s.push(other.uv2s[index]);
  22221. }
  22222. }
  22223. if (other.matricesIndices) {
  22224. if (!this.matricesIndices) {
  22225. this.matricesIndices = [];
  22226. }
  22227. for (index = 0; index < other.matricesIndices.length; index++) {
  22228. this.matricesIndices.push(other.matricesIndices[index]);
  22229. }
  22230. }
  22231. if (other.matricesWeights) {
  22232. if (!this.matricesWeights) {
  22233. this.matricesWeights = [];
  22234. }
  22235. for (index = 0; index < other.matricesWeights.length; index++) {
  22236. this.matricesWeights.push(other.matricesWeights[index]);
  22237. }
  22238. }
  22239. if (other.colors) {
  22240. if (!this.colors) {
  22241. this.colors = [];
  22242. }
  22243. for (index = 0; index < other.colors.length; index++) {
  22244. this.colors.push(other.colors[index]);
  22245. }
  22246. }
  22247. };
  22248. // Statics
  22249. VertexData.ExtractFromMesh = function (mesh) {
  22250. return VertexData._ExtractFrom(mesh);
  22251. };
  22252. VertexData.ExtractFromGeometry = function (geometry) {
  22253. return VertexData._ExtractFrom(geometry);
  22254. };
  22255. VertexData._ExtractFrom = function (meshOrGeometry) {
  22256. var result = new VertexData();
  22257. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22258. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22259. }
  22260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22261. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22262. }
  22263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22264. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22265. }
  22266. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22267. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22268. }
  22269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22270. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22271. }
  22272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22273. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22274. }
  22275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22276. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22277. }
  22278. result.indices = meshOrGeometry.getIndices();
  22279. return result;
  22280. };
  22281. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22282. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22283. closeArray = closeArray || false;
  22284. closePath = closePath || false;
  22285. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22286. offset = offset || defaultOffset;
  22287. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22288. var positions = [];
  22289. var indices = [];
  22290. var normals = [];
  22291. var uvs = [];
  22292. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22293. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22294. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22295. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22296. var minlg; // minimal length among all paths from pathArray
  22297. var lg = []; // array of path lengths : nb of vertex per path
  22298. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22299. var p; // path iterator
  22300. var i; // point iterator
  22301. var j; // point iterator
  22302. // if single path in pathArray
  22303. if (pathArray.length < 2) {
  22304. var ar1 = [];
  22305. var ar2 = [];
  22306. for (i = 0; i < pathArray[0].length - offset; i++) {
  22307. ar1.push(pathArray[0][i]);
  22308. ar2.push(pathArray[0][i + offset]);
  22309. }
  22310. pathArray = [ar1, ar2];
  22311. }
  22312. // positions and horizontal distances (u)
  22313. var idc = 0;
  22314. minlg = pathArray[0].length;
  22315. for (p = 0; p < pathArray.length; p++) {
  22316. uTotalDistance[p] = 0;
  22317. us[p] = [0];
  22318. var path = pathArray[p];
  22319. var l = path.length;
  22320. minlg = (minlg < l) ? minlg : l;
  22321. lg[p] = l;
  22322. idx[p] = idc;
  22323. j = 0;
  22324. while (j < l) {
  22325. positions.push(path[j].x, path[j].y, path[j].z);
  22326. if (j > 0) {
  22327. var vectlg = path[j].subtract(path[j - 1]).length();
  22328. var dist = vectlg + uTotalDistance[p];
  22329. us[p].push(dist);
  22330. uTotalDistance[p] = dist;
  22331. }
  22332. j++;
  22333. }
  22334. if (closePath) {
  22335. vectlg = path[0].subtract(path[j - 1]).length();
  22336. dist = vectlg + uTotalDistance[p];
  22337. uTotalDistance[p] = dist;
  22338. }
  22339. idc += l;
  22340. }
  22341. for (i = 0; i < minlg; i++) {
  22342. vTotalDistance[i] = 0;
  22343. vs[i] = [0];
  22344. var path1;
  22345. var path2;
  22346. for (p = 0; p < pathArray.length - 1; p++) {
  22347. path1 = pathArray[p];
  22348. path2 = pathArray[p + 1];
  22349. vectlg = path2[i].subtract(path1[i]).length();
  22350. dist = vectlg + vTotalDistance[i];
  22351. vs[i].push(dist);
  22352. vTotalDistance[i] = dist;
  22353. }
  22354. if (closeArray) {
  22355. path1 = pathArray[p];
  22356. path2 = pathArray[0];
  22357. vectlg = path2[i].subtract(path1[i]).length();
  22358. dist = vectlg + vTotalDistance[i];
  22359. vTotalDistance[i] = dist;
  22360. }
  22361. }
  22362. // uvs
  22363. var u;
  22364. var v;
  22365. for (p = 0; p < pathArray.length; p++) {
  22366. for (i = 0; i < minlg; i++) {
  22367. u = us[p][i] / uTotalDistance[p];
  22368. v = vs[i][p] / vTotalDistance[i];
  22369. uvs.push(u, v);
  22370. }
  22371. }
  22372. // indices
  22373. p = 0; // path index
  22374. var pi = 0; // positions array index
  22375. var l1 = lg[p] - 1; // path1 length
  22376. var l2 = lg[p + 1] - 1; // path2 length
  22377. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22378. var shft = idx[1] - idx[0]; // shift
  22379. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22380. var t1; // two consecutive triangles, so 4 points : point1
  22381. var t2; // point2
  22382. var t3; // point3
  22383. var t4; // point4
  22384. while (pi <= min && p < path1nb) {
  22385. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  22386. t1 = pi;
  22387. t2 = pi + shft;
  22388. t3 = pi + 1;
  22389. t4 = pi + shft + 1;
  22390. indices.push(pi, pi + shft, pi + 1);
  22391. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22392. pi += 1;
  22393. if (pi === min) {
  22394. if (closePath) {
  22395. indices.push(pi, pi + shft, idx[p]);
  22396. indices.push(idx[p] + shft, idx[p], pi + shft);
  22397. t3 = idx[p];
  22398. t4 = idx[p] + shft;
  22399. }
  22400. p++;
  22401. if (p === lg.length - 1) {
  22402. shft = idx[0] - idx[p];
  22403. l1 = lg[p] - 1;
  22404. l2 = lg[0] - 1;
  22405. }
  22406. else {
  22407. shft = idx[p + 1] - idx[p];
  22408. l1 = lg[p] - 1;
  22409. l2 = lg[p + 1] - 1;
  22410. }
  22411. pi = idx[p];
  22412. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22413. }
  22414. }
  22415. // normals
  22416. VertexData.ComputeNormals(positions, indices, normals);
  22417. // sides
  22418. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22419. // Result
  22420. var vertexData = new VertexData();
  22421. vertexData.indices = indices;
  22422. vertexData.positions = positions;
  22423. vertexData.normals = normals;
  22424. vertexData.uvs = uvs;
  22425. return vertexData;
  22426. };
  22427. VertexData.CreateBox = function (size, sideOrientation) {
  22428. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22429. var normalsSource = [
  22430. new BABYLON.Vector3(0, 0, 1),
  22431. new BABYLON.Vector3(0, 0, -1),
  22432. new BABYLON.Vector3(1, 0, 0),
  22433. new BABYLON.Vector3(-1, 0, 0),
  22434. new BABYLON.Vector3(0, 1, 0),
  22435. new BABYLON.Vector3(0, -1, 0)
  22436. ];
  22437. var indices = [];
  22438. var positions = [];
  22439. var normals = [];
  22440. var uvs = [];
  22441. size = size || 1;
  22442. for (var index = 0; index < normalsSource.length; index++) {
  22443. var normal = normalsSource[index];
  22444. // Get two vectors perpendicular to the face normal and to each other.
  22445. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22446. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22447. // Six indices (two triangles) per face.
  22448. var verticesLength = positions.length / 3;
  22449. indices.push(verticesLength);
  22450. indices.push(verticesLength + 1);
  22451. indices.push(verticesLength + 2);
  22452. indices.push(verticesLength);
  22453. indices.push(verticesLength + 2);
  22454. indices.push(verticesLength + 3);
  22455. // Four vertices per face.
  22456. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22457. positions.push(vertex.x, vertex.y, vertex.z);
  22458. normals.push(normal.x, normal.y, normal.z);
  22459. uvs.push(1.0, 1.0);
  22460. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22461. positions.push(vertex.x, vertex.y, vertex.z);
  22462. normals.push(normal.x, normal.y, normal.z);
  22463. uvs.push(0.0, 1.0);
  22464. vertex = normal.add(side1).add(side2).scale(size / 2);
  22465. positions.push(vertex.x, vertex.y, vertex.z);
  22466. normals.push(normal.x, normal.y, normal.z);
  22467. uvs.push(0.0, 0.0);
  22468. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22469. positions.push(vertex.x, vertex.y, vertex.z);
  22470. normals.push(normal.x, normal.y, normal.z);
  22471. uvs.push(1.0, 0.0);
  22472. }
  22473. // sides
  22474. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22475. // Result
  22476. var vertexData = new VertexData();
  22477. vertexData.indices = indices;
  22478. vertexData.positions = positions;
  22479. vertexData.normals = normals;
  22480. vertexData.uvs = uvs;
  22481. return vertexData;
  22482. };
  22483. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22484. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22485. segments = segments || 32;
  22486. diameter = diameter || 1;
  22487. var radius = diameter / 2;
  22488. var totalZRotationSteps = 2 + segments;
  22489. var totalYRotationSteps = 2 * totalZRotationSteps;
  22490. var indices = [];
  22491. var positions = [];
  22492. var normals = [];
  22493. var uvs = [];
  22494. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22495. var normalizedZ = zRotationStep / totalZRotationSteps;
  22496. var angleZ = (normalizedZ * Math.PI);
  22497. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22498. var normalizedY = yRotationStep / totalYRotationSteps;
  22499. var angleY = normalizedY * Math.PI * 2;
  22500. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22501. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22502. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22503. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22504. var vertex = complete.scale(radius);
  22505. var normal = BABYLON.Vector3.Normalize(vertex);
  22506. positions.push(vertex.x, vertex.y, vertex.z);
  22507. normals.push(normal.x, normal.y, normal.z);
  22508. uvs.push(normalizedZ, normalizedY);
  22509. }
  22510. if (zRotationStep > 0) {
  22511. var verticesCount = positions.length / 3;
  22512. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22513. indices.push((firstIndex));
  22514. indices.push((firstIndex + 1));
  22515. indices.push(firstIndex + totalYRotationSteps + 1);
  22516. indices.push((firstIndex + totalYRotationSteps + 1));
  22517. indices.push((firstIndex + 1));
  22518. indices.push((firstIndex + totalYRotationSteps + 2));
  22519. }
  22520. }
  22521. }
  22522. // Sides
  22523. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22524. // Result
  22525. var vertexData = new VertexData();
  22526. vertexData.indices = indices;
  22527. vertexData.positions = positions;
  22528. vertexData.normals = normals;
  22529. vertexData.uvs = uvs;
  22530. return vertexData;
  22531. };
  22532. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22533. if (subdivisions === void 0) { subdivisions = 1; }
  22534. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22535. var radiusTop = diameterTop / 2;
  22536. var radiusBottom = diameterBottom / 2;
  22537. var indices = [];
  22538. var positions = [];
  22539. var normals = [];
  22540. var uvs = [];
  22541. height = height || 1;
  22542. diameterTop = diameterTop || 0.5;
  22543. diameterBottom = diameterBottom || 1;
  22544. tessellation = tessellation || 16;
  22545. subdivisions = subdivisions || 1;
  22546. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22547. var getCircleVector = function (i) {
  22548. var angle = (i * 2.0 * Math.PI / tessellation);
  22549. var dx = Math.cos(angle);
  22550. var dz = Math.sin(angle);
  22551. return new BABYLON.Vector3(dx, 0, dz);
  22552. };
  22553. var createCylinderCap = function (isTop) {
  22554. var radius = isTop ? radiusTop : radiusBottom;
  22555. if (radius === 0) {
  22556. return;
  22557. }
  22558. var vbase = positions.length / 3;
  22559. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22560. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22561. if (!isTop) {
  22562. offset.scaleInPlace(-1);
  22563. textureScale.x = -textureScale.x;
  22564. }
  22565. for (var i = 0; i < tessellation; i++) {
  22566. var circleVector = getCircleVector(i);
  22567. var position = circleVector.scale(radius).add(offset);
  22568. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22569. positions.push(position.x, position.y, position.z);
  22570. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22571. }
  22572. for (i = 0; i < tessellation - 2; i++) {
  22573. if (!isTop) {
  22574. indices.push(vbase);
  22575. indices.push(vbase + (i + 2) % tessellation);
  22576. indices.push(vbase + (i + 1) % tessellation);
  22577. }
  22578. else {
  22579. indices.push(vbase);
  22580. indices.push(vbase + (i + 1) % tessellation);
  22581. indices.push(vbase + (i + 2) % tessellation);
  22582. }
  22583. }
  22584. };
  22585. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22586. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22587. var stride = tessellation + 1;
  22588. for (var i = 0; i <= tessellation; i++) {
  22589. var circleVector = getCircleVector(i);
  22590. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22591. var position, radius = radiusBottom;
  22592. for (var s = 0; s <= subdivisions; s++) {
  22593. // Update variables
  22594. position = circleVector.scale(radius);
  22595. position.addInPlace(base.add(offset.scale(s)));
  22596. textureCoordinate.y += 1 / subdivisions;
  22597. radius += (radiusTop - radiusBottom) / subdivisions;
  22598. // Push in arrays
  22599. positions.push(position.x, position.y, position.z);
  22600. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22601. }
  22602. }
  22603. subdivisions += 1;
  22604. for (s = 0; s < subdivisions - 1; s++) {
  22605. for (i = 0; i <= tessellation; i++) {
  22606. indices.push(i * subdivisions + s);
  22607. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22608. indices.push(i * subdivisions + (s + 1));
  22609. indices.push(i * subdivisions + (s + 1));
  22610. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22611. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22612. }
  22613. }
  22614. // Create flat triangle fan caps to seal the top and bottom.
  22615. createCylinderCap(true);
  22616. createCylinderCap(false);
  22617. // Normals
  22618. VertexData.ComputeNormals(positions, indices, normals);
  22619. // Sides
  22620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22621. // Result
  22622. var vertexData = new VertexData();
  22623. vertexData.indices = indices;
  22624. vertexData.positions = positions;
  22625. vertexData.normals = normals;
  22626. vertexData.uvs = uvs;
  22627. return vertexData;
  22628. };
  22629. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22630. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22631. var indices = [];
  22632. var positions = [];
  22633. var normals = [];
  22634. var uvs = [];
  22635. diameter = diameter || 1;
  22636. thickness = thickness || 0.5;
  22637. tessellation = tessellation || 16;
  22638. var stride = tessellation + 1;
  22639. for (var i = 0; i <= tessellation; i++) {
  22640. var u = i / tessellation;
  22641. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22642. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22643. for (var j = 0; j <= tessellation; j++) {
  22644. var v = 1 - j / tessellation;
  22645. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22646. var dx = Math.cos(innerAngle);
  22647. var dy = Math.sin(innerAngle);
  22648. // Create a vertex.
  22649. var normal = new BABYLON.Vector3(dx, dy, 0);
  22650. var position = normal.scale(thickness / 2);
  22651. var textureCoordinate = new BABYLON.Vector2(u, v);
  22652. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22653. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22654. positions.push(position.x, position.y, position.z);
  22655. normals.push(normal.x, normal.y, normal.z);
  22656. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22657. // And create indices for two triangles.
  22658. var nextI = (i + 1) % stride;
  22659. var nextJ = (j + 1) % stride;
  22660. indices.push(i * stride + j);
  22661. indices.push(i * stride + nextJ);
  22662. indices.push(nextI * stride + j);
  22663. indices.push(i * stride + nextJ);
  22664. indices.push(nextI * stride + nextJ);
  22665. indices.push(nextI * stride + j);
  22666. }
  22667. }
  22668. // Sides
  22669. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22670. // Result
  22671. var vertexData = new VertexData();
  22672. vertexData.indices = indices;
  22673. vertexData.positions = positions;
  22674. vertexData.normals = normals;
  22675. vertexData.uvs = uvs;
  22676. return vertexData;
  22677. };
  22678. VertexData.CreateLines = function (points) {
  22679. var indices = [];
  22680. var positions = [];
  22681. for (var index = 0; index < points.length; index++) {
  22682. positions.push(points[index].x, points[index].y, points[index].z);
  22683. if (index > 0) {
  22684. indices.push(index - 1);
  22685. indices.push(index);
  22686. }
  22687. }
  22688. // Result
  22689. var vertexData = new VertexData();
  22690. vertexData.indices = indices;
  22691. vertexData.positions = positions;
  22692. return vertexData;
  22693. };
  22694. VertexData.CreateGround = function (width, height, subdivisions) {
  22695. var indices = [];
  22696. var positions = [];
  22697. var normals = [];
  22698. var uvs = [];
  22699. var row, col;
  22700. width = width || 1;
  22701. height = height || 1;
  22702. subdivisions = subdivisions || 1;
  22703. for (row = 0; row <= subdivisions; row++) {
  22704. for (col = 0; col <= subdivisions; col++) {
  22705. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22706. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22707. positions.push(position.x, position.y, position.z);
  22708. normals.push(normal.x, normal.y, normal.z);
  22709. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22710. }
  22711. }
  22712. for (row = 0; row < subdivisions; row++) {
  22713. for (col = 0; col < subdivisions; col++) {
  22714. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22715. indices.push(col + 1 + row * (subdivisions + 1));
  22716. indices.push(col + row * (subdivisions + 1));
  22717. indices.push(col + (row + 1) * (subdivisions + 1));
  22718. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22719. indices.push(col + row * (subdivisions + 1));
  22720. }
  22721. }
  22722. // Result
  22723. var vertexData = new VertexData();
  22724. vertexData.indices = indices;
  22725. vertexData.positions = positions;
  22726. vertexData.normals = normals;
  22727. vertexData.uvs = uvs;
  22728. return vertexData;
  22729. };
  22730. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22731. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22732. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22733. var indices = [];
  22734. var positions = [];
  22735. var normals = [];
  22736. var uvs = [];
  22737. var row, col, tileRow, tileCol;
  22738. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22739. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22740. precision.w = (precision.w < 1) ? 1 : precision.w;
  22741. precision.h = (precision.h < 1) ? 1 : precision.h;
  22742. var tileSize = {
  22743. 'w': (xmax - xmin) / subdivisions.w,
  22744. 'h': (zmax - zmin) / subdivisions.h
  22745. };
  22746. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22747. // Indices
  22748. var base = positions.length / 3;
  22749. var rowLength = precision.w + 1;
  22750. for (row = 0; row < precision.h; row++) {
  22751. for (col = 0; col < precision.w; col++) {
  22752. var square = [
  22753. base + col + row * rowLength,
  22754. base + (col + 1) + row * rowLength,
  22755. base + (col + 1) + (row + 1) * rowLength,
  22756. base + col + (row + 1) * rowLength
  22757. ];
  22758. indices.push(square[1]);
  22759. indices.push(square[2]);
  22760. indices.push(square[3]);
  22761. indices.push(square[0]);
  22762. indices.push(square[1]);
  22763. indices.push(square[3]);
  22764. }
  22765. }
  22766. // Position, normals and uvs
  22767. var position = BABYLON.Vector3.Zero();
  22768. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22769. for (row = 0; row <= precision.h; row++) {
  22770. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22771. for (col = 0; col <= precision.w; col++) {
  22772. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22773. position.y = 0;
  22774. positions.push(position.x, position.y, position.z);
  22775. normals.push(normal.x, normal.y, normal.z);
  22776. uvs.push(col / precision.w, row / precision.h);
  22777. }
  22778. }
  22779. }
  22780. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22781. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22782. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22783. }
  22784. }
  22785. // Result
  22786. var vertexData = new VertexData();
  22787. vertexData.indices = indices;
  22788. vertexData.positions = positions;
  22789. vertexData.normals = normals;
  22790. vertexData.uvs = uvs;
  22791. return vertexData;
  22792. };
  22793. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22794. var indices = [];
  22795. var positions = [];
  22796. var normals = [];
  22797. var uvs = [];
  22798. var row, col;
  22799. for (row = 0; row <= subdivisions; row++) {
  22800. for (col = 0; col <= subdivisions; col++) {
  22801. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22802. // Compute height
  22803. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22804. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22805. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22806. var r = buffer[pos] / 255.0;
  22807. var g = buffer[pos + 1] / 255.0;
  22808. var b = buffer[pos + 2] / 255.0;
  22809. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22810. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22811. // Add vertex
  22812. positions.push(position.x, position.y, position.z);
  22813. normals.push(0, 0, 0);
  22814. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22815. }
  22816. }
  22817. for (row = 0; row < subdivisions; row++) {
  22818. for (col = 0; col < subdivisions; col++) {
  22819. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22820. indices.push(col + 1 + row * (subdivisions + 1));
  22821. indices.push(col + row * (subdivisions + 1));
  22822. indices.push(col + (row + 1) * (subdivisions + 1));
  22823. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22824. indices.push(col + row * (subdivisions + 1));
  22825. }
  22826. }
  22827. // Normals
  22828. VertexData.ComputeNormals(positions, indices, normals);
  22829. // Result
  22830. var vertexData = new VertexData();
  22831. vertexData.indices = indices;
  22832. vertexData.positions = positions;
  22833. vertexData.normals = normals;
  22834. vertexData.uvs = uvs;
  22835. return vertexData;
  22836. };
  22837. VertexData.CreatePlane = function (size, sideOrientation) {
  22838. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22839. var indices = [];
  22840. var positions = [];
  22841. var normals = [];
  22842. var uvs = [];
  22843. size = size || 1;
  22844. // Vertices
  22845. var halfSize = size / 2.0;
  22846. positions.push(-halfSize, -halfSize, 0);
  22847. normals.push(0, 0, -1.0);
  22848. uvs.push(0.0, 0.0);
  22849. positions.push(halfSize, -halfSize, 0);
  22850. normals.push(0, 0, -1.0);
  22851. uvs.push(1.0, 0.0);
  22852. positions.push(halfSize, halfSize, 0);
  22853. normals.push(0, 0, -1.0);
  22854. uvs.push(1.0, 1.0);
  22855. positions.push(-halfSize, halfSize, 0);
  22856. normals.push(0, 0, -1.0);
  22857. uvs.push(0.0, 1.0);
  22858. // Indices
  22859. indices.push(0);
  22860. indices.push(1);
  22861. indices.push(2);
  22862. indices.push(0);
  22863. indices.push(2);
  22864. indices.push(3);
  22865. // Sides
  22866. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22867. // Result
  22868. var vertexData = new VertexData();
  22869. vertexData.indices = indices;
  22870. vertexData.positions = positions;
  22871. vertexData.normals = normals;
  22872. vertexData.uvs = uvs;
  22873. return vertexData;
  22874. };
  22875. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22876. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22877. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22878. var indices = [];
  22879. var positions = [];
  22880. var normals = [];
  22881. var uvs = [];
  22882. radius = radius || 2;
  22883. tube = tube || 0.5;
  22884. radialSegments = radialSegments || 32;
  22885. tubularSegments = tubularSegments || 32;
  22886. p = p || 2;
  22887. q = q || 3;
  22888. // Helper
  22889. var getPos = function (angle) {
  22890. var cu = Math.cos(angle);
  22891. var su = Math.sin(angle);
  22892. var quOverP = q / p * angle;
  22893. var cs = Math.cos(quOverP);
  22894. var tx = radius * (2 + cs) * 0.5 * cu;
  22895. var ty = radius * (2 + cs) * su * 0.5;
  22896. var tz = radius * Math.sin(quOverP) * 0.5;
  22897. return new BABYLON.Vector3(tx, ty, tz);
  22898. };
  22899. for (var i = 0; i <= radialSegments; i++) {
  22900. var modI = i % radialSegments;
  22901. var u = modI / radialSegments * 2 * p * Math.PI;
  22902. var p1 = getPos(u);
  22903. var p2 = getPos(u + 0.01);
  22904. var tang = p2.subtract(p1);
  22905. var n = p2.add(p1);
  22906. var bitan = BABYLON.Vector3.Cross(tang, n);
  22907. n = BABYLON.Vector3.Cross(bitan, tang);
  22908. bitan.normalize();
  22909. n.normalize();
  22910. for (var j = 0; j < tubularSegments; j++) {
  22911. var modJ = j % tubularSegments;
  22912. var v = modJ / tubularSegments * 2 * Math.PI;
  22913. var cx = -tube * Math.cos(v);
  22914. var cy = tube * Math.sin(v);
  22915. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22916. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22917. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22918. uvs.push(i / radialSegments);
  22919. uvs.push(j / tubularSegments);
  22920. }
  22921. }
  22922. for (i = 0; i < radialSegments; i++) {
  22923. for (j = 0; j < tubularSegments; j++) {
  22924. var jNext = (j + 1) % tubularSegments;
  22925. var a = i * tubularSegments + j;
  22926. var b = (i + 1) * tubularSegments + j;
  22927. var c = (i + 1) * tubularSegments + jNext;
  22928. var d = i * tubularSegments + jNext;
  22929. indices.push(d);
  22930. indices.push(b);
  22931. indices.push(a);
  22932. indices.push(d);
  22933. indices.push(c);
  22934. indices.push(b);
  22935. }
  22936. }
  22937. // Normals
  22938. VertexData.ComputeNormals(positions, indices, normals);
  22939. // Sides
  22940. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22941. // Result
  22942. var vertexData = new VertexData();
  22943. vertexData.indices = indices;
  22944. vertexData.positions = positions;
  22945. vertexData.normals = normals;
  22946. vertexData.uvs = uvs;
  22947. return vertexData;
  22948. };
  22949. // Tools
  22950. /**
  22951. * @param {any} - positions (number[] or Float32Array)
  22952. * @param {any} - indices (number[] or Uint16Array)
  22953. * @param {any} - normals (number[] or Float32Array)
  22954. */
  22955. VertexData.ComputeNormals = function (positions, indices, normals) {
  22956. var positionVectors = [];
  22957. var facesOfVertices = [];
  22958. var index;
  22959. for (index = 0; index < positions.length; index += 3) {
  22960. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22961. positionVectors.push(vector3);
  22962. facesOfVertices.push([]);
  22963. }
  22964. // Compute normals
  22965. var facesNormals = [];
  22966. for (index = 0; index < indices.length / 3; index++) {
  22967. var i1 = indices[index * 3];
  22968. var i2 = indices[index * 3 + 1];
  22969. var i3 = indices[index * 3 + 2];
  22970. var p1 = positionVectors[i1];
  22971. var p2 = positionVectors[i2];
  22972. var p3 = positionVectors[i3];
  22973. var p1p2 = p1.subtract(p2);
  22974. var p3p2 = p3.subtract(p2);
  22975. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22976. facesOfVertices[i1].push(index);
  22977. facesOfVertices[i2].push(index);
  22978. facesOfVertices[i3].push(index);
  22979. }
  22980. for (index = 0; index < positionVectors.length; index++) {
  22981. var faces = facesOfVertices[index];
  22982. var normal = BABYLON.Vector3.Zero();
  22983. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22984. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22985. }
  22986. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22987. normals[index * 3] = normal.x;
  22988. normals[index * 3 + 1] = normal.y;
  22989. normals[index * 3 + 2] = normal.z;
  22990. }
  22991. };
  22992. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22993. var li = indices.length;
  22994. var ln = normals.length;
  22995. var i;
  22996. var n;
  22997. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22998. switch (sideOrientation) {
  22999. case BABYLON.Mesh.FRONTSIDE:
  23000. break;
  23001. case BABYLON.Mesh.BACKSIDE:
  23002. var tmp;
  23003. for (i = 0; i < li; i += 3) {
  23004. tmp = indices[i];
  23005. indices[i] = indices[i + 2];
  23006. indices[i + 2] = tmp;
  23007. }
  23008. for (n = 0; n < ln; n++) {
  23009. normals[n] = -normals[n];
  23010. }
  23011. break;
  23012. case BABYLON.Mesh.DOUBLESIDE:
  23013. // positions
  23014. var lp = positions.length;
  23015. var l = lp / 3;
  23016. for (var p = 0; p < lp; p++) {
  23017. positions[lp + p] = positions[p];
  23018. }
  23019. for (i = 0; i < li; i += 3) {
  23020. indices[i + li] = indices[i + 2] + l;
  23021. indices[i + 1 + li] = indices[i + 1] + l;
  23022. indices[i + 2 + li] = indices[i] + l;
  23023. }
  23024. for (n = 0; n < ln; n++) {
  23025. normals[ln + n] = -normals[n];
  23026. }
  23027. // uvs
  23028. var lu = uvs.length;
  23029. for (var u = 0; u < lu; u++) {
  23030. uvs[u + lu] = uvs[u];
  23031. }
  23032. break;
  23033. }
  23034. };
  23035. return VertexData;
  23036. })();
  23037. BABYLON.VertexData = VertexData;
  23038. })(BABYLON || (BABYLON = {}));
  23039. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23040. var BABYLON;
  23041. (function (BABYLON) {
  23042. var buildCamera = function (that, name) {
  23043. that._leftCamera.isIntermediate = true;
  23044. that.subCameras.push(that._leftCamera);
  23045. that.subCameras.push(that._rightCamera);
  23046. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23047. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23048. that._anaglyphPostProcess.onApply = function (effect) {
  23049. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23050. };
  23051. that._update();
  23052. };
  23053. var AnaglyphArcRotateCamera = (function (_super) {
  23054. __extends(AnaglyphArcRotateCamera, _super);
  23055. // ANY
  23056. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23057. _super.call(this, name, alpha, beta, radius, target, scene);
  23058. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23059. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23060. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23061. buildCamera(this, name);
  23062. }
  23063. AnaglyphArcRotateCamera.prototype._update = function () {
  23064. this._updateCamera(this._leftCamera);
  23065. this._updateCamera(this._rightCamera);
  23066. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23067. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23068. _super.prototype._update.call(this);
  23069. };
  23070. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23071. camera.beta = this.beta;
  23072. camera.radius = this.radius;
  23073. camera.minZ = this.minZ;
  23074. camera.maxZ = this.maxZ;
  23075. camera.fov = this.fov;
  23076. camera.target = this.target;
  23077. };
  23078. return AnaglyphArcRotateCamera;
  23079. })(BABYLON.ArcRotateCamera);
  23080. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23081. var AnaglyphFreeCamera = (function (_super) {
  23082. __extends(AnaglyphFreeCamera, _super);
  23083. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23084. _super.call(this, name, position, scene);
  23085. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23086. this._transformMatrix = new BABYLON.Matrix();
  23087. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23088. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23089. buildCamera(this, name);
  23090. }
  23091. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23092. var target = this.getTarget();
  23093. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23094. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23095. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23096. };
  23097. AnaglyphFreeCamera.prototype._update = function () {
  23098. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23099. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23100. this._updateCamera(this._leftCamera);
  23101. this._updateCamera(this._rightCamera);
  23102. _super.prototype._update.call(this);
  23103. };
  23104. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23105. camera.minZ = this.minZ;
  23106. camera.maxZ = this.maxZ;
  23107. camera.fov = this.fov;
  23108. camera.viewport = this.viewport;
  23109. camera.setTarget(this.getTarget());
  23110. };
  23111. return AnaglyphFreeCamera;
  23112. })(BABYLON.FreeCamera);
  23113. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23114. })(BABYLON || (BABYLON = {}));
  23115. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23116. var BABYLON;
  23117. (function (BABYLON) {
  23118. var AnaglyphPostProcess = (function (_super) {
  23119. __extends(AnaglyphPostProcess, _super);
  23120. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23121. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23122. }
  23123. return AnaglyphPostProcess;
  23124. })(BABYLON.PostProcess);
  23125. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23126. })(BABYLON || (BABYLON = {}));
  23127. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23128. (function (BABYLON) {
  23129. var Tags = (function () {
  23130. function Tags() {
  23131. }
  23132. Tags.EnableFor = function (obj) {
  23133. obj._tags = obj._tags || {};
  23134. obj.hasTags = function () {
  23135. return Tags.HasTags(obj);
  23136. };
  23137. obj.addTags = function (tagsString) {
  23138. return Tags.AddTagsTo(obj, tagsString);
  23139. };
  23140. obj.removeTags = function (tagsString) {
  23141. return Tags.RemoveTagsFrom(obj, tagsString);
  23142. };
  23143. obj.matchesTagsQuery = function (tagsQuery) {
  23144. return Tags.MatchesQuery(obj, tagsQuery);
  23145. };
  23146. };
  23147. Tags.DisableFor = function (obj) {
  23148. delete obj._tags;
  23149. delete obj.hasTags;
  23150. delete obj.addTags;
  23151. delete obj.removeTags;
  23152. delete obj.matchesTagsQuery;
  23153. };
  23154. Tags.HasTags = function (obj) {
  23155. if (!obj._tags) {
  23156. return false;
  23157. }
  23158. return !BABYLON.Tools.IsEmpty(obj._tags);
  23159. };
  23160. Tags.GetTags = function (obj) {
  23161. if (!obj._tags) {
  23162. return null;
  23163. }
  23164. return obj._tags;
  23165. };
  23166. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23167. // a tag cannot start with '||', '&&', and '!'
  23168. // it cannot contain whitespaces
  23169. Tags.AddTagsTo = function (obj, tagsString) {
  23170. if (!tagsString) {
  23171. return;
  23172. }
  23173. var tags = tagsString.split(" ");
  23174. for (var t in tags) {
  23175. Tags._AddTagTo(obj, tags[t]);
  23176. }
  23177. };
  23178. Tags._AddTagTo = function (obj, tag) {
  23179. tag = tag.trim();
  23180. if (tag === "" || tag === "true" || tag === "false") {
  23181. return;
  23182. }
  23183. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23184. return;
  23185. }
  23186. Tags.EnableFor(obj);
  23187. obj._tags[tag] = true;
  23188. };
  23189. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23190. if (!Tags.HasTags(obj)) {
  23191. return;
  23192. }
  23193. var tags = tagsString.split(" ");
  23194. for (var t in tags) {
  23195. Tags._RemoveTagFrom(obj, tags[t]);
  23196. }
  23197. };
  23198. Tags._RemoveTagFrom = function (obj, tag) {
  23199. delete obj._tags[tag];
  23200. };
  23201. Tags.MatchesQuery = function (obj, tagsQuery) {
  23202. if (tagsQuery === undefined) {
  23203. return true;
  23204. }
  23205. if (tagsQuery === "") {
  23206. return Tags.HasTags(obj);
  23207. }
  23208. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23209. };
  23210. return Tags;
  23211. })();
  23212. BABYLON.Tags = Tags;
  23213. })(BABYLON || (BABYLON = {}));
  23214. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23215. (function (BABYLON) {
  23216. var Internals;
  23217. (function (Internals) {
  23218. var AndOrNotEvaluator = (function () {
  23219. function AndOrNotEvaluator() {
  23220. }
  23221. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23222. if (!query.match(/\([^\(\)]*\)/g)) {
  23223. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23224. }
  23225. else {
  23226. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23227. // remove parenthesis
  23228. r = r.slice(1, r.length - 1);
  23229. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23230. });
  23231. }
  23232. if (query === "true") {
  23233. return true;
  23234. }
  23235. if (query === "false") {
  23236. return false;
  23237. }
  23238. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23239. };
  23240. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23241. evaluateCallback = evaluateCallback || (function (r) {
  23242. return r === "true" ? true : false;
  23243. });
  23244. var result;
  23245. var or = parenthesisContent.split("||");
  23246. for (var i in or) {
  23247. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23248. var and = ori.split("&&");
  23249. if (and.length > 1) {
  23250. for (var j = 0; j < and.length; ++j) {
  23251. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23252. if (andj !== "true" && andj !== "false") {
  23253. if (andj[0] === "!") {
  23254. result = !evaluateCallback(andj.substring(1));
  23255. }
  23256. else {
  23257. result = evaluateCallback(andj);
  23258. }
  23259. }
  23260. else {
  23261. result = andj === "true" ? true : false;
  23262. }
  23263. if (!result) {
  23264. ori = "false";
  23265. break;
  23266. }
  23267. }
  23268. }
  23269. if (result || ori === "true") {
  23270. result = true;
  23271. break;
  23272. }
  23273. // result equals false (or undefined)
  23274. if (ori !== "true" && ori !== "false") {
  23275. if (ori[0] === "!") {
  23276. result = !evaluateCallback(ori.substring(1));
  23277. }
  23278. else {
  23279. result = evaluateCallback(ori);
  23280. }
  23281. }
  23282. else {
  23283. result = ori === "true" ? true : false;
  23284. }
  23285. }
  23286. // the whole parenthesis scope is replaced by 'true' or 'false'
  23287. return result ? "true" : "false";
  23288. };
  23289. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23290. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23291. // remove whitespaces
  23292. r = r.replace(/[\s]/g, function () { return ""; });
  23293. return r.length % 2 ? "!" : "";
  23294. });
  23295. booleanString = booleanString.trim();
  23296. if (booleanString === "!true") {
  23297. booleanString = "false";
  23298. }
  23299. else if (booleanString === "!false") {
  23300. booleanString = "true";
  23301. }
  23302. return booleanString;
  23303. };
  23304. return AndOrNotEvaluator;
  23305. })();
  23306. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23308. })(BABYLON || (BABYLON = {}));
  23309. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23310. (function (BABYLON) {
  23311. var PostProcessRenderPass = (function () {
  23312. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23313. this._enabled = true;
  23314. this._refCount = 0;
  23315. this._name = name;
  23316. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23317. this.setRenderList(renderList);
  23318. this._renderTexture.onBeforeRender = beforeRender;
  23319. this._renderTexture.onAfterRender = afterRender;
  23320. this._scene = scene;
  23321. this._renderList = renderList;
  23322. }
  23323. // private
  23324. PostProcessRenderPass.prototype._incRefCount = function () {
  23325. if (this._refCount === 0) {
  23326. this._scene.customRenderTargets.push(this._renderTexture);
  23327. }
  23328. return ++this._refCount;
  23329. };
  23330. PostProcessRenderPass.prototype._decRefCount = function () {
  23331. this._refCount--;
  23332. if (this._refCount <= 0) {
  23333. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23334. }
  23335. return this._refCount;
  23336. };
  23337. PostProcessRenderPass.prototype._update = function () {
  23338. this.setRenderList(this._renderList);
  23339. };
  23340. // public
  23341. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23342. this._renderTexture.renderList = renderList;
  23343. };
  23344. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23345. return this._renderTexture;
  23346. };
  23347. return PostProcessRenderPass;
  23348. })();
  23349. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23350. })(BABYLON || (BABYLON = {}));
  23351. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23352. (function (BABYLON) {
  23353. var PostProcessRenderEffect = (function () {
  23354. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23355. this._engine = engine;
  23356. this._name = name;
  23357. this._singleInstance = singleInstance || true;
  23358. this._getPostProcess = getPostProcess;
  23359. this._cameras = [];
  23360. this._indicesForCamera = [];
  23361. this._postProcesses = {};
  23362. this._renderPasses = {};
  23363. this._renderEffectAsPasses = {};
  23364. }
  23365. PostProcessRenderEffect.prototype._update = function () {
  23366. for (var renderPassName in this._renderPasses) {
  23367. this._renderPasses[renderPassName]._update();
  23368. }
  23369. };
  23370. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23371. this._renderPasses[renderPass._name] = renderPass;
  23372. this._linkParameters();
  23373. };
  23374. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23375. delete this._renderPasses[renderPass._name];
  23376. this._linkParameters();
  23377. };
  23378. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23379. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23380. this._linkParameters();
  23381. };
  23382. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23383. for (var renderPassName in this._renderPasses) {
  23384. if (renderPassName === passName) {
  23385. return this._renderPasses[passName];
  23386. }
  23387. }
  23388. };
  23389. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23390. this._renderPasses = {};
  23391. this._linkParameters();
  23392. };
  23393. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23394. var cameraKey;
  23395. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23396. for (var i = 0; i < _cam.length; i++) {
  23397. var camera = _cam[i];
  23398. var cameraName = camera.name;
  23399. if (this._singleInstance) {
  23400. cameraKey = 0;
  23401. }
  23402. else {
  23403. cameraKey = cameraName;
  23404. }
  23405. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23406. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23407. if (!this._indicesForCamera[cameraName]) {
  23408. this._indicesForCamera[cameraName] = [];
  23409. }
  23410. this._indicesForCamera[cameraName].push(index);
  23411. if (this._cameras.indexOf(camera) === -1) {
  23412. this._cameras[cameraName] = camera;
  23413. }
  23414. for (var passName in this._renderPasses) {
  23415. this._renderPasses[passName]._incRefCount();
  23416. }
  23417. }
  23418. this._linkParameters();
  23419. };
  23420. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23421. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23422. for (var i = 0; i < _cam.length; i++) {
  23423. var camera = _cam[i];
  23424. var cameraName = camera.name;
  23425. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23426. var index = this._cameras.indexOf(cameraName);
  23427. this._indicesForCamera.splice(index, 1);
  23428. this._cameras.splice(index, 1);
  23429. for (var passName in this._renderPasses) {
  23430. this._renderPasses[passName]._decRefCount();
  23431. }
  23432. }
  23433. };
  23434. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23435. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23436. for (var i = 0; i < _cam.length; i++) {
  23437. var camera = _cam[i];
  23438. var cameraName = camera.name;
  23439. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23440. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23441. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23442. }
  23443. }
  23444. for (var passName in this._renderPasses) {
  23445. this._renderPasses[passName]._incRefCount();
  23446. }
  23447. }
  23448. };
  23449. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23450. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23451. for (var i = 0; i < _cam.length; i++) {
  23452. var camera = _cam[i];
  23453. var cameraName = camera.Name;
  23454. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23455. for (var passName in this._renderPasses) {
  23456. this._renderPasses[passName]._decRefCount();
  23457. }
  23458. }
  23459. };
  23460. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23461. if (this._singleInstance) {
  23462. return this._postProcesses[0];
  23463. }
  23464. else {
  23465. return this._postProcesses[camera.name];
  23466. }
  23467. };
  23468. PostProcessRenderEffect.prototype._linkParameters = function () {
  23469. var _this = this;
  23470. for (var index in this._postProcesses) {
  23471. if (this.applyParameters) {
  23472. this.applyParameters(this._postProcesses[index]);
  23473. }
  23474. this._postProcesses[index].onBeforeRender = function (effect) {
  23475. _this._linkTextures(effect);
  23476. };
  23477. }
  23478. };
  23479. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23480. for (var renderPassName in this._renderPasses) {
  23481. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23482. }
  23483. for (var renderEffectName in this._renderEffectAsPasses) {
  23484. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23485. }
  23486. };
  23487. return PostProcessRenderEffect;
  23488. })();
  23489. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23490. })(BABYLON || (BABYLON = {}));
  23491. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23492. (function (BABYLON) {
  23493. var PostProcessRenderPipeline = (function () {
  23494. function PostProcessRenderPipeline(engine, name) {
  23495. this._engine = engine;
  23496. this._name = name;
  23497. this._renderEffects = {};
  23498. this._renderEffectsForIsolatedPass = {};
  23499. this._cameras = [];
  23500. }
  23501. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23502. this._renderEffects[renderEffect._name] = renderEffect;
  23503. };
  23504. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23505. var renderEffects = this._renderEffects[renderEffectName];
  23506. if (!renderEffects) {
  23507. return;
  23508. }
  23509. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23510. };
  23511. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23512. var renderEffects = this._renderEffects[renderEffectName];
  23513. if (!renderEffects) {
  23514. return;
  23515. }
  23516. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23517. };
  23518. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23519. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23520. var indicesToDelete = [];
  23521. for (var i = 0; i < _cam.length; i++) {
  23522. var camera = _cam[i];
  23523. var cameraName = camera.name;
  23524. if (this._cameras.indexOf(camera) === -1) {
  23525. this._cameras[cameraName] = camera;
  23526. }
  23527. else if (unique) {
  23528. indicesToDelete.push(i);
  23529. }
  23530. }
  23531. for (var i = 0; i < indicesToDelete.length; i++) {
  23532. cameras.splice(indicesToDelete[i], 1);
  23533. }
  23534. for (var renderEffectName in this._renderEffects) {
  23535. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23536. }
  23537. };
  23538. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23539. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23540. for (var renderEffectName in this._renderEffects) {
  23541. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23542. }
  23543. for (var i = 0; i < _cam.length; i++) {
  23544. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23545. }
  23546. };
  23547. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23548. var _this = this;
  23549. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23550. var pass = null;
  23551. for (var renderEffectName in this._renderEffects) {
  23552. pass = this._renderEffects[renderEffectName].getPass(passName);
  23553. if (pass != null) {
  23554. break;
  23555. }
  23556. }
  23557. if (pass === null) {
  23558. return;
  23559. }
  23560. for (var renderEffectName in this._renderEffects) {
  23561. this._renderEffects[renderEffectName]._disable(_cam);
  23562. }
  23563. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23564. for (var i = 0; i < _cam.length; i++) {
  23565. var camera = _cam[i];
  23566. var cameraName = camera.name;
  23567. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23568. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23569. });
  23570. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23571. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23572. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23573. }
  23574. };
  23575. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23576. var _this = this;
  23577. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23578. for (var i = 0; i < _cam.length; i++) {
  23579. var camera = _cam[i];
  23580. var cameraName = camera.name;
  23581. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23582. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23583. });
  23584. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23585. }
  23586. for (var renderEffectName in this._renderEffects) {
  23587. this._renderEffects[renderEffectName]._enable(_cam);
  23588. }
  23589. };
  23590. PostProcessRenderPipeline.prototype._update = function () {
  23591. for (var renderEffectName in this._renderEffects) {
  23592. this._renderEffects[renderEffectName]._update();
  23593. }
  23594. for (var i = 0; i < this._cameras.length; i++) {
  23595. var cameraName = this._cameras[i].name;
  23596. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23597. this._renderEffectsForIsolatedPass[cameraName]._update();
  23598. }
  23599. }
  23600. };
  23601. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23602. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23603. return PostProcessRenderPipeline;
  23604. })();
  23605. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23606. })(BABYLON || (BABYLON = {}));
  23607. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23608. (function (BABYLON) {
  23609. var PostProcessRenderPipelineManager = (function () {
  23610. function PostProcessRenderPipelineManager() {
  23611. this._renderPipelines = {};
  23612. }
  23613. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23614. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23615. };
  23616. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23617. var renderPipeline = this._renderPipelines[renderPipelineName];
  23618. if (!renderPipeline) {
  23619. return;
  23620. }
  23621. renderPipeline._attachCameras(cameras, unique);
  23622. };
  23623. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23624. var renderPipeline = this._renderPipelines[renderPipelineName];
  23625. if (!renderPipeline) {
  23626. return;
  23627. }
  23628. renderPipeline._detachCameras(cameras);
  23629. };
  23630. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23631. var renderPipeline = this._renderPipelines[renderPipelineName];
  23632. if (!renderPipeline) {
  23633. return;
  23634. }
  23635. renderPipeline._enableEffect(renderEffectName, cameras);
  23636. };
  23637. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23638. var renderPipeline = this._renderPipelines[renderPipelineName];
  23639. if (!renderPipeline) {
  23640. return;
  23641. }
  23642. renderPipeline._disableEffect(renderEffectName, cameras);
  23643. };
  23644. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23645. var renderPipeline = this._renderPipelines[renderPipelineName];
  23646. if (!renderPipeline) {
  23647. return;
  23648. }
  23649. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23650. };
  23651. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23652. var renderPipeline = this._renderPipelines[renderPipelineName];
  23653. if (!renderPipeline) {
  23654. return;
  23655. }
  23656. renderPipeline._disableDisplayOnlyPass(cameras);
  23657. };
  23658. PostProcessRenderPipelineManager.prototype.update = function () {
  23659. for (var renderPipelineName in this._renderPipelines) {
  23660. this._renderPipelines[renderPipelineName]._update();
  23661. }
  23662. };
  23663. return PostProcessRenderPipelineManager;
  23664. })();
  23665. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23666. })(BABYLON || (BABYLON = {}));
  23667. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23668. var BABYLON;
  23669. (function (BABYLON) {
  23670. var DisplayPassPostProcess = (function (_super) {
  23671. __extends(DisplayPassPostProcess, _super);
  23672. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23673. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23674. }
  23675. return DisplayPassPostProcess;
  23676. })(BABYLON.PostProcess);
  23677. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23678. })(BABYLON || (BABYLON = {}));
  23679. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23680. (function (BABYLON) {
  23681. var BoundingBoxRenderer = (function () {
  23682. function BoundingBoxRenderer(scene) {
  23683. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23684. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23685. this.showBackLines = true;
  23686. this.renderList = new BABYLON.SmartArray(32);
  23687. this._scene = scene;
  23688. }
  23689. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23690. if (this._colorShader) {
  23691. return;
  23692. }
  23693. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23694. attributes: ["position"],
  23695. uniforms: ["worldViewProjection", "color"]
  23696. });
  23697. var engine = this._scene.getEngine();
  23698. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23699. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23700. 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]);
  23701. };
  23702. BoundingBoxRenderer.prototype.reset = function () {
  23703. this.renderList.reset();
  23704. };
  23705. BoundingBoxRenderer.prototype.render = function () {
  23706. if (this.renderList.length === 0) {
  23707. return;
  23708. }
  23709. this._prepareRessources();
  23710. if (!this._colorShader.isReady()) {
  23711. return;
  23712. }
  23713. var engine = this._scene.getEngine();
  23714. engine.setDepthWrite(false);
  23715. this._colorShader._preBind();
  23716. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23717. var boundingBox = this.renderList.data[boundingBoxIndex];
  23718. var min = boundingBox.minimum;
  23719. var max = boundingBox.maximum;
  23720. var diff = max.subtract(min);
  23721. var median = min.add(diff.scale(0.5));
  23722. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23723. // VBOs
  23724. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23725. if (this.showBackLines) {
  23726. // Back
  23727. engine.setDepthFunctionToGreaterOrEqual();
  23728. this._scene.resetCachedMaterial();
  23729. this._colorShader.setColor4("color", this.backColor.toColor4());
  23730. this._colorShader.bind(worldMatrix);
  23731. // Draw order
  23732. engine.draw(false, 0, 24);
  23733. }
  23734. // Front
  23735. engine.setDepthFunctionToLess();
  23736. this._scene.resetCachedMaterial();
  23737. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23738. this._colorShader.bind(worldMatrix);
  23739. // Draw order
  23740. engine.draw(false, 0, 24);
  23741. }
  23742. this._colorShader.unbind();
  23743. engine.setDepthFunctionToLessOrEqual();
  23744. engine.setDepthWrite(true);
  23745. };
  23746. BoundingBoxRenderer.prototype.dispose = function () {
  23747. if (!this._colorShader) {
  23748. return;
  23749. }
  23750. this._colorShader.dispose();
  23751. this._vb.dispose();
  23752. this._scene.getEngine()._releaseBuffer(this._ib);
  23753. };
  23754. return BoundingBoxRenderer;
  23755. })();
  23756. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23757. })(BABYLON || (BABYLON = {}));
  23758. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23759. (function (BABYLON) {
  23760. var Internals;
  23761. (function (Internals) {
  23762. /*
  23763. * Based on jsTGALoader - Javascript loader for TGA file
  23764. * By Vincent Thibault
  23765. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23766. */
  23767. var TGATools = (function () {
  23768. function TGATools() {
  23769. }
  23770. TGATools.GetTGAHeader = function (data) {
  23771. var offset = 0;
  23772. var header = {
  23773. id_length: data[offset++],
  23774. colormap_type: data[offset++],
  23775. image_type: data[offset++],
  23776. colormap_index: data[offset++] | data[offset++] << 8,
  23777. colormap_length: data[offset++] | data[offset++] << 8,
  23778. colormap_size: data[offset++],
  23779. origin: [
  23780. data[offset++] | data[offset++] << 8,
  23781. data[offset++] | data[offset++] << 8
  23782. ],
  23783. width: data[offset++] | data[offset++] << 8,
  23784. height: data[offset++] | data[offset++] << 8,
  23785. pixel_size: data[offset++],
  23786. flags: data[offset++]
  23787. };
  23788. return header;
  23789. };
  23790. TGATools.UploadContent = function (gl, data) {
  23791. // Not enough data to contain header ?
  23792. if (data.length < 19) {
  23793. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23794. return;
  23795. }
  23796. // Read Header
  23797. var offset = 18;
  23798. var header = TGATools.GetTGAHeader(data);
  23799. // Assume it's a valid Targa file.
  23800. if (header.id_length + offset > data.length) {
  23801. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23802. return;
  23803. }
  23804. // Skip not needed data
  23805. offset += header.id_length;
  23806. var use_rle = false;
  23807. var use_pal = false;
  23808. var use_rgb = false;
  23809. var use_grey = false;
  23810. switch (header.image_type) {
  23811. case TGATools._TYPE_RLE_INDEXED:
  23812. use_rle = true;
  23813. case TGATools._TYPE_INDEXED:
  23814. use_pal = true;
  23815. break;
  23816. case TGATools._TYPE_RLE_RGB:
  23817. use_rle = true;
  23818. case TGATools._TYPE_RGB:
  23819. use_rgb = true;
  23820. break;
  23821. case TGATools._TYPE_RLE_GREY:
  23822. use_rle = true;
  23823. case TGATools._TYPE_GREY:
  23824. use_grey = true;
  23825. break;
  23826. }
  23827. var pixel_data;
  23828. var numAlphaBits = header.flags & 0xf;
  23829. var pixel_size = header.pixel_size >> 3;
  23830. var pixel_total = header.width * header.height * pixel_size;
  23831. // Read palettes
  23832. var palettes;
  23833. if (use_pal) {
  23834. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23835. }
  23836. // Read LRE
  23837. if (use_rle) {
  23838. pixel_data = new Uint8Array(pixel_total);
  23839. var c, count, i;
  23840. var localOffset = 0;
  23841. var pixels = new Uint8Array(pixel_size);
  23842. while (offset < pixel_total && localOffset < pixel_total) {
  23843. c = data[offset++];
  23844. count = (c & 0x7f) + 1;
  23845. // RLE pixels
  23846. if (c & 0x80) {
  23847. for (i = 0; i < pixel_size; ++i) {
  23848. pixels[i] = data[offset++];
  23849. }
  23850. for (i = 0; i < count; ++i) {
  23851. pixel_data.set(pixels, localOffset + i * pixel_size);
  23852. }
  23853. localOffset += pixel_size * count;
  23854. }
  23855. else {
  23856. count *= pixel_size;
  23857. for (i = 0; i < count; ++i) {
  23858. pixel_data[localOffset + i] = data[offset++];
  23859. }
  23860. localOffset += count;
  23861. }
  23862. }
  23863. }
  23864. else {
  23865. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23866. }
  23867. // Load to texture
  23868. var x_start, y_start, x_step, y_step, y_end, x_end;
  23869. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23870. default:
  23871. case TGATools._ORIGIN_UL:
  23872. x_start = 0;
  23873. x_step = 1;
  23874. x_end = header.width;
  23875. y_start = 0;
  23876. y_step = 1;
  23877. y_end = header.height;
  23878. break;
  23879. case TGATools._ORIGIN_BL:
  23880. x_start = 0;
  23881. x_step = 1;
  23882. x_end = header.width;
  23883. y_start = header.height - 1;
  23884. y_step = -1;
  23885. y_end = -1;
  23886. break;
  23887. case TGATools._ORIGIN_UR:
  23888. x_start = header.width - 1;
  23889. x_step = -1;
  23890. x_end = -1;
  23891. y_start = 0;
  23892. y_step = 1;
  23893. y_end = header.height;
  23894. break;
  23895. case TGATools._ORIGIN_BR:
  23896. x_start = header.width - 1;
  23897. x_step = -1;
  23898. x_end = -1;
  23899. y_start = header.height - 1;
  23900. y_step = -1;
  23901. y_end = -1;
  23902. break;
  23903. }
  23904. // Load the specify method
  23905. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23906. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23907. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23908. };
  23909. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23910. var image = pixel_data, colormap = palettes;
  23911. var width = header.width, height = header.height;
  23912. var color, i = 0, x, y;
  23913. var imageData = new Uint8Array(width * height * 4);
  23914. for (y = y_start; y !== y_end; y += y_step) {
  23915. for (x = x_start; x !== x_end; x += x_step, i++) {
  23916. color = image[i];
  23917. imageData[(x + width * y) * 4 + 3] = 255;
  23918. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23919. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23920. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23921. }
  23922. }
  23923. return imageData;
  23924. };
  23925. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23926. var image = pixel_data;
  23927. var width = header.width, height = header.height;
  23928. var color, i = 0, x, y;
  23929. var imageData = new Uint8Array(width * height * 4);
  23930. for (y = y_start; y !== y_end; y += y_step) {
  23931. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23932. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23933. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23934. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23935. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23936. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23937. }
  23938. }
  23939. return imageData;
  23940. };
  23941. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23942. var image = pixel_data;
  23943. var width = header.width, height = header.height;
  23944. var i = 0, x, y;
  23945. var imageData = new Uint8Array(width * height * 4);
  23946. for (y = y_start; y !== y_end; y += y_step) {
  23947. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23948. imageData[(x + width * y) * 4 + 3] = 255;
  23949. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23950. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23951. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23952. }
  23953. }
  23954. return imageData;
  23955. };
  23956. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23957. var image = pixel_data;
  23958. var width = header.width, height = header.height;
  23959. var i = 0, x, y;
  23960. var imageData = new Uint8Array(width * height * 4);
  23961. for (y = y_start; y !== y_end; y += y_step) {
  23962. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23963. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23964. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23965. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23966. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23967. }
  23968. }
  23969. return imageData;
  23970. };
  23971. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23972. var image = pixel_data;
  23973. var width = header.width, height = header.height;
  23974. var color, i = 0, x, y;
  23975. var imageData = new Uint8Array(width * height * 4);
  23976. for (y = y_start; y !== y_end; y += y_step) {
  23977. for (x = x_start; x !== x_end; x += x_step, i++) {
  23978. color = image[i];
  23979. imageData[(x + width * y) * 4 + 0] = color;
  23980. imageData[(x + width * y) * 4 + 1] = color;
  23981. imageData[(x + width * y) * 4 + 2] = color;
  23982. imageData[(x + width * y) * 4 + 3] = 255;
  23983. }
  23984. }
  23985. return imageData;
  23986. };
  23987. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23988. var image = pixel_data;
  23989. var width = header.width, height = header.height;
  23990. var i = 0, x, y;
  23991. var imageData = new Uint8Array(width * height * 4);
  23992. for (y = y_start; y !== y_end; y += y_step) {
  23993. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23994. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23995. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23996. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23997. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23998. }
  23999. }
  24000. return imageData;
  24001. };
  24002. TGATools._TYPE_NO_DATA = 0;
  24003. TGATools._TYPE_INDEXED = 1;
  24004. TGATools._TYPE_RGB = 2;
  24005. TGATools._TYPE_GREY = 3;
  24006. TGATools._TYPE_RLE_INDEXED = 9;
  24007. TGATools._TYPE_RLE_RGB = 10;
  24008. TGATools._TYPE_RLE_GREY = 11;
  24009. TGATools._ORIGIN_MASK = 0x30;
  24010. TGATools._ORIGIN_SHIFT = 0x04;
  24011. TGATools._ORIGIN_BL = 0x00;
  24012. TGATools._ORIGIN_BR = 0x01;
  24013. TGATools._ORIGIN_UL = 0x02;
  24014. TGATools._ORIGIN_UR = 0x03;
  24015. return TGATools;
  24016. })();
  24017. Internals.TGATools = TGATools;
  24018. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24019. })(BABYLON || (BABYLON = {}));
  24020. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24021. (function (BABYLON) {
  24022. var Internals;
  24023. (function (Internals) {
  24024. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24025. // All values and structures referenced from:
  24026. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24027. var DDS_MAGIC = 0x20534444;
  24028. 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;
  24029. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24030. 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;
  24031. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24032. function FourCCToInt32(value) {
  24033. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24034. }
  24035. function Int32ToFourCC(value) {
  24036. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24037. }
  24038. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24039. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24040. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24041. var headerLengthInt = 31; // The header length in 32 bit ints
  24042. // Offsets into the header array
  24043. var off_magic = 0;
  24044. var off_size = 1;
  24045. var off_flags = 2;
  24046. var off_height = 3;
  24047. var off_width = 4;
  24048. var off_mipmapCount = 7;
  24049. var off_pfFlags = 20;
  24050. var off_pfFourCC = 21;
  24051. var off_RGBbpp = 22;
  24052. var off_RMask = 23;
  24053. var off_GMask = 24;
  24054. var off_BMask = 25;
  24055. var off_AMask = 26;
  24056. var off_caps1 = 27;
  24057. var off_caps2 = 28;
  24058. ;
  24059. var DDSTools = (function () {
  24060. function DDSTools() {
  24061. }
  24062. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24063. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24064. var mipmapCount = 1;
  24065. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24066. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24067. }
  24068. return {
  24069. width: header[off_width],
  24070. height: header[off_height],
  24071. mipmapCount: mipmapCount,
  24072. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24073. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24074. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24075. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24076. };
  24077. };
  24078. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24079. var byteArray = new Uint8Array(dataLength);
  24080. var srcData = new Uint8Array(arrayBuffer);
  24081. var index = 0;
  24082. for (var y = height - 1; y >= 0; y--) {
  24083. for (var x = 0; x < width; x++) {
  24084. var srcPos = dataOffset + (x + y * width) * 4;
  24085. byteArray[index + 2] = srcData[srcPos];
  24086. byteArray[index + 1] = srcData[srcPos + 1];
  24087. byteArray[index] = srcData[srcPos + 2];
  24088. byteArray[index + 3] = srcData[srcPos + 3];
  24089. index += 4;
  24090. }
  24091. }
  24092. return byteArray;
  24093. };
  24094. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24095. var byteArray = new Uint8Array(dataLength);
  24096. var srcData = new Uint8Array(arrayBuffer);
  24097. var index = 0;
  24098. for (var y = height - 1; y >= 0; y--) {
  24099. for (var x = 0; x < width; x++) {
  24100. var srcPos = dataOffset + (x + y * width) * 3;
  24101. byteArray[index + 2] = srcData[srcPos];
  24102. byteArray[index + 1] = srcData[srcPos + 1];
  24103. byteArray[index] = srcData[srcPos + 2];
  24104. index += 3;
  24105. }
  24106. }
  24107. return byteArray;
  24108. };
  24109. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24110. var byteArray = new Uint8Array(dataLength);
  24111. var srcData = new Uint8Array(arrayBuffer);
  24112. var index = 0;
  24113. for (var y = height - 1; y >= 0; y--) {
  24114. for (var x = 0; x < width; x++) {
  24115. var srcPos = dataOffset + (x + y * width);
  24116. byteArray[index] = srcData[srcPos];
  24117. index++;
  24118. }
  24119. }
  24120. return byteArray;
  24121. };
  24122. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24123. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24124. if (header[off_magic] != DDS_MAGIC) {
  24125. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24126. return;
  24127. }
  24128. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24129. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24130. return;
  24131. }
  24132. if (info.isFourCC) {
  24133. fourCC = header[off_pfFourCC];
  24134. switch (fourCC) {
  24135. case FOURCC_DXT1:
  24136. blockBytes = 8;
  24137. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24138. break;
  24139. case FOURCC_DXT3:
  24140. blockBytes = 16;
  24141. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24142. break;
  24143. case FOURCC_DXT5:
  24144. blockBytes = 16;
  24145. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24146. break;
  24147. default:
  24148. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24149. return;
  24150. }
  24151. }
  24152. mipmapCount = 1;
  24153. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24154. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24155. }
  24156. var bpp = header[off_RGBbpp];
  24157. for (var face = 0; face < faces; face++) {
  24158. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24159. width = header[off_width];
  24160. height = header[off_height];
  24161. dataOffset = header[off_size] + 4;
  24162. for (i = 0; i < mipmapCount; ++i) {
  24163. if (info.isRGB) {
  24164. if (bpp == 24) {
  24165. dataLength = width * height * 3;
  24166. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24167. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24168. }
  24169. else {
  24170. dataLength = width * height * 4;
  24171. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24172. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24173. }
  24174. }
  24175. else if (info.isLuminance) {
  24176. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24177. var unpaddedRowSize = width;
  24178. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24179. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24180. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24181. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24182. }
  24183. else {
  24184. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24185. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24186. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24187. }
  24188. dataOffset += dataLength;
  24189. width *= 0.5;
  24190. height *= 0.5;
  24191. width = Math.max(1.0, width);
  24192. height = Math.max(1.0, height);
  24193. }
  24194. }
  24195. };
  24196. return DDSTools;
  24197. })();
  24198. Internals.DDSTools = DDSTools;
  24199. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24200. })(BABYLON || (BABYLON = {}));
  24201. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24202. (function (BABYLON) {
  24203. var SmartArray = (function () {
  24204. function SmartArray(capacity) {
  24205. this.length = 0;
  24206. this._duplicateId = 0;
  24207. this.data = new Array(capacity);
  24208. this._id = SmartArray._GlobalId++;
  24209. }
  24210. SmartArray.prototype.push = function (value) {
  24211. this.data[this.length++] = value;
  24212. if (this.length > this.data.length) {
  24213. this.data.length *= 2;
  24214. }
  24215. if (!value.__smartArrayFlags) {
  24216. value.__smartArrayFlags = {};
  24217. }
  24218. value.__smartArrayFlags[this._id] = this._duplicateId;
  24219. };
  24220. SmartArray.prototype.pushNoDuplicate = function (value) {
  24221. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24222. return;
  24223. }
  24224. this.push(value);
  24225. };
  24226. SmartArray.prototype.sort = function (compareFn) {
  24227. this.data.sort(compareFn);
  24228. };
  24229. SmartArray.prototype.reset = function () {
  24230. this.length = 0;
  24231. this._duplicateId++;
  24232. };
  24233. SmartArray.prototype.concat = function (array) {
  24234. if (array.length === 0) {
  24235. return;
  24236. }
  24237. if (this.length + array.length > this.data.length) {
  24238. this.data.length = (this.length + array.length) * 2;
  24239. }
  24240. for (var index = 0; index < array.length; index++) {
  24241. this.data[this.length++] = (array.data || array)[index];
  24242. }
  24243. };
  24244. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24245. if (array.length === 0) {
  24246. return;
  24247. }
  24248. if (this.length + array.length > this.data.length) {
  24249. this.data.length = (this.length + array.length) * 2;
  24250. }
  24251. for (var index = 0; index < array.length; index++) {
  24252. var item = (array.data || array)[index];
  24253. this.pushNoDuplicate(item);
  24254. }
  24255. };
  24256. SmartArray.prototype.indexOf = function (value) {
  24257. var position = this.data.indexOf(value);
  24258. if (position >= this.length) {
  24259. return -1;
  24260. }
  24261. return position;
  24262. };
  24263. // Statics
  24264. SmartArray._GlobalId = 0;
  24265. return SmartArray;
  24266. })();
  24267. BABYLON.SmartArray = SmartArray;
  24268. })(BABYLON || (BABYLON = {}));
  24269. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24270. (function (BABYLON) {
  24271. var CannonJSPlugin = (function () {
  24272. function CannonJSPlugin() {
  24273. this._registeredMeshes = [];
  24274. this._physicsMaterials = [];
  24275. this.updateBodyPosition = function (mesh) {
  24276. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24277. var registeredMesh = this._registeredMeshes[index];
  24278. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24279. var body = registeredMesh.body;
  24280. var center = mesh.getBoundingInfo().boundingBox.center;
  24281. body.position.set(center.x, center.z, center.y);
  24282. body.quaternion.x = mesh.rotationQuaternion.x;
  24283. body.quaternion.z = mesh.rotationQuaternion.y;
  24284. body.quaternion.y = mesh.rotationQuaternion.z;
  24285. body.quaternion.w = -mesh.rotationQuaternion.w;
  24286. return;
  24287. }
  24288. }
  24289. };
  24290. }
  24291. CannonJSPlugin.prototype.initialize = function (iterations) {
  24292. if (iterations === void 0) { iterations = 10; }
  24293. this._world = new CANNON.World();
  24294. this._world.broadphase = new CANNON.NaiveBroadphase();
  24295. this._world.solver.iterations = iterations;
  24296. };
  24297. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24298. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24299. };
  24300. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24301. this._world.step(delta);
  24302. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24303. var registeredMesh = this._registeredMeshes[index];
  24304. if (registeredMesh.isChild) {
  24305. continue;
  24306. }
  24307. // Body position
  24308. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24309. var deltaPos = registeredMesh.delta;
  24310. if (deltaPos) {
  24311. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24312. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24313. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24314. }
  24315. else {
  24316. registeredMesh.mesh.position.x = bodyX;
  24317. registeredMesh.mesh.position.y = bodyZ;
  24318. registeredMesh.mesh.position.z = bodyY;
  24319. }
  24320. if (!registeredMesh.mesh.rotationQuaternion) {
  24321. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24322. }
  24323. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24324. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24325. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24326. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24327. }
  24328. };
  24329. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24330. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24331. };
  24332. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24333. this.unregisterMesh(mesh);
  24334. mesh.computeWorldMatrix(true);
  24335. switch (impostor) {
  24336. case BABYLON.PhysicsEngine.SphereImpostor:
  24337. var bbox = mesh.getBoundingInfo().boundingBox;
  24338. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24339. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24340. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24341. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24342. case BABYLON.PhysicsEngine.BoxImpostor:
  24343. bbox = mesh.getBoundingInfo().boundingBox;
  24344. var min = bbox.minimumWorld;
  24345. var max = bbox.maximumWorld;
  24346. var box = max.subtract(min).scale(0.5);
  24347. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24348. case BABYLON.PhysicsEngine.PlaneImpostor:
  24349. return this._createPlane(mesh, options);
  24350. case BABYLON.PhysicsEngine.MeshImpostor:
  24351. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24352. var rawFaces = mesh.getIndices();
  24353. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24354. }
  24355. return null;
  24356. };
  24357. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24358. var shape = new CANNON.Sphere(radius);
  24359. if (!options) {
  24360. return shape;
  24361. }
  24362. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24363. };
  24364. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24365. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24366. if (!options) {
  24367. return shape;
  24368. }
  24369. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24370. };
  24371. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24372. var shape = new CANNON.Plane();
  24373. if (!options) {
  24374. return shape;
  24375. }
  24376. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24377. };
  24378. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24379. var verts = [], faces = [];
  24380. mesh.computeWorldMatrix(true);
  24381. for (var i = 0; i < rawVerts.length; i += 3) {
  24382. var transformed = BABYLON.Vector3.Zero();
  24383. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24384. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24385. }
  24386. for (var j = 0; j < rawFaces.length; j += 3) {
  24387. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24388. }
  24389. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24390. if (!options) {
  24391. return shape;
  24392. }
  24393. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24394. };
  24395. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24396. var index;
  24397. var mat;
  24398. for (index = 0; index < this._physicsMaterials.length; index++) {
  24399. mat = this._physicsMaterials[index];
  24400. if (mat.friction === friction && mat.restitution === restitution) {
  24401. return mat;
  24402. }
  24403. }
  24404. var currentMat = new CANNON.Material();
  24405. currentMat.friction = friction;
  24406. currentMat.restitution = restitution;
  24407. this._physicsMaterials.push(currentMat);
  24408. for (index = 0; index < this._physicsMaterials.length; index++) {
  24409. mat = this._physicsMaterials[index];
  24410. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24411. contactMaterial.contactEquationStiffness = 1e10;
  24412. contactMaterial.contactEquationRegularizationTime = 10;
  24413. this._world.addContactMaterial(contactMaterial);
  24414. }
  24415. return currentMat;
  24416. };
  24417. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24418. var initialRotation = null;
  24419. if (mesh.rotationQuaternion) {
  24420. initialRotation = mesh.rotationQuaternion.clone();
  24421. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24422. }
  24423. // The delta between the mesh position and the mesh bounding box center
  24424. var bbox = mesh.getBoundingInfo().boundingBox;
  24425. var deltaPosition = mesh.position.subtract(bbox.center);
  24426. var material = this._addMaterial(friction, restitution);
  24427. var body = new CANNON.RigidBody(mass, shape, material);
  24428. if (initialRotation) {
  24429. body.quaternion.x = initialRotation.x;
  24430. body.quaternion.z = initialRotation.y;
  24431. body.quaternion.y = initialRotation.z;
  24432. body.quaternion.w = -initialRotation.w;
  24433. }
  24434. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24435. this._world.add(body);
  24436. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24437. return body;
  24438. };
  24439. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24440. var compoundShape = new CANNON.Compound();
  24441. for (var index = 0; index < parts.length; index++) {
  24442. var mesh = parts[index].mesh;
  24443. var shape = this.registerMesh(mesh, parts[index].impostor);
  24444. if (index == 0) {
  24445. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24446. }
  24447. else {
  24448. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24449. }
  24450. }
  24451. var initialMesh = parts[0].mesh;
  24452. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24453. body.parts = parts;
  24454. return body;
  24455. };
  24456. CannonJSPlugin.prototype._unbindBody = function (body) {
  24457. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24458. var registeredMesh = this._registeredMeshes[index];
  24459. if (registeredMesh.body === body) {
  24460. registeredMesh.body = null;
  24461. registeredMesh.delta = 0;
  24462. }
  24463. }
  24464. };
  24465. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24466. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24467. var registeredMesh = this._registeredMeshes[index];
  24468. if (registeredMesh.mesh === mesh) {
  24469. // Remove body
  24470. if (registeredMesh.body) {
  24471. this._world.remove(registeredMesh.body);
  24472. this._unbindBody(registeredMesh.body);
  24473. }
  24474. this._registeredMeshes.splice(index, 1);
  24475. return;
  24476. }
  24477. }
  24478. };
  24479. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24480. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24481. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24482. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24483. var registeredMesh = this._registeredMeshes[index];
  24484. if (registeredMesh.mesh === mesh) {
  24485. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24486. return;
  24487. }
  24488. }
  24489. };
  24490. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24491. var body1 = null, body2 = null;
  24492. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24493. var registeredMesh = this._registeredMeshes[index];
  24494. if (registeredMesh.mesh === mesh1) {
  24495. body1 = registeredMesh.body;
  24496. }
  24497. else if (registeredMesh.mesh === mesh2) {
  24498. body2 = registeredMesh.body;
  24499. }
  24500. }
  24501. if (!body1 || !body2) {
  24502. return false;
  24503. }
  24504. 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));
  24505. this._world.addConstraint(constraint);
  24506. return true;
  24507. };
  24508. CannonJSPlugin.prototype.dispose = function () {
  24509. while (this._registeredMeshes.length) {
  24510. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24511. }
  24512. };
  24513. CannonJSPlugin.prototype.isSupported = function () {
  24514. return window.CANNON !== undefined;
  24515. };
  24516. return CannonJSPlugin;
  24517. })();
  24518. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24519. })(BABYLON || (BABYLON = {}));
  24520. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24521. var BABYLON;
  24522. (function (BABYLON) {
  24523. var Condition = (function () {
  24524. function Condition(actionManager) {
  24525. this._actionManager = actionManager;
  24526. }
  24527. Condition.prototype.isValid = function () {
  24528. return true;
  24529. };
  24530. Condition.prototype._getProperty = function (propertyPath) {
  24531. return this._actionManager._getProperty(propertyPath);
  24532. };
  24533. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24534. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24535. };
  24536. return Condition;
  24537. })();
  24538. BABYLON.Condition = Condition;
  24539. var ValueCondition = (function (_super) {
  24540. __extends(ValueCondition, _super);
  24541. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24542. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24543. _super.call(this, actionManager);
  24544. this.propertyPath = propertyPath;
  24545. this.value = value;
  24546. this.operator = operator;
  24547. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24548. this._property = this._getProperty(this.propertyPath);
  24549. }
  24550. Object.defineProperty(ValueCondition, "IsEqual", {
  24551. get: function () {
  24552. return ValueCondition._IsEqual;
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(ValueCondition, "IsDifferent", {
  24558. get: function () {
  24559. return ValueCondition._IsDifferent;
  24560. },
  24561. enumerable: true,
  24562. configurable: true
  24563. });
  24564. Object.defineProperty(ValueCondition, "IsGreater", {
  24565. get: function () {
  24566. return ValueCondition._IsGreater;
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. Object.defineProperty(ValueCondition, "IsLesser", {
  24572. get: function () {
  24573. return ValueCondition._IsLesser;
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. // Methods
  24579. ValueCondition.prototype.isValid = function () {
  24580. switch (this.operator) {
  24581. case ValueCondition.IsGreater:
  24582. return this._target[this._property] > this.value;
  24583. case ValueCondition.IsLesser:
  24584. return this._target[this._property] < this.value;
  24585. case ValueCondition.IsEqual:
  24586. case ValueCondition.IsDifferent:
  24587. var check;
  24588. if (this.value.equals) {
  24589. check = this.value.equals(this._target[this._property]);
  24590. }
  24591. else {
  24592. check = this.value === this._target[this._property];
  24593. }
  24594. return this.operator === ValueCondition.IsEqual ? check : !check;
  24595. }
  24596. return false;
  24597. };
  24598. // Statics
  24599. ValueCondition._IsEqual = 0;
  24600. ValueCondition._IsDifferent = 1;
  24601. ValueCondition._IsGreater = 2;
  24602. ValueCondition._IsLesser = 3;
  24603. return ValueCondition;
  24604. })(Condition);
  24605. BABYLON.ValueCondition = ValueCondition;
  24606. var PredicateCondition = (function (_super) {
  24607. __extends(PredicateCondition, _super);
  24608. function PredicateCondition(actionManager, predicate) {
  24609. _super.call(this, actionManager);
  24610. this.predicate = predicate;
  24611. }
  24612. PredicateCondition.prototype.isValid = function () {
  24613. return this.predicate();
  24614. };
  24615. return PredicateCondition;
  24616. })(Condition);
  24617. BABYLON.PredicateCondition = PredicateCondition;
  24618. var StateCondition = (function (_super) {
  24619. __extends(StateCondition, _super);
  24620. function StateCondition(actionManager, target, value) {
  24621. _super.call(this, actionManager);
  24622. this.value = value;
  24623. this._target = target;
  24624. }
  24625. // Methods
  24626. StateCondition.prototype.isValid = function () {
  24627. return this._target.state === this.value;
  24628. };
  24629. return StateCondition;
  24630. })(Condition);
  24631. BABYLON.StateCondition = StateCondition;
  24632. })(BABYLON || (BABYLON = {}));
  24633. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24634. (function (BABYLON) {
  24635. var Action = (function () {
  24636. function Action(triggerOptions, condition) {
  24637. this.triggerOptions = triggerOptions;
  24638. if (triggerOptions.parameter) {
  24639. this.trigger = triggerOptions.trigger;
  24640. this._triggerParameter = triggerOptions.parameter;
  24641. }
  24642. else {
  24643. this.trigger = triggerOptions;
  24644. }
  24645. this._nextActiveAction = this;
  24646. this._condition = condition;
  24647. }
  24648. // Methods
  24649. Action.prototype._prepare = function () {
  24650. };
  24651. Action.prototype.getTriggerParameter = function () {
  24652. return this._triggerParameter;
  24653. };
  24654. Action.prototype._executeCurrent = function (evt) {
  24655. if (this._nextActiveAction._condition) {
  24656. var condition = this._nextActiveAction._condition;
  24657. var currentRenderId = this._actionManager.getScene().getRenderId();
  24658. // We cache the current evaluation for the current frame
  24659. if (condition._evaluationId === currentRenderId) {
  24660. if (!condition._currentResult) {
  24661. return;
  24662. }
  24663. }
  24664. else {
  24665. condition._evaluationId = currentRenderId;
  24666. if (!condition.isValid()) {
  24667. condition._currentResult = false;
  24668. return;
  24669. }
  24670. condition._currentResult = true;
  24671. }
  24672. }
  24673. this._nextActiveAction.execute(evt);
  24674. if (this._nextActiveAction._child) {
  24675. if (!this._nextActiveAction._child._actionManager) {
  24676. this._nextActiveAction._child._actionManager = this._actionManager;
  24677. }
  24678. this._nextActiveAction = this._nextActiveAction._child;
  24679. }
  24680. else {
  24681. this._nextActiveAction = this;
  24682. }
  24683. };
  24684. Action.prototype.execute = function (evt) {
  24685. };
  24686. Action.prototype.then = function (action) {
  24687. this._child = action;
  24688. action._actionManager = this._actionManager;
  24689. action._prepare();
  24690. return action;
  24691. };
  24692. Action.prototype._getProperty = function (propertyPath) {
  24693. return this._actionManager._getProperty(propertyPath);
  24694. };
  24695. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24696. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24697. };
  24698. return Action;
  24699. })();
  24700. BABYLON.Action = Action;
  24701. })(BABYLON || (BABYLON = {}));
  24702. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24703. (function (BABYLON) {
  24704. /**
  24705. * ActionEvent is the event beint sent when an action is triggered.
  24706. */
  24707. var ActionEvent = (function () {
  24708. /**
  24709. * @constructor
  24710. * @param source The mesh that triggered the action.
  24711. * @param pointerX the X mouse cursor position at the time of the event
  24712. * @param pointerY the Y mouse cursor position at the time of the event
  24713. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24714. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24715. */
  24716. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24717. this.source = source;
  24718. this.pointerX = pointerX;
  24719. this.pointerY = pointerY;
  24720. this.meshUnderPointer = meshUnderPointer;
  24721. this.sourceEvent = sourceEvent;
  24722. }
  24723. /**
  24724. * Helper function to auto-create an ActionEvent from a source mesh.
  24725. * @param source the source mesh that triggered the event
  24726. * @param evt {Event} The original (browser) event
  24727. */
  24728. ActionEvent.CreateNew = function (source, evt) {
  24729. var scene = source.getScene();
  24730. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24731. };
  24732. /**
  24733. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24734. * @param scene the scene where the event occurred
  24735. * @param evt {Event} The original (browser) event
  24736. */
  24737. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24738. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24739. };
  24740. return ActionEvent;
  24741. })();
  24742. BABYLON.ActionEvent = ActionEvent;
  24743. /**
  24744. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24745. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24746. */
  24747. var ActionManager = (function () {
  24748. function ActionManager(scene) {
  24749. // Members
  24750. this.actions = new Array();
  24751. this._scene = scene;
  24752. scene._actionManagers.push(this);
  24753. }
  24754. Object.defineProperty(ActionManager, "NothingTrigger", {
  24755. get: function () {
  24756. return ActionManager._NothingTrigger;
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24762. get: function () {
  24763. return ActionManager._OnPickTrigger;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24769. get: function () {
  24770. return ActionManager._OnLeftPickTrigger;
  24771. },
  24772. enumerable: true,
  24773. configurable: true
  24774. });
  24775. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24776. get: function () {
  24777. return ActionManager._OnRightPickTrigger;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24783. get: function () {
  24784. return ActionManager._OnCenterPickTrigger;
  24785. },
  24786. enumerable: true,
  24787. configurable: true
  24788. });
  24789. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24790. get: function () {
  24791. return ActionManager._OnPointerOverTrigger;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24797. get: function () {
  24798. return ActionManager._OnPointerOutTrigger;
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24804. get: function () {
  24805. return ActionManager._OnEveryFrameTrigger;
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24811. get: function () {
  24812. return ActionManager._OnIntersectionEnterTrigger;
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24818. get: function () {
  24819. return ActionManager._OnIntersectionExitTrigger;
  24820. },
  24821. enumerable: true,
  24822. configurable: true
  24823. });
  24824. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24825. get: function () {
  24826. return ActionManager._OnKeyDownTrigger;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24832. get: function () {
  24833. return ActionManager._OnKeyUpTrigger;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. // Methods
  24839. ActionManager.prototype.dispose = function () {
  24840. var index = this._scene._actionManagers.indexOf(this);
  24841. if (index > -1) {
  24842. this._scene._actionManagers.splice(index, 1);
  24843. }
  24844. };
  24845. ActionManager.prototype.getScene = function () {
  24846. return this._scene;
  24847. };
  24848. /**
  24849. * Does this action manager handles actions of any of the given triggers
  24850. * @param {number[]} triggers - the triggers to be tested
  24851. * @return {boolean} whether one (or more) of the triggers is handeled
  24852. */
  24853. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24854. for (var index = 0; index < this.actions.length; index++) {
  24855. var action = this.actions[index];
  24856. if (triggers.indexOf(action.trigger) > -1) {
  24857. return true;
  24858. }
  24859. }
  24860. return false;
  24861. };
  24862. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24863. /**
  24864. * Does this action manager has pointer triggers
  24865. * @return {boolean} whether or not it has pointer triggers
  24866. */
  24867. get: function () {
  24868. for (var index = 0; index < this.actions.length; index++) {
  24869. var action = this.actions[index];
  24870. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24871. return true;
  24872. }
  24873. }
  24874. return false;
  24875. },
  24876. enumerable: true,
  24877. configurable: true
  24878. });
  24879. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24880. /**
  24881. * Does this action manager has pick triggers
  24882. * @return {boolean} whether or not it has pick triggers
  24883. */
  24884. get: function () {
  24885. for (var index = 0; index < this.actions.length; index++) {
  24886. var action = this.actions[index];
  24887. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24888. return true;
  24889. }
  24890. }
  24891. return false;
  24892. },
  24893. enumerable: true,
  24894. configurable: true
  24895. });
  24896. /**
  24897. * Registers an action to this action manager
  24898. * @param {BABYLON.Action} action - the action to be registered
  24899. * @return {BABYLON.Action} the action amended (prepared) after registration
  24900. */
  24901. ActionManager.prototype.registerAction = function (action) {
  24902. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24903. if (this.getScene().actionManager !== this) {
  24904. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24905. return null;
  24906. }
  24907. }
  24908. this.actions.push(action);
  24909. action._actionManager = this;
  24910. action._prepare();
  24911. return action;
  24912. };
  24913. /**
  24914. * Process a specific trigger
  24915. * @param {number} trigger - the trigger to process
  24916. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24917. */
  24918. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24919. for (var index = 0; index < this.actions.length; index++) {
  24920. var action = this.actions[index];
  24921. if (action.trigger === trigger) {
  24922. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24923. var parameter = action.getTriggerParameter();
  24924. if (parameter) {
  24925. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24926. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24927. if (actualkey !== parameter.toLowerCase()) {
  24928. continue;
  24929. }
  24930. }
  24931. }
  24932. action._executeCurrent(evt);
  24933. }
  24934. }
  24935. };
  24936. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24937. var properties = propertyPath.split(".");
  24938. for (var index = 0; index < properties.length - 1; index++) {
  24939. target = target[properties[index]];
  24940. }
  24941. return target;
  24942. };
  24943. ActionManager.prototype._getProperty = function (propertyPath) {
  24944. var properties = propertyPath.split(".");
  24945. return properties[properties.length - 1];
  24946. };
  24947. // Statics
  24948. ActionManager._NothingTrigger = 0;
  24949. ActionManager._OnPickTrigger = 1;
  24950. ActionManager._OnLeftPickTrigger = 2;
  24951. ActionManager._OnRightPickTrigger = 3;
  24952. ActionManager._OnCenterPickTrigger = 4;
  24953. ActionManager._OnPointerOverTrigger = 5;
  24954. ActionManager._OnPointerOutTrigger = 6;
  24955. ActionManager._OnEveryFrameTrigger = 7;
  24956. ActionManager._OnIntersectionEnterTrigger = 8;
  24957. ActionManager._OnIntersectionExitTrigger = 9;
  24958. ActionManager._OnKeyDownTrigger = 10;
  24959. ActionManager._OnKeyUpTrigger = 11;
  24960. return ActionManager;
  24961. })();
  24962. BABYLON.ActionManager = ActionManager;
  24963. })(BABYLON || (BABYLON = {}));
  24964. //# sourceMappingURL=babylon.actionManager.js.map
  24965. var BABYLON;
  24966. (function (BABYLON) {
  24967. var InterpolateValueAction = (function (_super) {
  24968. __extends(InterpolateValueAction, _super);
  24969. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24970. if (duration === void 0) { duration = 1000; }
  24971. _super.call(this, triggerOptions, condition);
  24972. this.propertyPath = propertyPath;
  24973. this.value = value;
  24974. this.duration = duration;
  24975. this.stopOtherAnimations = stopOtherAnimations;
  24976. this._target = target;
  24977. }
  24978. InterpolateValueAction.prototype._prepare = function () {
  24979. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24980. this._property = this._getProperty(this.propertyPath);
  24981. };
  24982. InterpolateValueAction.prototype.execute = function () {
  24983. var scene = this._actionManager.getScene();
  24984. var keys = [
  24985. {
  24986. frame: 0,
  24987. value: this._target[this._property]
  24988. },
  24989. {
  24990. frame: 100,
  24991. value: this.value
  24992. }
  24993. ];
  24994. var dataType;
  24995. if (typeof this.value === "number") {
  24996. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24997. }
  24998. else if (this.value instanceof BABYLON.Color3) {
  24999. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25000. }
  25001. else if (this.value instanceof BABYLON.Vector3) {
  25002. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25003. }
  25004. else if (this.value instanceof BABYLON.Matrix) {
  25005. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25006. }
  25007. else if (this.value instanceof BABYLON.Quaternion) {
  25008. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25009. }
  25010. else {
  25011. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25012. return;
  25013. }
  25014. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25015. animation.setKeys(keys);
  25016. if (this.stopOtherAnimations) {
  25017. scene.stopAnimation(this._target);
  25018. }
  25019. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25020. };
  25021. return InterpolateValueAction;
  25022. })(BABYLON.Action);
  25023. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25024. })(BABYLON || (BABYLON = {}));
  25025. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25026. var BABYLON;
  25027. (function (BABYLON) {
  25028. var SwitchBooleanAction = (function (_super) {
  25029. __extends(SwitchBooleanAction, _super);
  25030. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25031. _super.call(this, triggerOptions, condition);
  25032. this.propertyPath = propertyPath;
  25033. this._target = target;
  25034. }
  25035. SwitchBooleanAction.prototype._prepare = function () {
  25036. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25037. this._property = this._getProperty(this.propertyPath);
  25038. };
  25039. SwitchBooleanAction.prototype.execute = function () {
  25040. this._target[this._property] = !this._target[this._property];
  25041. };
  25042. return SwitchBooleanAction;
  25043. })(BABYLON.Action);
  25044. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25045. var SetStateAction = (function (_super) {
  25046. __extends(SetStateAction, _super);
  25047. function SetStateAction(triggerOptions, target, value, condition) {
  25048. _super.call(this, triggerOptions, condition);
  25049. this.value = value;
  25050. this._target = target;
  25051. }
  25052. SetStateAction.prototype.execute = function () {
  25053. this._target.state = this.value;
  25054. };
  25055. return SetStateAction;
  25056. })(BABYLON.Action);
  25057. BABYLON.SetStateAction = SetStateAction;
  25058. var SetValueAction = (function (_super) {
  25059. __extends(SetValueAction, _super);
  25060. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25061. _super.call(this, triggerOptions, condition);
  25062. this.propertyPath = propertyPath;
  25063. this.value = value;
  25064. this._target = target;
  25065. }
  25066. SetValueAction.prototype._prepare = function () {
  25067. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25068. this._property = this._getProperty(this.propertyPath);
  25069. };
  25070. SetValueAction.prototype.execute = function () {
  25071. this._target[this._property] = this.value;
  25072. };
  25073. return SetValueAction;
  25074. })(BABYLON.Action);
  25075. BABYLON.SetValueAction = SetValueAction;
  25076. var IncrementValueAction = (function (_super) {
  25077. __extends(IncrementValueAction, _super);
  25078. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25079. _super.call(this, triggerOptions, condition);
  25080. this.propertyPath = propertyPath;
  25081. this.value = value;
  25082. this._target = target;
  25083. }
  25084. IncrementValueAction.prototype._prepare = function () {
  25085. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25086. this._property = this._getProperty(this.propertyPath);
  25087. if (typeof this._target[this._property] !== "number") {
  25088. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25089. }
  25090. };
  25091. IncrementValueAction.prototype.execute = function () {
  25092. this._target[this._property] += this.value;
  25093. };
  25094. return IncrementValueAction;
  25095. })(BABYLON.Action);
  25096. BABYLON.IncrementValueAction = IncrementValueAction;
  25097. var PlayAnimationAction = (function (_super) {
  25098. __extends(PlayAnimationAction, _super);
  25099. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25100. _super.call(this, triggerOptions, condition);
  25101. this.from = from;
  25102. this.to = to;
  25103. this.loop = loop;
  25104. this._target = target;
  25105. }
  25106. PlayAnimationAction.prototype._prepare = function () {
  25107. };
  25108. PlayAnimationAction.prototype.execute = function () {
  25109. var scene = this._actionManager.getScene();
  25110. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25111. };
  25112. return PlayAnimationAction;
  25113. })(BABYLON.Action);
  25114. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25115. var StopAnimationAction = (function (_super) {
  25116. __extends(StopAnimationAction, _super);
  25117. function StopAnimationAction(triggerOptions, target, condition) {
  25118. _super.call(this, triggerOptions, condition);
  25119. this._target = target;
  25120. }
  25121. StopAnimationAction.prototype._prepare = function () {
  25122. };
  25123. StopAnimationAction.prototype.execute = function () {
  25124. var scene = this._actionManager.getScene();
  25125. scene.stopAnimation(this._target);
  25126. };
  25127. return StopAnimationAction;
  25128. })(BABYLON.Action);
  25129. BABYLON.StopAnimationAction = StopAnimationAction;
  25130. var DoNothingAction = (function (_super) {
  25131. __extends(DoNothingAction, _super);
  25132. function DoNothingAction(triggerOptions, condition) {
  25133. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25134. _super.call(this, triggerOptions, condition);
  25135. }
  25136. DoNothingAction.prototype.execute = function () {
  25137. };
  25138. return DoNothingAction;
  25139. })(BABYLON.Action);
  25140. BABYLON.DoNothingAction = DoNothingAction;
  25141. var CombineAction = (function (_super) {
  25142. __extends(CombineAction, _super);
  25143. function CombineAction(triggerOptions, children, condition) {
  25144. _super.call(this, triggerOptions, condition);
  25145. this.children = children;
  25146. }
  25147. CombineAction.prototype._prepare = function () {
  25148. for (var index = 0; index < this.children.length; index++) {
  25149. this.children[index]._actionManager = this._actionManager;
  25150. this.children[index]._prepare();
  25151. }
  25152. };
  25153. CombineAction.prototype.execute = function (evt) {
  25154. for (var index = 0; index < this.children.length; index++) {
  25155. this.children[index].execute(evt);
  25156. }
  25157. };
  25158. return CombineAction;
  25159. })(BABYLON.Action);
  25160. BABYLON.CombineAction = CombineAction;
  25161. var ExecuteCodeAction = (function (_super) {
  25162. __extends(ExecuteCodeAction, _super);
  25163. function ExecuteCodeAction(triggerOptions, func, condition) {
  25164. _super.call(this, triggerOptions, condition);
  25165. this.func = func;
  25166. }
  25167. ExecuteCodeAction.prototype.execute = function (evt) {
  25168. this.func(evt);
  25169. };
  25170. return ExecuteCodeAction;
  25171. })(BABYLON.Action);
  25172. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25173. var SetParentAction = (function (_super) {
  25174. __extends(SetParentAction, _super);
  25175. function SetParentAction(triggerOptions, target, parent, condition) {
  25176. _super.call(this, triggerOptions, condition);
  25177. this._target = target;
  25178. this._parent = parent;
  25179. }
  25180. SetParentAction.prototype._prepare = function () {
  25181. };
  25182. SetParentAction.prototype.execute = function () {
  25183. if (this._target.parent === this._parent) {
  25184. return;
  25185. }
  25186. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25187. invertParentWorldMatrix.invert();
  25188. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25189. this._target.parent = this._parent;
  25190. };
  25191. return SetParentAction;
  25192. })(BABYLON.Action);
  25193. BABYLON.SetParentAction = SetParentAction;
  25194. var PlaySoundAction = (function (_super) {
  25195. __extends(PlaySoundAction, _super);
  25196. function PlaySoundAction(triggerOptions, sound, condition) {
  25197. _super.call(this, triggerOptions, condition);
  25198. this._sound = sound;
  25199. }
  25200. PlaySoundAction.prototype._prepare = function () {
  25201. };
  25202. PlaySoundAction.prototype.execute = function () {
  25203. if (this._sound !== undefined)
  25204. this._sound.play();
  25205. };
  25206. return PlaySoundAction;
  25207. })(BABYLON.Action);
  25208. BABYLON.PlaySoundAction = PlaySoundAction;
  25209. var StopSoundAction = (function (_super) {
  25210. __extends(StopSoundAction, _super);
  25211. function StopSoundAction(triggerOptions, sound, condition) {
  25212. _super.call(this, triggerOptions, condition);
  25213. this._sound = sound;
  25214. }
  25215. StopSoundAction.prototype._prepare = function () {
  25216. };
  25217. StopSoundAction.prototype.execute = function () {
  25218. if (this._sound !== undefined)
  25219. this._sound.stop();
  25220. };
  25221. return StopSoundAction;
  25222. })(BABYLON.Action);
  25223. BABYLON.StopSoundAction = StopSoundAction;
  25224. })(BABYLON || (BABYLON = {}));
  25225. //# sourceMappingURL=babylon.directActions.js.map
  25226. var BABYLON;
  25227. (function (BABYLON) {
  25228. var Geometry = (function () {
  25229. function Geometry(id, scene, vertexData, updatable, mesh) {
  25230. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25231. this._totalVertices = 0;
  25232. this._indices = [];
  25233. this._isDisposed = false;
  25234. this.id = id;
  25235. this._engine = scene.getEngine();
  25236. this._meshes = [];
  25237. this._scene = scene;
  25238. // vertexData
  25239. if (vertexData) {
  25240. this.setAllVerticesData(vertexData, updatable);
  25241. }
  25242. else {
  25243. this._totalVertices = 0;
  25244. this._indices = [];
  25245. }
  25246. // applyToMesh
  25247. if (mesh) {
  25248. this.applyToMesh(mesh);
  25249. mesh.computeWorldMatrix(true);
  25250. }
  25251. }
  25252. Geometry.prototype.getScene = function () {
  25253. return this._scene;
  25254. };
  25255. Geometry.prototype.getEngine = function () {
  25256. return this._engine;
  25257. };
  25258. Geometry.prototype.isReady = function () {
  25259. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25260. };
  25261. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25262. vertexData.applyToGeometry(this, updatable);
  25263. };
  25264. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25265. this._vertexBuffers = this._vertexBuffers || {};
  25266. if (this._vertexBuffers[kind]) {
  25267. this._vertexBuffers[kind].dispose();
  25268. }
  25269. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25270. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25271. stride = this._vertexBuffers[kind].getStrideSize();
  25272. this._totalVertices = data.length / stride;
  25273. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25274. var meshes = this._meshes;
  25275. var numOfMeshes = meshes.length;
  25276. for (var index = 0; index < numOfMeshes; index++) {
  25277. var mesh = meshes[index];
  25278. mesh._resetPointsArrayCache();
  25279. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25280. mesh._createGlobalSubMesh();
  25281. mesh.computeWorldMatrix(true);
  25282. }
  25283. }
  25284. };
  25285. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25286. var vertexBuffer = this.getVertexBuffer(kind);
  25287. if (!vertexBuffer) {
  25288. return;
  25289. }
  25290. vertexBuffer.updateDirectly(data, offset);
  25291. };
  25292. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25293. var vertexBuffer = this.getVertexBuffer(kind);
  25294. if (!vertexBuffer) {
  25295. return;
  25296. }
  25297. vertexBuffer.update(data);
  25298. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25299. var extend;
  25300. var stride = vertexBuffer.getStrideSize();
  25301. this._totalVertices = data.length / stride;
  25302. if (updateExtends) {
  25303. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25304. }
  25305. var meshes = this._meshes;
  25306. var numOfMeshes = meshes.length;
  25307. for (var index = 0; index < numOfMeshes; index++) {
  25308. var mesh = meshes[index];
  25309. mesh._resetPointsArrayCache();
  25310. if (updateExtends) {
  25311. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25312. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25313. var subMesh = mesh.subMeshes[subIndex];
  25314. subMesh.refreshBoundingInfo();
  25315. }
  25316. }
  25317. }
  25318. }
  25319. };
  25320. Geometry.prototype.getTotalVertices = function () {
  25321. if (!this.isReady()) {
  25322. return 0;
  25323. }
  25324. return this._totalVertices;
  25325. };
  25326. Geometry.prototype.getVerticesData = function (kind) {
  25327. var vertexBuffer = this.getVertexBuffer(kind);
  25328. if (!vertexBuffer) {
  25329. return null;
  25330. }
  25331. return vertexBuffer.getData();
  25332. };
  25333. Geometry.prototype.getVertexBuffer = function (kind) {
  25334. if (!this.isReady()) {
  25335. return null;
  25336. }
  25337. return this._vertexBuffers[kind];
  25338. };
  25339. Geometry.prototype.getVertexBuffers = function () {
  25340. if (!this.isReady()) {
  25341. return null;
  25342. }
  25343. return this._vertexBuffers;
  25344. };
  25345. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25346. if (!this._vertexBuffers) {
  25347. if (this._delayInfo) {
  25348. return this._delayInfo.indexOf(kind) !== -1;
  25349. }
  25350. return false;
  25351. }
  25352. return this._vertexBuffers[kind] !== undefined;
  25353. };
  25354. Geometry.prototype.getVerticesDataKinds = function () {
  25355. var result = [];
  25356. if (!this._vertexBuffers && this._delayInfo) {
  25357. for (var kind in this._delayInfo) {
  25358. result.push(kind);
  25359. }
  25360. }
  25361. else {
  25362. for (kind in this._vertexBuffers) {
  25363. result.push(kind);
  25364. }
  25365. }
  25366. return result;
  25367. };
  25368. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25369. if (this._indexBuffer) {
  25370. this._engine._releaseBuffer(this._indexBuffer);
  25371. }
  25372. this._indices = indices;
  25373. if (this._meshes.length !== 0 && this._indices) {
  25374. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25375. }
  25376. if (totalVertices !== undefined) {
  25377. this._totalVertices = totalVertices;
  25378. }
  25379. var meshes = this._meshes;
  25380. var numOfMeshes = meshes.length;
  25381. for (var index = 0; index < numOfMeshes; index++) {
  25382. meshes[index]._createGlobalSubMesh();
  25383. }
  25384. };
  25385. Geometry.prototype.getTotalIndices = function () {
  25386. if (!this.isReady()) {
  25387. return 0;
  25388. }
  25389. return this._indices.length;
  25390. };
  25391. Geometry.prototype.getIndices = function () {
  25392. if (!this.isReady()) {
  25393. return null;
  25394. }
  25395. return this._indices;
  25396. };
  25397. Geometry.prototype.getIndexBuffer = function () {
  25398. if (!this.isReady()) {
  25399. return null;
  25400. }
  25401. return this._indexBuffer;
  25402. };
  25403. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25404. var meshes = this._meshes;
  25405. var index = meshes.indexOf(mesh);
  25406. if (index === -1) {
  25407. return;
  25408. }
  25409. for (var kind in this._vertexBuffers) {
  25410. this._vertexBuffers[kind].dispose();
  25411. }
  25412. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25413. this._indexBuffer = null;
  25414. }
  25415. meshes.splice(index, 1);
  25416. mesh._geometry = null;
  25417. if (meshes.length === 0 && shouldDispose) {
  25418. this.dispose();
  25419. }
  25420. };
  25421. Geometry.prototype.applyToMesh = function (mesh) {
  25422. if (mesh._geometry === this) {
  25423. return;
  25424. }
  25425. var previousGeometry = mesh._geometry;
  25426. if (previousGeometry) {
  25427. previousGeometry.releaseForMesh(mesh);
  25428. }
  25429. var meshes = this._meshes;
  25430. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25431. mesh._geometry = this;
  25432. this._scene.pushGeometry(this);
  25433. meshes.push(mesh);
  25434. if (this.isReady()) {
  25435. this._applyToMesh(mesh);
  25436. }
  25437. else {
  25438. mesh._boundingInfo = this._boundingInfo;
  25439. }
  25440. };
  25441. Geometry.prototype._applyToMesh = function (mesh) {
  25442. var numOfMeshes = this._meshes.length;
  25443. for (var kind in this._vertexBuffers) {
  25444. if (numOfMeshes === 1) {
  25445. this._vertexBuffers[kind].create();
  25446. }
  25447. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25448. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25449. mesh._resetPointsArrayCache();
  25450. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25451. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25452. mesh._createGlobalSubMesh();
  25453. //bounding info was just created again, world matrix should be applied again.
  25454. mesh._updateBoundingInfo();
  25455. }
  25456. }
  25457. // indexBuffer
  25458. if (numOfMeshes === 1 && this._indices) {
  25459. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25460. }
  25461. if (this._indexBuffer) {
  25462. this._indexBuffer.references = numOfMeshes;
  25463. }
  25464. };
  25465. Geometry.prototype.load = function (scene, onLoaded) {
  25466. var _this = this;
  25467. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25468. return;
  25469. }
  25470. if (this.isReady()) {
  25471. if (onLoaded) {
  25472. onLoaded();
  25473. }
  25474. return;
  25475. }
  25476. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25477. scene._addPendingData(this);
  25478. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25479. _this._delayLoadingFunction(JSON.parse(data), _this);
  25480. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25481. _this._delayInfo = [];
  25482. scene._removePendingData(_this);
  25483. var meshes = _this._meshes;
  25484. var numOfMeshes = meshes.length;
  25485. for (var index = 0; index < numOfMeshes; index++) {
  25486. _this._applyToMesh(meshes[index]);
  25487. }
  25488. if (onLoaded) {
  25489. onLoaded();
  25490. }
  25491. }, function () {
  25492. }, scene.database);
  25493. };
  25494. Geometry.prototype.isDisposed = function () {
  25495. return this._isDisposed;
  25496. };
  25497. Geometry.prototype.dispose = function () {
  25498. var meshes = this._meshes;
  25499. var numOfMeshes = meshes.length;
  25500. var index;
  25501. for (index = 0; index < numOfMeshes; index++) {
  25502. this.releaseForMesh(meshes[index]);
  25503. }
  25504. this._meshes = [];
  25505. for (var kind in this._vertexBuffers) {
  25506. this._vertexBuffers[kind].dispose();
  25507. }
  25508. this._vertexBuffers = [];
  25509. this._totalVertices = 0;
  25510. if (this._indexBuffer) {
  25511. this._engine._releaseBuffer(this._indexBuffer);
  25512. }
  25513. this._indexBuffer = null;
  25514. this._indices = [];
  25515. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25516. this.delayLoadingFile = null;
  25517. this._delayLoadingFunction = null;
  25518. this._delayInfo = [];
  25519. this._boundingInfo = null; // todo: .dispose()
  25520. var geometries = this._scene.getGeometries();
  25521. index = geometries.indexOf(this);
  25522. if (index > -1) {
  25523. geometries.splice(index, 1);
  25524. }
  25525. this._isDisposed = true;
  25526. };
  25527. Geometry.prototype.copy = function (id) {
  25528. var vertexData = new BABYLON.VertexData();
  25529. vertexData.indices = [];
  25530. var indices = this.getIndices();
  25531. for (var index = 0; index < indices.length; index++) {
  25532. vertexData.indices.push(indices[index]);
  25533. }
  25534. var updatable = false;
  25535. var stopChecking = false;
  25536. for (var kind in this._vertexBuffers) {
  25537. // using slice() to make a copy of the array and not just reference it
  25538. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25539. if (!stopChecking) {
  25540. updatable = this.getVertexBuffer(kind).isUpdatable();
  25541. stopChecking = !updatable;
  25542. }
  25543. }
  25544. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25545. geometry.delayLoadState = this.delayLoadState;
  25546. geometry.delayLoadingFile = this.delayLoadingFile;
  25547. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25548. for (kind in this._delayInfo) {
  25549. geometry._delayInfo = geometry._delayInfo || [];
  25550. geometry._delayInfo.push(kind);
  25551. }
  25552. // Bounding info
  25553. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25554. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25555. return geometry;
  25556. };
  25557. // Statics
  25558. Geometry.ExtractFromMesh = function (mesh, id) {
  25559. var geometry = mesh._geometry;
  25560. if (!geometry) {
  25561. return null;
  25562. }
  25563. return geometry.copy(id);
  25564. };
  25565. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25566. // be aware Math.random() could cause collisions
  25567. Geometry.RandomId = function () {
  25568. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25569. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25570. return v.toString(16);
  25571. });
  25572. };
  25573. return Geometry;
  25574. })();
  25575. BABYLON.Geometry = Geometry;
  25576. /////// Primitives //////////////////////////////////////////////
  25577. var Geometry;
  25578. (function (Geometry) {
  25579. var Primitives;
  25580. (function (Primitives) {
  25581. /// Abstract class
  25582. var _Primitive = (function (_super) {
  25583. __extends(_Primitive, _super);
  25584. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25585. this._beingRegenerated = true;
  25586. this._canBeRegenerated = canBeRegenerated;
  25587. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25588. this._beingRegenerated = false;
  25589. }
  25590. _Primitive.prototype.canBeRegenerated = function () {
  25591. return this._canBeRegenerated;
  25592. };
  25593. _Primitive.prototype.regenerate = function () {
  25594. if (!this._canBeRegenerated) {
  25595. return;
  25596. }
  25597. this._beingRegenerated = true;
  25598. this.setAllVerticesData(this._regenerateVertexData(), false);
  25599. this._beingRegenerated = false;
  25600. };
  25601. _Primitive.prototype.asNewGeometry = function (id) {
  25602. return _super.prototype.copy.call(this, id);
  25603. };
  25604. // overrides
  25605. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25606. if (!this._beingRegenerated) {
  25607. return;
  25608. }
  25609. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25610. };
  25611. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25612. if (!this._beingRegenerated) {
  25613. return;
  25614. }
  25615. _super.prototype.setVerticesData.call(this, kind, data, false);
  25616. };
  25617. // to override
  25618. // protected
  25619. _Primitive.prototype._regenerateVertexData = function () {
  25620. throw new Error("Abstract method");
  25621. };
  25622. _Primitive.prototype.copy = function (id) {
  25623. throw new Error("Must be overriden in sub-classes.");
  25624. };
  25625. return _Primitive;
  25626. })(Geometry);
  25627. Primitives._Primitive = _Primitive;
  25628. var Ribbon = (function (_super) {
  25629. __extends(Ribbon, _super);
  25630. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25631. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25632. this.pathArray = pathArray;
  25633. this.closeArray = closeArray;
  25634. this.closePath = closePath;
  25635. this.offset = offset;
  25636. this.side = side;
  25637. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25638. }
  25639. Ribbon.prototype._regenerateVertexData = function () {
  25640. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25641. };
  25642. Ribbon.prototype.copy = function (id) {
  25643. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25644. };
  25645. return Ribbon;
  25646. })(_Primitive);
  25647. Primitives.Ribbon = Ribbon;
  25648. var Box = (function (_super) {
  25649. __extends(Box, _super);
  25650. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25651. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25652. this.size = size;
  25653. this.side = side;
  25654. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25655. }
  25656. Box.prototype._regenerateVertexData = function () {
  25657. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25658. };
  25659. Box.prototype.copy = function (id) {
  25660. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25661. };
  25662. return Box;
  25663. })(_Primitive);
  25664. Primitives.Box = Box;
  25665. var Sphere = (function (_super) {
  25666. __extends(Sphere, _super);
  25667. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25669. this.segments = segments;
  25670. this.diameter = diameter;
  25671. this.side = side;
  25672. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25673. }
  25674. Sphere.prototype._regenerateVertexData = function () {
  25675. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25676. };
  25677. Sphere.prototype.copy = function (id) {
  25678. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25679. };
  25680. return Sphere;
  25681. })(_Primitive);
  25682. Primitives.Sphere = Sphere;
  25683. var Cylinder = (function (_super) {
  25684. __extends(Cylinder, _super);
  25685. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25686. if (subdivisions === void 0) { subdivisions = 1; }
  25687. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25688. this.height = height;
  25689. this.diameterTop = diameterTop;
  25690. this.diameterBottom = diameterBottom;
  25691. this.tessellation = tessellation;
  25692. this.subdivisions = subdivisions;
  25693. this.side = side;
  25694. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25695. }
  25696. Cylinder.prototype._regenerateVertexData = function () {
  25697. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25698. };
  25699. Cylinder.prototype.copy = function (id) {
  25700. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25701. };
  25702. return Cylinder;
  25703. })(_Primitive);
  25704. Primitives.Cylinder = Cylinder;
  25705. var Torus = (function (_super) {
  25706. __extends(Torus, _super);
  25707. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25709. this.diameter = diameter;
  25710. this.thickness = thickness;
  25711. this.tessellation = tessellation;
  25712. this.side = side;
  25713. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25714. }
  25715. Torus.prototype._regenerateVertexData = function () {
  25716. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25717. };
  25718. Torus.prototype.copy = function (id) {
  25719. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25720. };
  25721. return Torus;
  25722. })(_Primitive);
  25723. Primitives.Torus = Torus;
  25724. var Ground = (function (_super) {
  25725. __extends(Ground, _super);
  25726. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25727. this.width = width;
  25728. this.height = height;
  25729. this.subdivisions = subdivisions;
  25730. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25731. }
  25732. Ground.prototype._regenerateVertexData = function () {
  25733. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25734. };
  25735. Ground.prototype.copy = function (id) {
  25736. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25737. };
  25738. return Ground;
  25739. })(_Primitive);
  25740. Primitives.Ground = Ground;
  25741. var TiledGround = (function (_super) {
  25742. __extends(TiledGround, _super);
  25743. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25744. this.xmin = xmin;
  25745. this.zmin = zmin;
  25746. this.xmax = xmax;
  25747. this.zmax = zmax;
  25748. this.subdivisions = subdivisions;
  25749. this.precision = precision;
  25750. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25751. }
  25752. TiledGround.prototype._regenerateVertexData = function () {
  25753. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25754. };
  25755. TiledGround.prototype.copy = function (id) {
  25756. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25757. };
  25758. return TiledGround;
  25759. })(_Primitive);
  25760. Primitives.TiledGround = TiledGround;
  25761. var Plane = (function (_super) {
  25762. __extends(Plane, _super);
  25763. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25764. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25765. this.size = size;
  25766. this.side = side;
  25767. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25768. }
  25769. Plane.prototype._regenerateVertexData = function () {
  25770. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25771. };
  25772. Plane.prototype.copy = function (id) {
  25773. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25774. };
  25775. return Plane;
  25776. })(_Primitive);
  25777. Primitives.Plane = Plane;
  25778. var TorusKnot = (function (_super) {
  25779. __extends(TorusKnot, _super);
  25780. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25781. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25782. this.radius = radius;
  25783. this.tube = tube;
  25784. this.radialSegments = radialSegments;
  25785. this.tubularSegments = tubularSegments;
  25786. this.p = p;
  25787. this.q = q;
  25788. this.side = side;
  25789. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25790. }
  25791. TorusKnot.prototype._regenerateVertexData = function () {
  25792. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25793. };
  25794. TorusKnot.prototype.copy = function (id) {
  25795. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25796. };
  25797. return TorusKnot;
  25798. })(_Primitive);
  25799. Primitives.TorusKnot = TorusKnot;
  25800. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25801. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25802. })(BABYLON || (BABYLON = {}));
  25803. //# sourceMappingURL=babylon.geometry.js.map
  25804. var BABYLON;
  25805. (function (BABYLON) {
  25806. var Gamepads = (function () {
  25807. function Gamepads(ongamedpadconnected) {
  25808. var _this = this;
  25809. this.babylonGamepads = [];
  25810. this.oneGamepadConnected = false;
  25811. this.isMonitoring = false;
  25812. this.gamepadEventSupported = 'GamepadEvent' in window;
  25813. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25814. 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=";
  25815. this._callbackGamepadConnected = ongamedpadconnected;
  25816. if (this.gamepadSupportAvailable) {
  25817. // Checking if the gamepad connected event is supported (like in Firefox)
  25818. if (this.gamepadEventSupported) {
  25819. window.addEventListener('gamepadconnected', function (evt) {
  25820. _this._onGamepadConnected(evt);
  25821. }, false);
  25822. window.addEventListener('gamepaddisconnected', function (evt) {
  25823. _this._onGamepadDisconnected(evt);
  25824. }, false);
  25825. }
  25826. else {
  25827. this._startMonitoringGamepads();
  25828. }
  25829. if (!this.oneGamepadConnected) {
  25830. this._insertGamepadDOMInstructions();
  25831. }
  25832. }
  25833. else {
  25834. this._insertGamepadDOMNotSupported();
  25835. }
  25836. }
  25837. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25838. Gamepads.gamepadDOMInfo = document.createElement("div");
  25839. var buttonAImage = document.createElement("img");
  25840. buttonAImage.src = this.buttonADataURL;
  25841. var spanMessage = document.createElement("span");
  25842. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25843. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25844. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25845. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25846. Gamepads.gamepadDOMInfo.style.width = "100%";
  25847. Gamepads.gamepadDOMInfo.style.height = "48px";
  25848. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25849. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25850. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25851. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25852. buttonAImage.style.position = "relative";
  25853. buttonAImage.style.bottom = "8px";
  25854. spanMessage.style.position = "relative";
  25855. spanMessage.style.fontSize = "32px";
  25856. spanMessage.style.bottom = "32px";
  25857. spanMessage.style.color = "green";
  25858. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25859. };
  25860. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25861. Gamepads.gamepadDOMInfo = document.createElement("div");
  25862. var spanMessage = document.createElement("span");
  25863. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25864. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25865. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25866. Gamepads.gamepadDOMInfo.style.width = "100%";
  25867. Gamepads.gamepadDOMInfo.style.height = "40px";
  25868. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25869. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25870. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25871. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25872. spanMessage.style.position = "relative";
  25873. spanMessage.style.fontSize = "32px";
  25874. spanMessage.style.color = "red";
  25875. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25876. };
  25877. Gamepads.prototype.dispose = function () {
  25878. if (Gamepads.gamepadDOMInfo) {
  25879. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25880. }
  25881. };
  25882. Gamepads.prototype._onGamepadConnected = function (evt) {
  25883. var newGamepad = this._addNewGamepad(evt.gamepad);
  25884. if (this._callbackGamepadConnected)
  25885. this._callbackGamepadConnected(newGamepad);
  25886. this._startMonitoringGamepads();
  25887. };
  25888. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25889. if (!this.oneGamepadConnected) {
  25890. this.oneGamepadConnected = true;
  25891. if (Gamepads.gamepadDOMInfo) {
  25892. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25893. Gamepads.gamepadDOMInfo = null;
  25894. }
  25895. }
  25896. var newGamepad;
  25897. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25898. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25899. }
  25900. else {
  25901. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25902. }
  25903. this.babylonGamepads.push(newGamepad);
  25904. return newGamepad;
  25905. };
  25906. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25907. for (var i in this.babylonGamepads) {
  25908. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25909. this.babylonGamepads.splice(i, 1);
  25910. break;
  25911. }
  25912. }
  25913. // If no gamepads are left, stop the polling loop.
  25914. if (this.babylonGamepads.length == 0) {
  25915. this._stopMonitoringGamepads();
  25916. }
  25917. };
  25918. Gamepads.prototype._startMonitoringGamepads = function () {
  25919. if (!this.isMonitoring) {
  25920. this.isMonitoring = true;
  25921. this._checkGamepadsStatus();
  25922. }
  25923. };
  25924. Gamepads.prototype._stopMonitoringGamepads = function () {
  25925. this.isMonitoring = false;
  25926. };
  25927. Gamepads.prototype._checkGamepadsStatus = function () {
  25928. var _this = this;
  25929. // updating gamepad objects
  25930. this._updateGamepadObjects();
  25931. for (var i in this.babylonGamepads) {
  25932. this.babylonGamepads[i].update();
  25933. }
  25934. if (this.isMonitoring) {
  25935. if (window.requestAnimationFrame) {
  25936. window.requestAnimationFrame(function () {
  25937. _this._checkGamepadsStatus();
  25938. });
  25939. }
  25940. else if (window.mozRequestAnimationFrame) {
  25941. window.mozRequestAnimationFrame(function () {
  25942. _this._checkGamepadsStatus();
  25943. });
  25944. }
  25945. else if (window.webkitRequestAnimationFrame) {
  25946. window.webkitRequestAnimationFrame(function () {
  25947. _this._checkGamepadsStatus();
  25948. });
  25949. }
  25950. }
  25951. };
  25952. // This function is called only on Chrome, which does not yet support
  25953. // connection/disconnection events, but requires you to monitor
  25954. // an array for changes.
  25955. Gamepads.prototype._updateGamepadObjects = function () {
  25956. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25957. for (var i = 0; i < gamepads.length; i++) {
  25958. if (gamepads[i]) {
  25959. if (!(gamepads[i].index in this.babylonGamepads)) {
  25960. var newGamepad = this._addNewGamepad(gamepads[i]);
  25961. if (this._callbackGamepadConnected) {
  25962. this._callbackGamepadConnected(newGamepad);
  25963. }
  25964. }
  25965. else {
  25966. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25967. }
  25968. }
  25969. }
  25970. };
  25971. return Gamepads;
  25972. })();
  25973. BABYLON.Gamepads = Gamepads;
  25974. var StickValues = (function () {
  25975. function StickValues(x, y) {
  25976. this.x = x;
  25977. this.y = y;
  25978. }
  25979. return StickValues;
  25980. })();
  25981. BABYLON.StickValues = StickValues;
  25982. var Gamepad = (function () {
  25983. function Gamepad(id, index, browserGamepad) {
  25984. this.id = id;
  25985. this.index = index;
  25986. this.browserGamepad = browserGamepad;
  25987. if (this.browserGamepad.axes.length >= 2) {
  25988. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25989. }
  25990. if (this.browserGamepad.axes.length >= 4) {
  25991. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25992. }
  25993. }
  25994. Gamepad.prototype.onleftstickchanged = function (callback) {
  25995. this._onleftstickchanged = callback;
  25996. };
  25997. Gamepad.prototype.onrightstickchanged = function (callback) {
  25998. this._onrightstickchanged = callback;
  25999. };
  26000. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26001. get: function () {
  26002. return this._leftStick;
  26003. },
  26004. set: function (newValues) {
  26005. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26006. this._onleftstickchanged(newValues);
  26007. }
  26008. this._leftStick = newValues;
  26009. },
  26010. enumerable: true,
  26011. configurable: true
  26012. });
  26013. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26014. get: function () {
  26015. return this._rightStick;
  26016. },
  26017. set: function (newValues) {
  26018. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26019. this._onrightstickchanged(newValues);
  26020. }
  26021. this._rightStick = newValues;
  26022. },
  26023. enumerable: true,
  26024. configurable: true
  26025. });
  26026. Gamepad.prototype.update = function () {
  26027. if (this._leftStick) {
  26028. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26029. }
  26030. if (this._rightStick) {
  26031. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26032. }
  26033. };
  26034. return Gamepad;
  26035. })();
  26036. BABYLON.Gamepad = Gamepad;
  26037. var GenericPad = (function (_super) {
  26038. __extends(GenericPad, _super);
  26039. function GenericPad(id, index, gamepad) {
  26040. _super.call(this, id, index, gamepad);
  26041. this.id = id;
  26042. this.index = index;
  26043. this.gamepad = gamepad;
  26044. this._buttons = new Array(gamepad.buttons.length);
  26045. }
  26046. GenericPad.prototype.onbuttondown = function (callback) {
  26047. this._onbuttondown = callback;
  26048. };
  26049. GenericPad.prototype.onbuttonup = function (callback) {
  26050. this._onbuttonup = callback;
  26051. };
  26052. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26053. if (newValue !== currentValue) {
  26054. if (this._onbuttondown && newValue === 1) {
  26055. this._onbuttondown(buttonIndex);
  26056. }
  26057. if (this._onbuttonup && newValue === 0) {
  26058. this._onbuttonup(buttonIndex);
  26059. }
  26060. }
  26061. return newValue;
  26062. };
  26063. GenericPad.prototype.update = function () {
  26064. _super.prototype.update.call(this);
  26065. for (var index = 0; index < this._buttons.length; index++) {
  26066. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26067. }
  26068. };
  26069. return GenericPad;
  26070. })(Gamepad);
  26071. BABYLON.GenericPad = GenericPad;
  26072. (function (Xbox360Button) {
  26073. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26074. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26075. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26076. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26077. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26078. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26079. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26080. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26081. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26082. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26083. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26084. var Xbox360Button = BABYLON.Xbox360Button;
  26085. (function (Xbox360Dpad) {
  26086. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26087. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26088. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26089. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26090. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26091. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26092. var Xbox360Pad = (function (_super) {
  26093. __extends(Xbox360Pad, _super);
  26094. function Xbox360Pad() {
  26095. _super.apply(this, arguments);
  26096. this._leftTrigger = 0;
  26097. this._rightTrigger = 0;
  26098. this._buttonA = 0;
  26099. this._buttonB = 0;
  26100. this._buttonX = 0;
  26101. this._buttonY = 0;
  26102. this._buttonBack = 0;
  26103. this._buttonStart = 0;
  26104. this._buttonLB = 0;
  26105. this._buttonRB = 0;
  26106. this._buttonLeftStick = 0;
  26107. this._buttonRightStick = 0;
  26108. this._dPadUp = 0;
  26109. this._dPadDown = 0;
  26110. this._dPadLeft = 0;
  26111. this._dPadRight = 0;
  26112. }
  26113. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26114. this._onlefttriggerchanged = callback;
  26115. };
  26116. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26117. this._onrighttriggerchanged = callback;
  26118. };
  26119. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26120. get: function () {
  26121. return this._leftTrigger;
  26122. },
  26123. set: function (newValue) {
  26124. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26125. this._onlefttriggerchanged(newValue);
  26126. }
  26127. this._leftTrigger = newValue;
  26128. },
  26129. enumerable: true,
  26130. configurable: true
  26131. });
  26132. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26133. get: function () {
  26134. return this._rightTrigger;
  26135. },
  26136. set: function (newValue) {
  26137. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26138. this._onrighttriggerchanged(newValue);
  26139. }
  26140. this._rightTrigger = newValue;
  26141. },
  26142. enumerable: true,
  26143. configurable: true
  26144. });
  26145. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26146. this._onbuttondown = callback;
  26147. };
  26148. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26149. this._onbuttonup = callback;
  26150. };
  26151. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26152. this._ondpaddown = callback;
  26153. };
  26154. Xbox360Pad.prototype.ondpadup = function (callback) {
  26155. this._ondpadup = callback;
  26156. };
  26157. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26158. if (newValue !== currentValue) {
  26159. if (this._onbuttondown && newValue === 1) {
  26160. this._onbuttondown(buttonType);
  26161. }
  26162. if (this._onbuttonup && newValue === 0) {
  26163. this._onbuttonup(buttonType);
  26164. }
  26165. }
  26166. return newValue;
  26167. };
  26168. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26169. if (newValue !== currentValue) {
  26170. if (this._ondpaddown && newValue === 1) {
  26171. this._ondpaddown(buttonType);
  26172. }
  26173. if (this._ondpadup && newValue === 0) {
  26174. this._ondpadup(buttonType);
  26175. }
  26176. }
  26177. return newValue;
  26178. };
  26179. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26180. get: function () {
  26181. return this._buttonA;
  26182. },
  26183. set: function (value) {
  26184. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26190. get: function () {
  26191. return this._buttonB;
  26192. },
  26193. set: function (value) {
  26194. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26195. },
  26196. enumerable: true,
  26197. configurable: true
  26198. });
  26199. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26200. get: function () {
  26201. return this._buttonX;
  26202. },
  26203. set: function (value) {
  26204. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26205. },
  26206. enumerable: true,
  26207. configurable: true
  26208. });
  26209. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26210. get: function () {
  26211. return this._buttonY;
  26212. },
  26213. set: function (value) {
  26214. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26215. },
  26216. enumerable: true,
  26217. configurable: true
  26218. });
  26219. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26220. get: function () {
  26221. return this._buttonStart;
  26222. },
  26223. set: function (value) {
  26224. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26225. },
  26226. enumerable: true,
  26227. configurable: true
  26228. });
  26229. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26230. get: function () {
  26231. return this._buttonBack;
  26232. },
  26233. set: function (value) {
  26234. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26235. },
  26236. enumerable: true,
  26237. configurable: true
  26238. });
  26239. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26240. get: function () {
  26241. return this._buttonLB;
  26242. },
  26243. set: function (value) {
  26244. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26245. },
  26246. enumerable: true,
  26247. configurable: true
  26248. });
  26249. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26250. get: function () {
  26251. return this._buttonRB;
  26252. },
  26253. set: function (value) {
  26254. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26255. },
  26256. enumerable: true,
  26257. configurable: true
  26258. });
  26259. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26260. get: function () {
  26261. return this._buttonLeftStick;
  26262. },
  26263. set: function (value) {
  26264. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26265. },
  26266. enumerable: true,
  26267. configurable: true
  26268. });
  26269. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26270. get: function () {
  26271. return this._buttonRightStick;
  26272. },
  26273. set: function (value) {
  26274. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26275. },
  26276. enumerable: true,
  26277. configurable: true
  26278. });
  26279. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26280. get: function () {
  26281. return this._dPadUp;
  26282. },
  26283. set: function (value) {
  26284. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26285. },
  26286. enumerable: true,
  26287. configurable: true
  26288. });
  26289. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26290. get: function () {
  26291. return this._dPadDown;
  26292. },
  26293. set: function (value) {
  26294. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26295. },
  26296. enumerable: true,
  26297. configurable: true
  26298. });
  26299. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26300. get: function () {
  26301. return this._dPadLeft;
  26302. },
  26303. set: function (value) {
  26304. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26305. },
  26306. enumerable: true,
  26307. configurable: true
  26308. });
  26309. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26310. get: function () {
  26311. return this._dPadRight;
  26312. },
  26313. set: function (value) {
  26314. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26315. },
  26316. enumerable: true,
  26317. configurable: true
  26318. });
  26319. Xbox360Pad.prototype.update = function () {
  26320. _super.prototype.update.call(this);
  26321. this.buttonA = this.browserGamepad.buttons[0].value;
  26322. this.buttonB = this.browserGamepad.buttons[1].value;
  26323. this.buttonX = this.browserGamepad.buttons[2].value;
  26324. this.buttonY = this.browserGamepad.buttons[3].value;
  26325. this.buttonLB = this.browserGamepad.buttons[4].value;
  26326. this.buttonRB = this.browserGamepad.buttons[5].value;
  26327. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26328. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26329. this.buttonBack = this.browserGamepad.buttons[8].value;
  26330. this.buttonStart = this.browserGamepad.buttons[9].value;
  26331. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26332. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26333. this.dPadUp = this.browserGamepad.buttons[12].value;
  26334. this.dPadDown = this.browserGamepad.buttons[13].value;
  26335. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26336. this.dPadRight = this.browserGamepad.buttons[15].value;
  26337. };
  26338. return Xbox360Pad;
  26339. })(Gamepad);
  26340. BABYLON.Xbox360Pad = Xbox360Pad;
  26341. })(BABYLON || (BABYLON = {}));
  26342. //# sourceMappingURL=babylon.gamepads.js.map
  26343. var BABYLON;
  26344. (function (BABYLON) {
  26345. // We're mainly based on the logic defined into the FreeCamera code
  26346. var GamepadCamera = (function (_super) {
  26347. __extends(GamepadCamera, _super);
  26348. function GamepadCamera(name, position, scene) {
  26349. var _this = this;
  26350. _super.call(this, name, position, scene);
  26351. this.angularSensibility = 200;
  26352. this.moveSensibility = 75;
  26353. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26354. _this._onNewGameConnected(gamepad);
  26355. });
  26356. }
  26357. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26358. // Only the first gamepad can control the camera
  26359. if (gamepad.index === 0) {
  26360. this._gamepad = gamepad;
  26361. }
  26362. };
  26363. GamepadCamera.prototype._checkInputs = function () {
  26364. if (!this._gamepad) {
  26365. return;
  26366. }
  26367. var LSValues = this._gamepad.leftStick;
  26368. var normalizedLX = LSValues.x / this.moveSensibility;
  26369. var normalizedLY = LSValues.y / this.moveSensibility;
  26370. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26371. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26372. var RSValues = this._gamepad.rightStick;
  26373. var normalizedRX = RSValues.x / this.angularSensibility;
  26374. var normalizedRY = RSValues.y / this.angularSensibility;
  26375. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26376. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26377. ;
  26378. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26379. var speed = this._computeLocalCameraSpeed() * 50.0;
  26380. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26381. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26382. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26383. };
  26384. GamepadCamera.prototype.dispose = function () {
  26385. this._gamepads.dispose();
  26386. _super.prototype.dispose.call(this);
  26387. };
  26388. return GamepadCamera;
  26389. })(BABYLON.FreeCamera);
  26390. BABYLON.GamepadCamera = GamepadCamera;
  26391. })(BABYLON || (BABYLON = {}));
  26392. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26393. var BABYLON;
  26394. (function (BABYLON) {
  26395. var LinesMesh = (function (_super) {
  26396. __extends(LinesMesh, _super);
  26397. function LinesMesh(name, scene, updatable) {
  26398. if (updatable === void 0) { updatable = false; }
  26399. _super.call(this, name, scene);
  26400. this.color = new BABYLON.Color3(1, 1, 1);
  26401. this.alpha = 1;
  26402. this._indices = new Array();
  26403. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26404. attributes: ["position"],
  26405. uniforms: ["worldViewProjection", "color"],
  26406. needAlphaBlending: true
  26407. });
  26408. }
  26409. Object.defineProperty(LinesMesh.prototype, "material", {
  26410. get: function () {
  26411. return this._colorShader;
  26412. },
  26413. enumerable: true,
  26414. configurable: true
  26415. });
  26416. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26417. get: function () {
  26418. return false;
  26419. },
  26420. enumerable: true,
  26421. configurable: true
  26422. });
  26423. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26424. get: function () {
  26425. return false;
  26426. },
  26427. enumerable: true,
  26428. configurable: true
  26429. });
  26430. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26431. var engine = this.getScene().getEngine();
  26432. var indexToBind = this._geometry.getIndexBuffer();
  26433. // VBOs
  26434. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26435. // Color
  26436. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26437. };
  26438. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26439. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26440. return;
  26441. }
  26442. var engine = this.getScene().getEngine();
  26443. // Draw order
  26444. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26445. };
  26446. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26447. return null;
  26448. };
  26449. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26450. this._colorShader.dispose();
  26451. _super.prototype.dispose.call(this, doNotRecurse);
  26452. };
  26453. return LinesMesh;
  26454. })(BABYLON.Mesh);
  26455. BABYLON.LinesMesh = LinesMesh;
  26456. })(BABYLON || (BABYLON = {}));
  26457. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26458. (function (BABYLON) {
  26459. var OutlineRenderer = (function () {
  26460. function OutlineRenderer(scene) {
  26461. this._scene = scene;
  26462. }
  26463. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26464. var _this = this;
  26465. if (useOverlay === void 0) { useOverlay = false; }
  26466. var scene = this._scene;
  26467. var engine = this._scene.getEngine();
  26468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26469. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26470. return;
  26471. }
  26472. var mesh = subMesh.getRenderingMesh();
  26473. var material = subMesh.getMaterial();
  26474. engine.enableEffect(this._effect);
  26475. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26476. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26477. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26478. // Bones
  26479. if (mesh.useBones) {
  26480. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26481. }
  26482. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26483. // Alpha test
  26484. if (material && material.needAlphaTesting()) {
  26485. var alphaTexture = material.getAlphaTestTexture();
  26486. this._effect.setTexture("diffuseSampler", alphaTexture);
  26487. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26488. }
  26489. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26490. _this._effect.setMatrix("world", world);
  26491. });
  26492. };
  26493. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26494. var defines = [];
  26495. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26496. var mesh = subMesh.getMesh();
  26497. var material = subMesh.getMaterial();
  26498. // Alpha test
  26499. if (material && material.needAlphaTesting()) {
  26500. defines.push("#define ALPHATEST");
  26501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26502. attribs.push(BABYLON.VertexBuffer.UVKind);
  26503. defines.push("#define UV1");
  26504. }
  26505. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26506. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26507. defines.push("#define UV2");
  26508. }
  26509. }
  26510. // Bones
  26511. if (mesh.useBones) {
  26512. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26513. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26514. defines.push("#define BONES");
  26515. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26516. }
  26517. // Instances
  26518. if (useInstances) {
  26519. defines.push("#define INSTANCES");
  26520. attribs.push("world0");
  26521. attribs.push("world1");
  26522. attribs.push("world2");
  26523. attribs.push("world3");
  26524. }
  26525. // Get correct effect
  26526. var join = defines.join("\n");
  26527. if (this._cachedDefines !== join) {
  26528. this._cachedDefines = join;
  26529. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26530. }
  26531. return this._effect.isReady();
  26532. };
  26533. return OutlineRenderer;
  26534. })();
  26535. BABYLON.OutlineRenderer = OutlineRenderer;
  26536. })(BABYLON || (BABYLON = {}));
  26537. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26538. (function (BABYLON) {
  26539. var MeshAssetTask = (function () {
  26540. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26541. this.name = name;
  26542. this.meshesNames = meshesNames;
  26543. this.rootUrl = rootUrl;
  26544. this.sceneFilename = sceneFilename;
  26545. this.isCompleted = false;
  26546. }
  26547. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26548. var _this = this;
  26549. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26550. _this.loadedMeshes = meshes;
  26551. _this.loadedParticleSystems = particleSystems;
  26552. _this.loadedSkeletons = skeletons;
  26553. _this.isCompleted = true;
  26554. if (_this.onSuccess) {
  26555. _this.onSuccess(_this);
  26556. }
  26557. onSuccess();
  26558. }, null, function () {
  26559. if (_this.onError) {
  26560. _this.onError(_this);
  26561. }
  26562. onError();
  26563. });
  26564. };
  26565. return MeshAssetTask;
  26566. })();
  26567. BABYLON.MeshAssetTask = MeshAssetTask;
  26568. var TextFileAssetTask = (function () {
  26569. function TextFileAssetTask(name, url) {
  26570. this.name = name;
  26571. this.url = url;
  26572. this.isCompleted = false;
  26573. }
  26574. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26575. var _this = this;
  26576. BABYLON.Tools.LoadFile(this.url, function (data) {
  26577. _this.text = data;
  26578. _this.isCompleted = true;
  26579. if (_this.onSuccess) {
  26580. _this.onSuccess(_this);
  26581. }
  26582. onSuccess();
  26583. }, null, scene.database, false, function () {
  26584. if (_this.onError) {
  26585. _this.onError(_this);
  26586. }
  26587. onError();
  26588. });
  26589. };
  26590. return TextFileAssetTask;
  26591. })();
  26592. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26593. var BinaryFileAssetTask = (function () {
  26594. function BinaryFileAssetTask(name, url) {
  26595. this.name = name;
  26596. this.url = url;
  26597. this.isCompleted = false;
  26598. }
  26599. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26600. var _this = this;
  26601. BABYLON.Tools.LoadFile(this.url, function (data) {
  26602. _this.data = data;
  26603. _this.isCompleted = true;
  26604. if (_this.onSuccess) {
  26605. _this.onSuccess(_this);
  26606. }
  26607. onSuccess();
  26608. }, null, scene.database, true, function () {
  26609. if (_this.onError) {
  26610. _this.onError(_this);
  26611. }
  26612. onError();
  26613. });
  26614. };
  26615. return BinaryFileAssetTask;
  26616. })();
  26617. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26618. var ImageAssetTask = (function () {
  26619. function ImageAssetTask(name, url) {
  26620. this.name = name;
  26621. this.url = url;
  26622. this.isCompleted = false;
  26623. }
  26624. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26625. var _this = this;
  26626. var img = new Image();
  26627. img.onload = function () {
  26628. _this.image = img;
  26629. _this.isCompleted = true;
  26630. if (_this.onSuccess) {
  26631. _this.onSuccess(_this);
  26632. }
  26633. onSuccess();
  26634. };
  26635. img.onerror = function () {
  26636. if (_this.onError) {
  26637. _this.onError(_this);
  26638. }
  26639. onError();
  26640. };
  26641. img.src = this.url;
  26642. };
  26643. return ImageAssetTask;
  26644. })();
  26645. BABYLON.ImageAssetTask = ImageAssetTask;
  26646. var TextureAssetTask = (function () {
  26647. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26649. this.name = name;
  26650. this.url = url;
  26651. this.noMipmap = noMipmap;
  26652. this.invertY = invertY;
  26653. this.samplingMode = samplingMode;
  26654. this.isCompleted = false;
  26655. }
  26656. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26657. var _this = this;
  26658. var onload = function () {
  26659. _this.isCompleted = true;
  26660. if (_this.onSuccess) {
  26661. _this.onSuccess(_this);
  26662. }
  26663. onSuccess();
  26664. };
  26665. var onerror = function () {
  26666. if (_this.onError) {
  26667. _this.onError(_this);
  26668. }
  26669. onError();
  26670. };
  26671. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26672. };
  26673. return TextureAssetTask;
  26674. })();
  26675. BABYLON.TextureAssetTask = TextureAssetTask;
  26676. var AssetsManager = (function () {
  26677. function AssetsManager(scene) {
  26678. this._tasks = new Array();
  26679. this._waitingTasksCount = 0;
  26680. this.useDefaultLoadingScreen = true;
  26681. this._scene = scene;
  26682. }
  26683. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26684. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26685. this._tasks.push(task);
  26686. return task;
  26687. };
  26688. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26689. var task = new TextFileAssetTask(taskName, url);
  26690. this._tasks.push(task);
  26691. return task;
  26692. };
  26693. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26694. var task = new BinaryFileAssetTask(taskName, url);
  26695. this._tasks.push(task);
  26696. return task;
  26697. };
  26698. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26699. var task = new ImageAssetTask(taskName, url);
  26700. this._tasks.push(task);
  26701. return task;
  26702. };
  26703. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26705. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26706. this._tasks.push(task);
  26707. return task;
  26708. };
  26709. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26710. this._waitingTasksCount--;
  26711. if (this._waitingTasksCount === 0) {
  26712. if (this.onFinish) {
  26713. this.onFinish(this._tasks);
  26714. }
  26715. this._scene.getEngine().hideLoadingUI();
  26716. }
  26717. };
  26718. AssetsManager.prototype._runTask = function (task) {
  26719. var _this = this;
  26720. task.run(this._scene, function () {
  26721. if (_this.onTaskSuccess) {
  26722. _this.onTaskSuccess(task);
  26723. }
  26724. _this._decreaseWaitingTasksCount();
  26725. }, function () {
  26726. if (_this.onTaskError) {
  26727. _this.onTaskError(task);
  26728. }
  26729. _this._decreaseWaitingTasksCount();
  26730. });
  26731. };
  26732. AssetsManager.prototype.reset = function () {
  26733. this._tasks = new Array();
  26734. return this;
  26735. };
  26736. AssetsManager.prototype.load = function () {
  26737. this._waitingTasksCount = this._tasks.length;
  26738. if (this._waitingTasksCount === 0) {
  26739. if (this.onFinish) {
  26740. this.onFinish(this._tasks);
  26741. }
  26742. return this;
  26743. }
  26744. if (this.useDefaultLoadingScreen) {
  26745. this._scene.getEngine().displayLoadingUI();
  26746. }
  26747. for (var index = 0; index < this._tasks.length; index++) {
  26748. var task = this._tasks[index];
  26749. this._runTask(task);
  26750. }
  26751. return this;
  26752. };
  26753. return AssetsManager;
  26754. })();
  26755. BABYLON.AssetsManager = AssetsManager;
  26756. })(BABYLON || (BABYLON = {}));
  26757. //# sourceMappingURL=babylon.assetsManager.js.map
  26758. var BABYLON;
  26759. (function (BABYLON) {
  26760. var VRDeviceOrientationCamera = (function (_super) {
  26761. __extends(VRDeviceOrientationCamera, _super);
  26762. function VRDeviceOrientationCamera(name, position, scene) {
  26763. _super.call(this, name, position, scene);
  26764. this._alpha = 0;
  26765. this._beta = 0;
  26766. this._gamma = 0;
  26767. }
  26768. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26769. this._alpha = +evt.alpha | 0;
  26770. this._beta = +evt.beta | 0;
  26771. this._gamma = +evt.gamma | 0;
  26772. if (this._gamma < 0) {
  26773. this._gamma = 90 + this._gamma;
  26774. }
  26775. else {
  26776. // Incline it in the correct angle.
  26777. this._gamma = 270 - this._gamma;
  26778. }
  26779. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26780. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26781. this.rotation.z = this._beta / 180.0 * Math.PI;
  26782. };
  26783. return VRDeviceOrientationCamera;
  26784. })(BABYLON.OculusCamera);
  26785. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26786. })(BABYLON || (BABYLON = {}));
  26787. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26788. var BABYLON;
  26789. (function (BABYLON) {
  26790. var WebVRCamera = (function (_super) {
  26791. __extends(WebVRCamera, _super);
  26792. function WebVRCamera(name, position, scene) {
  26793. _super.call(this, name, position, scene);
  26794. this._hmdDevice = null;
  26795. this._sensorDevice = null;
  26796. this._cacheState = null;
  26797. this._cacheQuaternion = new BABYLON.Quaternion();
  26798. this._cacheRotation = BABYLON.Vector3.Zero();
  26799. this._vrEnabled = false;
  26800. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26801. }
  26802. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26803. var size = devices.length;
  26804. var i = 0;
  26805. // Reset devices.
  26806. this._sensorDevice = null;
  26807. this._hmdDevice = null;
  26808. while (i < size && this._hmdDevice === null) {
  26809. if (devices[i] instanceof HMDVRDevice) {
  26810. this._hmdDevice = devices[i];
  26811. }
  26812. i++;
  26813. }
  26814. i = 0;
  26815. while (i < size && this._sensorDevice === null) {
  26816. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26817. this._sensorDevice = devices[i];
  26818. }
  26819. i++;
  26820. }
  26821. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26822. };
  26823. WebVRCamera.prototype._update = function () {
  26824. if (this._vrEnabled) {
  26825. this._cacheState = this._sensorDevice.getState();
  26826. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26827. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26828. this.rotation.x = -this._cacheRotation.z;
  26829. this.rotation.y = -this._cacheRotation.y;
  26830. this.rotation.z = this._cacheRotation.x;
  26831. }
  26832. _super.prototype._update.call(this);
  26833. };
  26834. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26835. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26836. if (navigator.getVRDevices) {
  26837. navigator.getVRDevices().then(this._getWebVRDevices);
  26838. }
  26839. else if (navigator.mozGetVRDevices) {
  26840. navigator.mozGetVRDevices(this._getWebVRDevices);
  26841. }
  26842. };
  26843. WebVRCamera.prototype.detachControl = function (element) {
  26844. _super.prototype.detachControl.call(this, element);
  26845. this._vrEnabled = false;
  26846. };
  26847. return WebVRCamera;
  26848. })(BABYLON.OculusCamera);
  26849. BABYLON.WebVRCamera = WebVRCamera;
  26850. })(BABYLON || (BABYLON = {}));
  26851. //# sourceMappingURL=babylon.webVRCamera.js.map
  26852. var BABYLON;
  26853. (function (BABYLON) {
  26854. // Standard optimizations
  26855. var SceneOptimization = (function () {
  26856. function SceneOptimization(priority) {
  26857. if (priority === void 0) { priority = 0; }
  26858. this.priority = priority;
  26859. this.apply = function (scene) {
  26860. return true; // Return true if everything that can be done was applied
  26861. };
  26862. }
  26863. return SceneOptimization;
  26864. })();
  26865. BABYLON.SceneOptimization = SceneOptimization;
  26866. var TextureOptimization = (function (_super) {
  26867. __extends(TextureOptimization, _super);
  26868. function TextureOptimization(priority, maximumSize) {
  26869. var _this = this;
  26870. if (priority === void 0) { priority = 0; }
  26871. if (maximumSize === void 0) { maximumSize = 1024; }
  26872. _super.call(this, priority);
  26873. this.priority = priority;
  26874. this.maximumSize = maximumSize;
  26875. this.apply = function (scene) {
  26876. var allDone = true;
  26877. for (var index = 0; index < scene.textures.length; index++) {
  26878. var texture = scene.textures[index];
  26879. if (!texture.canRescale) {
  26880. continue;
  26881. }
  26882. var currentSize = texture.getSize();
  26883. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26884. if (maxDimension > _this.maximumSize) {
  26885. texture.scale(0.5);
  26886. allDone = false;
  26887. }
  26888. }
  26889. return allDone;
  26890. };
  26891. }
  26892. return TextureOptimization;
  26893. })(SceneOptimization);
  26894. BABYLON.TextureOptimization = TextureOptimization;
  26895. var HardwareScalingOptimization = (function (_super) {
  26896. __extends(HardwareScalingOptimization, _super);
  26897. function HardwareScalingOptimization(priority, maximumScale) {
  26898. var _this = this;
  26899. if (priority === void 0) { priority = 0; }
  26900. if (maximumScale === void 0) { maximumScale = 2; }
  26901. _super.call(this, priority);
  26902. this.priority = priority;
  26903. this.maximumScale = maximumScale;
  26904. this._currentScale = 1;
  26905. this.apply = function (scene) {
  26906. _this._currentScale++;
  26907. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26908. return _this._currentScale >= _this.maximumScale;
  26909. };
  26910. }
  26911. return HardwareScalingOptimization;
  26912. })(SceneOptimization);
  26913. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26914. var ShadowsOptimization = (function (_super) {
  26915. __extends(ShadowsOptimization, _super);
  26916. function ShadowsOptimization() {
  26917. _super.apply(this, arguments);
  26918. this.apply = function (scene) {
  26919. scene.shadowsEnabled = false;
  26920. return true;
  26921. };
  26922. }
  26923. return ShadowsOptimization;
  26924. })(SceneOptimization);
  26925. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26926. var PostProcessesOptimization = (function (_super) {
  26927. __extends(PostProcessesOptimization, _super);
  26928. function PostProcessesOptimization() {
  26929. _super.apply(this, arguments);
  26930. this.apply = function (scene) {
  26931. scene.postProcessesEnabled = false;
  26932. return true;
  26933. };
  26934. }
  26935. return PostProcessesOptimization;
  26936. })(SceneOptimization);
  26937. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26938. var LensFlaresOptimization = (function (_super) {
  26939. __extends(LensFlaresOptimization, _super);
  26940. function LensFlaresOptimization() {
  26941. _super.apply(this, arguments);
  26942. this.apply = function (scene) {
  26943. scene.lensFlaresEnabled = false;
  26944. return true;
  26945. };
  26946. }
  26947. return LensFlaresOptimization;
  26948. })(SceneOptimization);
  26949. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26950. var ParticlesOptimization = (function (_super) {
  26951. __extends(ParticlesOptimization, _super);
  26952. function ParticlesOptimization() {
  26953. _super.apply(this, arguments);
  26954. this.apply = function (scene) {
  26955. scene.particlesEnabled = false;
  26956. return true;
  26957. };
  26958. }
  26959. return ParticlesOptimization;
  26960. })(SceneOptimization);
  26961. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26962. var RenderTargetsOptimization = (function (_super) {
  26963. __extends(RenderTargetsOptimization, _super);
  26964. function RenderTargetsOptimization() {
  26965. _super.apply(this, arguments);
  26966. this.apply = function (scene) {
  26967. scene.renderTargetsEnabled = false;
  26968. return true;
  26969. };
  26970. }
  26971. return RenderTargetsOptimization;
  26972. })(SceneOptimization);
  26973. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26974. var MergeMeshesOptimization = (function (_super) {
  26975. __extends(MergeMeshesOptimization, _super);
  26976. function MergeMeshesOptimization() {
  26977. var _this = this;
  26978. _super.apply(this, arguments);
  26979. this._canBeMerged = function (abstractMesh) {
  26980. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26981. return false;
  26982. }
  26983. var mesh = abstractMesh;
  26984. if (!mesh.isVisible || !mesh.isEnabled()) {
  26985. return false;
  26986. }
  26987. if (mesh.instances.length > 0) {
  26988. return false;
  26989. }
  26990. if (mesh.skeleton || mesh.hasLODLevels) {
  26991. return false;
  26992. }
  26993. return true;
  26994. };
  26995. this.apply = function (scene) {
  26996. var globalPool = scene.meshes.slice(0);
  26997. var globalLength = globalPool.length;
  26998. for (var index = 0; index < globalLength; index++) {
  26999. var currentPool = new Array();
  27000. var current = globalPool[index];
  27001. // Checks
  27002. if (!_this._canBeMerged(current)) {
  27003. continue;
  27004. }
  27005. currentPool.push(current);
  27006. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27007. var otherMesh = globalPool[subIndex];
  27008. if (!_this._canBeMerged(otherMesh)) {
  27009. continue;
  27010. }
  27011. if (otherMesh.material !== current.material) {
  27012. continue;
  27013. }
  27014. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27015. continue;
  27016. }
  27017. currentPool.push(otherMesh);
  27018. globalLength--;
  27019. globalPool.splice(subIndex, 1);
  27020. subIndex--;
  27021. }
  27022. if (currentPool.length < 2) {
  27023. continue;
  27024. }
  27025. // Merge meshes
  27026. BABYLON.Mesh.MergeMeshes(currentPool);
  27027. }
  27028. return true;
  27029. };
  27030. }
  27031. return MergeMeshesOptimization;
  27032. })(SceneOptimization);
  27033. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27034. // Options
  27035. var SceneOptimizerOptions = (function () {
  27036. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27037. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27038. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27039. this.targetFrameRate = targetFrameRate;
  27040. this.trackerDuration = trackerDuration;
  27041. this.optimizations = new Array();
  27042. }
  27043. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27044. var result = new SceneOptimizerOptions(targetFrameRate);
  27045. var priority = 0;
  27046. result.optimizations.push(new MergeMeshesOptimization(priority));
  27047. result.optimizations.push(new ShadowsOptimization(priority));
  27048. result.optimizations.push(new LensFlaresOptimization(priority));
  27049. // Next priority
  27050. priority++;
  27051. result.optimizations.push(new PostProcessesOptimization(priority));
  27052. result.optimizations.push(new ParticlesOptimization(priority));
  27053. // Next priority
  27054. priority++;
  27055. result.optimizations.push(new TextureOptimization(priority, 1024));
  27056. return result;
  27057. };
  27058. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27059. var result = new SceneOptimizerOptions(targetFrameRate);
  27060. var priority = 0;
  27061. result.optimizations.push(new MergeMeshesOptimization(priority));
  27062. result.optimizations.push(new ShadowsOptimization(priority));
  27063. result.optimizations.push(new LensFlaresOptimization(priority));
  27064. // Next priority
  27065. priority++;
  27066. result.optimizations.push(new PostProcessesOptimization(priority));
  27067. result.optimizations.push(new ParticlesOptimization(priority));
  27068. // Next priority
  27069. priority++;
  27070. result.optimizations.push(new TextureOptimization(priority, 512));
  27071. // Next priority
  27072. priority++;
  27073. result.optimizations.push(new RenderTargetsOptimization(priority));
  27074. // Next priority
  27075. priority++;
  27076. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27077. return result;
  27078. };
  27079. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27080. var result = new SceneOptimizerOptions(targetFrameRate);
  27081. var priority = 0;
  27082. result.optimizations.push(new MergeMeshesOptimization(priority));
  27083. result.optimizations.push(new ShadowsOptimization(priority));
  27084. result.optimizations.push(new LensFlaresOptimization(priority));
  27085. // Next priority
  27086. priority++;
  27087. result.optimizations.push(new PostProcessesOptimization(priority));
  27088. result.optimizations.push(new ParticlesOptimization(priority));
  27089. // Next priority
  27090. priority++;
  27091. result.optimizations.push(new TextureOptimization(priority, 256));
  27092. // Next priority
  27093. priority++;
  27094. result.optimizations.push(new RenderTargetsOptimization(priority));
  27095. // Next priority
  27096. priority++;
  27097. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27098. return result;
  27099. };
  27100. return SceneOptimizerOptions;
  27101. })();
  27102. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27103. // Scene optimizer tool
  27104. var SceneOptimizer = (function () {
  27105. function SceneOptimizer() {
  27106. }
  27107. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27108. // TODO: add an epsilon
  27109. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27110. if (onSuccess) {
  27111. onSuccess();
  27112. }
  27113. return;
  27114. }
  27115. // Apply current level of optimizations
  27116. var allDone = true;
  27117. var noOptimizationApplied = true;
  27118. for (var index = 0; index < options.optimizations.length; index++) {
  27119. var optimization = options.optimizations[index];
  27120. if (optimization.priority === currentPriorityLevel) {
  27121. noOptimizationApplied = false;
  27122. allDone = allDone && optimization.apply(scene);
  27123. }
  27124. }
  27125. // If no optimization was applied, this is a failure :(
  27126. if (noOptimizationApplied) {
  27127. if (onFailure) {
  27128. onFailure();
  27129. }
  27130. return;
  27131. }
  27132. // If all optimizations were done, move to next level
  27133. if (allDone) {
  27134. currentPriorityLevel++;
  27135. }
  27136. // Let's the system running for a specific amount of time before checking FPS
  27137. scene.executeWhenReady(function () {
  27138. setTimeout(function () {
  27139. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27140. }, options.trackerDuration);
  27141. });
  27142. };
  27143. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27144. if (!options) {
  27145. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27146. }
  27147. // Let's the system running for a specific amount of time before checking FPS
  27148. scene.executeWhenReady(function () {
  27149. setTimeout(function () {
  27150. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27151. }, options.trackerDuration);
  27152. });
  27153. };
  27154. return SceneOptimizer;
  27155. })();
  27156. BABYLON.SceneOptimizer = SceneOptimizer;
  27157. })(BABYLON || (BABYLON = {}));
  27158. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27159. (function (BABYLON) {
  27160. var Internals;
  27161. (function (Internals) {
  27162. var MeshLODLevel = (function () {
  27163. function MeshLODLevel(distance, mesh) {
  27164. this.distance = distance;
  27165. this.mesh = mesh;
  27166. }
  27167. return MeshLODLevel;
  27168. })();
  27169. Internals.MeshLODLevel = MeshLODLevel;
  27170. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27171. })(BABYLON || (BABYLON = {}));
  27172. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27173. (function (BABYLON) {
  27174. var AudioEngine = (function () {
  27175. function AudioEngine() {
  27176. this.audioContext = null;
  27177. this.canUseWebAudio = false;
  27178. this.WarnedWebAudioUnsupported = false;
  27179. try {
  27180. if (typeof AudioContext !== 'undefined') {
  27181. this.audioContext = new AudioContext();
  27182. this.canUseWebAudio = true;
  27183. }
  27184. else if (typeof webkitAudioContext !== 'undefined') {
  27185. this.audioContext = new webkitAudioContext();
  27186. this.canUseWebAudio = true;
  27187. }
  27188. }
  27189. catch (e) {
  27190. this.canUseWebAudio = false;
  27191. BABYLON.Tools.Error("Web Audio: " + e.message);
  27192. }
  27193. // create a global volume gain node
  27194. if (this.canUseWebAudio) {
  27195. this.masterGain = this.audioContext.createGain();
  27196. this.masterGain.gain.value = 1;
  27197. this.masterGain.connect(this.audioContext.destination);
  27198. }
  27199. }
  27200. AudioEngine.prototype.dispose = function () {
  27201. if (this.canUseWebAudio) {
  27202. if (this._connectedAnalyser) {
  27203. this._connectedAnalyser.stopDebugCanvas();
  27204. this._connectedAnalyser.dispose();
  27205. this.masterGain.disconnect();
  27206. this.masterGain.connect(this.audioContext.destination);
  27207. this._connectedAnalyser = null;
  27208. }
  27209. this.masterGain.gain.value = 1;
  27210. }
  27211. this.WarnedWebAudioUnsupported = false;
  27212. };
  27213. AudioEngine.prototype.getGlobalVolume = function () {
  27214. if (this.canUseWebAudio) {
  27215. return this.masterGain.gain.value;
  27216. }
  27217. else {
  27218. return -1;
  27219. }
  27220. };
  27221. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27222. if (this.canUseWebAudio) {
  27223. this.masterGain.gain.value = newVolume;
  27224. }
  27225. };
  27226. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27227. if (this._connectedAnalyser) {
  27228. this._connectedAnalyser.stopDebugCanvas();
  27229. }
  27230. this._connectedAnalyser = analyser;
  27231. if (this.canUseWebAudio) {
  27232. this.masterGain.disconnect();
  27233. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  27234. }
  27235. };
  27236. return AudioEngine;
  27237. })();
  27238. BABYLON.AudioEngine = AudioEngine;
  27239. })(BABYLON || (BABYLON = {}));
  27240. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27241. (function (BABYLON) {
  27242. var Sound = (function () {
  27243. /**
  27244. * Create a sound and attach it to a scene
  27245. * @param name Name of your sound
  27246. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27247. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27248. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27249. */
  27250. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27251. var _this = this;
  27252. this.autoplay = false;
  27253. this.loop = false;
  27254. this.useCustomAttenuation = false;
  27255. this.spatialSound = false;
  27256. this.refDistance = 1;
  27257. this.rolloffFactor = 1;
  27258. this.maxDistance = 100;
  27259. this.distanceModel = "linear";
  27260. this._panningModel = "equalpower";
  27261. this._playbackRate = 1;
  27262. this._startTime = 0;
  27263. this._startOffset = 0;
  27264. this._position = BABYLON.Vector3.Zero();
  27265. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27266. this._volume = 1;
  27267. this._isLoaded = false;
  27268. this._isReadyToPlay = false;
  27269. this.isPlaying = false;
  27270. this.isPaused = false;
  27271. this._isDirectional = false;
  27272. // Used if you'd like to create a directional sound.
  27273. // If not set, the sound will be omnidirectional
  27274. this._coneInnerAngle = 360;
  27275. this._coneOuterAngle = 360;
  27276. this._coneOuterGain = 0;
  27277. this.name = name;
  27278. this._scene = scene;
  27279. this._readyToPlayCallback = readyToPlayCallback;
  27280. // Default custom attenuation function is a linear attenuation
  27281. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27282. if (currentDistance < maxDistance) {
  27283. return currentVolume * (1 - currentDistance / maxDistance);
  27284. }
  27285. else {
  27286. return 0;
  27287. }
  27288. };
  27289. if (options) {
  27290. this.autoplay = options.autoplay || false;
  27291. this.loop = options.loop || false;
  27292. // if volume === 0, we need another way to check this option
  27293. if (options.volume !== undefined) {
  27294. this._volume = options.volume;
  27295. }
  27296. this.spatialSound = options.spatialSound || false;
  27297. this.maxDistance = options.maxDistance || 100;
  27298. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27299. this.rolloffFactor = options.rolloffFactor || 1;
  27300. this.refDistance = options.refDistance || 1;
  27301. this.distanceModel = options.distanceModel || "linear";
  27302. this._playbackRate = options.playbackRate || 1;
  27303. }
  27304. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27305. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27306. this._soundGain.gain.value = this._volume;
  27307. this._inputAudioNode = this._soundGain;
  27308. this._ouputAudioNode = this._soundGain;
  27309. if (this.spatialSound) {
  27310. this._createSpatialParameters();
  27311. }
  27312. this._scene.mainSoundTrack.AddSound(this);
  27313. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27314. if (urlOrArrayBuffer) {
  27315. // If it's an URL
  27316. if (typeof (urlOrArrayBuffer) === "string") {
  27317. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27318. _this._soundLoaded(data);
  27319. }, null, null, true);
  27320. }
  27321. else {
  27322. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27323. this._soundLoaded(urlOrArrayBuffer);
  27324. }
  27325. else {
  27326. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27327. }
  27328. }
  27329. }
  27330. }
  27331. else {
  27332. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27333. this._scene.mainSoundTrack.AddSound(this);
  27334. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27335. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27336. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27337. }
  27338. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27339. if (this._readyToPlayCallback) {
  27340. window.setTimeout(function () {
  27341. _this._readyToPlayCallback();
  27342. }, 1000);
  27343. }
  27344. }
  27345. }
  27346. Sound.prototype.dispose = function () {
  27347. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27348. if (this.isPlaying) {
  27349. this.stop();
  27350. }
  27351. this._isReadyToPlay = false;
  27352. if (this.soundTrackId === -1) {
  27353. this._scene.mainSoundTrack.RemoveSound(this);
  27354. }
  27355. else {
  27356. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27357. }
  27358. if (this._soundGain) {
  27359. this._soundGain.disconnect();
  27360. this._soundGain = null;
  27361. }
  27362. if (this._soundPanner) {
  27363. this._soundPanner.disconnect();
  27364. this._soundPanner = null;
  27365. }
  27366. if (this._soundSource) {
  27367. this._soundSource.disconnect();
  27368. this._soundSource = null;
  27369. }
  27370. this._audioBuffer = null;
  27371. if (this._connectedMesh) {
  27372. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27373. this._connectedMesh = null;
  27374. }
  27375. }
  27376. };
  27377. Sound.prototype._soundLoaded = function (audioData) {
  27378. var _this = this;
  27379. this._isLoaded = true;
  27380. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27381. _this._audioBuffer = buffer;
  27382. _this._isReadyToPlay = true;
  27383. if (_this.autoplay) {
  27384. _this.play();
  27385. }
  27386. if (_this._readyToPlayCallback) {
  27387. _this._readyToPlayCallback();
  27388. }
  27389. }, function (error) {
  27390. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27391. });
  27392. };
  27393. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27394. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27395. this._audioBuffer = audioBuffer;
  27396. this._isReadyToPlay = true;
  27397. }
  27398. };
  27399. Sound.prototype.updateOptions = function (options) {
  27400. if (options) {
  27401. this.loop = options.loop || this.loop;
  27402. this.maxDistance = options.maxDistance || this.maxDistance;
  27403. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27404. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27405. this.refDistance = options.refDistance || this.refDistance;
  27406. this.distanceModel = options.distanceModel || this.distanceModel;
  27407. this._playbackRate = options.playbackRate || this._playbackRate;
  27408. }
  27409. };
  27410. Sound.prototype._createSpatialParameters = function () {
  27411. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27412. if (this._scene.headphone) {
  27413. this._panningModel = "HRTF";
  27414. }
  27415. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27416. if (this.useCustomAttenuation) {
  27417. // Tricks to disable in a way embedded Web Audio attenuation
  27418. this._soundPanner.distanceModel = "linear";
  27419. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27420. this._soundPanner.refDistance = 1;
  27421. this._soundPanner.rolloffFactor = 1;
  27422. this._soundPanner.panningModel = this._panningModel;
  27423. }
  27424. else {
  27425. this._soundPanner.distanceModel = this.distanceModel;
  27426. this._soundPanner.maxDistance = this.maxDistance;
  27427. this._soundPanner.refDistance = this.refDistance;
  27428. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27429. this._soundPanner.panningModel = this._panningModel;
  27430. }
  27431. this._soundPanner.connect(this._ouputAudioNode);
  27432. this._inputAudioNode = this._soundPanner;
  27433. }
  27434. };
  27435. Sound.prototype.switchPanningModelToHRTF = function () {
  27436. this._panningModel = "HRTF";
  27437. this._switchPanningModel();
  27438. };
  27439. Sound.prototype.switchPanningModelToEqualPower = function () {
  27440. this._panningModel = "equalpower";
  27441. this._switchPanningModel();
  27442. };
  27443. Sound.prototype._switchPanningModel = function () {
  27444. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27445. this._soundPanner.panningModel = this._panningModel;
  27446. }
  27447. };
  27448. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27449. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27450. this._ouputAudioNode.disconnect();
  27451. this._ouputAudioNode.connect(soundTrackAudioNode);
  27452. }
  27453. };
  27454. /**
  27455. * Transform this sound into a directional source
  27456. * @param coneInnerAngle Size of the inner cone in degree
  27457. * @param coneOuterAngle Size of the outer cone in degree
  27458. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27459. */
  27460. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27461. if (coneOuterAngle < coneInnerAngle) {
  27462. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27463. return;
  27464. }
  27465. this._coneInnerAngle = coneInnerAngle;
  27466. this._coneOuterAngle = coneOuterAngle;
  27467. this._coneOuterGain = coneOuterGain;
  27468. this._isDirectional = true;
  27469. if (this.isPlaying && this.loop) {
  27470. this.stop();
  27471. this.play();
  27472. }
  27473. };
  27474. Sound.prototype.setPosition = function (newPosition) {
  27475. this._position = newPosition;
  27476. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27477. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27478. }
  27479. };
  27480. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27481. this._localDirection = newLocalDirection;
  27482. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27483. this._updateDirection();
  27484. }
  27485. };
  27486. Sound.prototype._updateDirection = function () {
  27487. var mat = this._connectedMesh.getWorldMatrix();
  27488. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27489. direction.normalize();
  27490. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27491. };
  27492. Sound.prototype.updateDistanceFromListener = function () {
  27493. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27494. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27495. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27496. }
  27497. };
  27498. Sound.prototype.setAttenuationFunction = function (callback) {
  27499. this._customAttenuationFunction = callback;
  27500. };
  27501. /**
  27502. * Play the sound
  27503. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27504. */
  27505. Sound.prototype.play = function (time) {
  27506. var _this = this;
  27507. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27508. try {
  27509. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27510. if (!this._soundSource) {
  27511. if (this.spatialSound) {
  27512. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27513. if (this._isDirectional) {
  27514. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27515. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27516. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27517. if (this._connectedMesh) {
  27518. this._updateDirection();
  27519. }
  27520. else {
  27521. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27522. }
  27523. }
  27524. }
  27525. }
  27526. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27527. this._soundSource.buffer = this._audioBuffer;
  27528. this._soundSource.connect(this._inputAudioNode);
  27529. this._soundSource.loop = this.loop;
  27530. this._soundSource.playbackRate.value = this._playbackRate;
  27531. this._startTime = startTime;
  27532. this._soundSource.onended = function () {
  27533. _this._onended();
  27534. };
  27535. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27536. this.isPlaying = true;
  27537. this.isPaused = false;
  27538. }
  27539. catch (ex) {
  27540. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27541. }
  27542. }
  27543. };
  27544. Sound.prototype._onended = function () {
  27545. this.isPlaying = false;
  27546. if (this.onended) {
  27547. this.onended();
  27548. }
  27549. };
  27550. /**
  27551. * Stop the sound
  27552. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27553. */
  27554. Sound.prototype.stop = function (time) {
  27555. if (this.isPlaying) {
  27556. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27557. this._soundSource.stop(stopTime);
  27558. this.isPlaying = false;
  27559. }
  27560. };
  27561. Sound.prototype.pause = function () {
  27562. if (this.isPlaying) {
  27563. this.stop(0);
  27564. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27565. this.isPaused = true;
  27566. }
  27567. };
  27568. Sound.prototype.setVolume = function (newVolume, time) {
  27569. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27570. if (time) {
  27571. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27572. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27573. }
  27574. else {
  27575. this._soundGain.gain.value = newVolume;
  27576. }
  27577. }
  27578. this._volume = newVolume;
  27579. };
  27580. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27581. this._playbackRate = newPlaybackRate;
  27582. if (this.isPlaying) {
  27583. this._soundSource.playbackRate.value = this._playbackRate;
  27584. }
  27585. };
  27586. Sound.prototype.getVolume = function () {
  27587. return this._volume;
  27588. };
  27589. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27590. var _this = this;
  27591. this._connectedMesh = meshToConnectTo;
  27592. if (!this.spatialSound) {
  27593. this._createSpatialParameters();
  27594. this.spatialSound = true;
  27595. if (this.isPlaying && this.loop) {
  27596. this.stop();
  27597. this.play();
  27598. }
  27599. }
  27600. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27601. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27602. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27603. };
  27604. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27605. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27606. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27607. this._updateDirection();
  27608. }
  27609. };
  27610. return Sound;
  27611. })();
  27612. BABYLON.Sound = Sound;
  27613. })(BABYLON || (BABYLON = {}));
  27614. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27615. (function (BABYLON) {
  27616. var SoundTrack = (function () {
  27617. function SoundTrack(scene, options) {
  27618. this.id = -1;
  27619. this._isMainTrack = false;
  27620. this._scene = scene;
  27621. this._audioEngine = BABYLON.Engine.audioEngine;
  27622. this.soundCollection = new Array();
  27623. if (this._audioEngine.canUseWebAudio) {
  27624. this._trackGain = this._audioEngine.audioContext.createGain();
  27625. this._trackGain.connect(this._audioEngine.masterGain);
  27626. if (options) {
  27627. if (options.volume) {
  27628. this._trackGain.gain.value = options.volume;
  27629. }
  27630. if (options.mainTrack) {
  27631. this._isMainTrack = options.mainTrack;
  27632. }
  27633. }
  27634. }
  27635. if (!this._isMainTrack) {
  27636. this._scene.soundTracks.push(this);
  27637. this.id = this._scene.soundTracks.length - 1;
  27638. }
  27639. }
  27640. SoundTrack.prototype.dispose = function () {
  27641. if (this._audioEngine.canUseWebAudio) {
  27642. if (this._connectedAnalyser) {
  27643. this._connectedAnalyser.stopDebugCanvas();
  27644. }
  27645. while (this.soundCollection.length) {
  27646. this.soundCollection[0].dispose();
  27647. }
  27648. this._trackGain.disconnect();
  27649. this._trackGain = null;
  27650. }
  27651. };
  27652. SoundTrack.prototype.AddSound = function (sound) {
  27653. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27654. sound.connectToSoundTrackAudioNode(this._trackGain);
  27655. }
  27656. if (sound.soundTrackId) {
  27657. if (sound.soundTrackId === -1) {
  27658. this._scene.mainSoundTrack.RemoveSound(sound);
  27659. }
  27660. else {
  27661. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27662. }
  27663. }
  27664. this.soundCollection.push(sound);
  27665. sound.soundTrackId = this.id;
  27666. };
  27667. SoundTrack.prototype.RemoveSound = function (sound) {
  27668. var index = this.soundCollection.indexOf(sound);
  27669. if (index !== -1) {
  27670. this.soundCollection.splice(index, 1);
  27671. }
  27672. };
  27673. SoundTrack.prototype.setVolume = function (newVolume) {
  27674. if (this._audioEngine.canUseWebAudio) {
  27675. this._trackGain.gain.value = newVolume;
  27676. }
  27677. };
  27678. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27679. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27680. for (var i = 0; i < this.soundCollection.length; i++) {
  27681. this.soundCollection[i].switchPanningModelToHRTF();
  27682. }
  27683. }
  27684. };
  27685. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27686. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27687. for (var i = 0; i < this.soundCollection.length; i++) {
  27688. this.soundCollection[i].switchPanningModelToEqualPower();
  27689. }
  27690. }
  27691. };
  27692. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27693. if (this._connectedAnalyser) {
  27694. this._connectedAnalyser.stopDebugCanvas();
  27695. }
  27696. this._connectedAnalyser = analyser;
  27697. if (this._audioEngine.canUseWebAudio) {
  27698. this._trackGain.disconnect();
  27699. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27700. }
  27701. };
  27702. return SoundTrack;
  27703. })();
  27704. BABYLON.SoundTrack = SoundTrack;
  27705. })(BABYLON || (BABYLON = {}));
  27706. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27707. (function (BABYLON) {
  27708. var DebugLayer = (function () {
  27709. function DebugLayer(scene) {
  27710. var _this = this;
  27711. this._transformationMatrix = BABYLON.Matrix.Identity();
  27712. this._enabled = false;
  27713. this._labelsEnabled = false;
  27714. this._displayStatistics = true;
  27715. this._displayTree = false;
  27716. this._displayLogs = false;
  27717. this._identityMatrix = BABYLON.Matrix.Identity();
  27718. this.axisRatio = 0.02;
  27719. this.accentColor = "orange";
  27720. this._scene = scene;
  27721. this._syncPositions = function () {
  27722. var engine = _this._scene.getEngine();
  27723. var canvasRect = engine.getRenderingCanvasClientRect();
  27724. if (_this._showUI) {
  27725. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27726. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27727. _this._statsDiv.style.width = "400px";
  27728. _this._statsDiv.style.height = "auto";
  27729. _this._statsSubsetDiv.style.maxHeight = "240px";
  27730. _this._optionsDiv.style.left = "0px";
  27731. _this._optionsDiv.style.top = "10px";
  27732. _this._optionsDiv.style.width = "200px";
  27733. _this._optionsDiv.style.height = "auto";
  27734. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27735. _this._logDiv.style.left = "0px";
  27736. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27737. _this._logDiv.style.width = "600px";
  27738. _this._logDiv.style.height = "160px";
  27739. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27740. _this._treeDiv.style.top = "10px";
  27741. _this._treeDiv.style.width = "300px";
  27742. _this._treeDiv.style.height = "auto";
  27743. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27744. }
  27745. _this._globalDiv.style.left = canvasRect.left + "px";
  27746. _this._globalDiv.style.top = canvasRect.top + "px";
  27747. _this._drawingCanvas.style.left = "0px";
  27748. _this._drawingCanvas.style.top = "0px";
  27749. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27750. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27751. var devicePixelRatio = window.devicePixelRatio || 1;
  27752. var context = _this._drawingContext;
  27753. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27754. _this._ratio = devicePixelRatio / backingStoreRatio;
  27755. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27756. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27757. };
  27758. this._onCanvasClick = function (evt) {
  27759. _this._clickPosition = {
  27760. x: evt.clientX * _this._ratio,
  27761. y: evt.clientY * _this._ratio
  27762. };
  27763. };
  27764. this._syncUI = function () {
  27765. if (_this._showUI) {
  27766. if (_this._displayStatistics) {
  27767. _this._displayStats();
  27768. _this._statsDiv.style.display = "";
  27769. }
  27770. else {
  27771. _this._statsDiv.style.display = "none";
  27772. }
  27773. if (_this._displayLogs) {
  27774. _this._logDiv.style.display = "";
  27775. }
  27776. else {
  27777. _this._logDiv.style.display = "none";
  27778. }
  27779. if (_this._displayTree) {
  27780. _this._treeDiv.style.display = "";
  27781. if (_this._needToRefreshMeshesTree) {
  27782. _this._needToRefreshMeshesTree = false;
  27783. _this._refreshMeshesTreeContent();
  27784. }
  27785. }
  27786. else {
  27787. _this._treeDiv.style.display = "none";
  27788. }
  27789. }
  27790. };
  27791. this._syncData = function () {
  27792. if (_this._labelsEnabled || !_this._showUI) {
  27793. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27794. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27795. var engine = _this._scene.getEngine();
  27796. var viewport = _this._camera.viewport;
  27797. var globalViewport = viewport.toGlobal(engine);
  27798. // Meshes
  27799. var meshes = _this._camera.getActiveMeshes();
  27800. for (var index = 0; index < meshes.length; index++) {
  27801. var mesh = meshes.data[index];
  27802. var position = mesh.getBoundingInfo().boundingSphere.center;
  27803. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27804. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27805. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27806. }
  27807. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27808. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27809. mesh.renderOverlay = !mesh.renderOverlay;
  27810. }, function () {
  27811. return mesh.renderOverlay ? 'red' : 'black';
  27812. });
  27813. }
  27814. }
  27815. // Cameras
  27816. var cameras = _this._scene.cameras;
  27817. for (index = 0; index < cameras.length; index++) {
  27818. var camera = cameras[index];
  27819. if (camera === _this._camera) {
  27820. continue;
  27821. }
  27822. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27823. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27824. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27825. _this._camera.detachControl(engine.getRenderingCanvas());
  27826. _this._camera = camera;
  27827. _this._camera.attachControl(engine.getRenderingCanvas());
  27828. }, function () {
  27829. return "purple";
  27830. });
  27831. }
  27832. }
  27833. // Lights
  27834. var lights = _this._scene.lights;
  27835. for (index = 0; index < lights.length; index++) {
  27836. var light = lights[index];
  27837. if (light.position) {
  27838. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27839. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27840. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27841. light.setEnabled(!light.isEnabled());
  27842. }, function () {
  27843. return light.isEnabled() ? "orange" : "gray";
  27844. });
  27845. }
  27846. }
  27847. }
  27848. }
  27849. _this._clickPosition = undefined;
  27850. };
  27851. }
  27852. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27853. while (this._treeSubsetDiv.hasChildNodes()) {
  27854. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27855. }
  27856. // Add meshes
  27857. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27858. sortedArray.sort(function (a, b) {
  27859. if (a.name === b.name) {
  27860. return 0;
  27861. }
  27862. return (a.name > b.name) ? 1 : -1;
  27863. });
  27864. for (var index = 0; index < sortedArray.length; index++) {
  27865. var mesh = sortedArray[index];
  27866. if (!mesh.isEnabled()) {
  27867. continue;
  27868. }
  27869. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27870. m.isVisible = element.checked;
  27871. }, mesh);
  27872. }
  27873. };
  27874. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27875. this._drawingContext.beginPath();
  27876. this._drawingContext.moveTo(zero.x, zero.y);
  27877. this._drawingContext.lineTo(unit.x, unit.y);
  27878. this._drawingContext.strokeStyle = color;
  27879. this._drawingContext.lineWidth = 4;
  27880. this._drawingContext.stroke();
  27881. this._drawingContext.font = "normal 14px Segoe UI";
  27882. this._drawingContext.fillStyle = color;
  27883. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27884. };
  27885. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27886. var position = mesh.getBoundingInfo().boundingSphere.center;
  27887. var worldMatrix = mesh.getWorldMatrix();
  27888. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27889. var unit = (unprojectedVector.subtract(position)).length();
  27890. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27891. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27892. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27893. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27894. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27895. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27896. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27897. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27898. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27899. };
  27900. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27901. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27902. this._drawingContext.font = "normal 12px Segoe UI";
  27903. var textMetrics = this._drawingContext.measureText(text);
  27904. var centerX = projectedPosition.x - textMetrics.width / 2;
  27905. var centerY = projectedPosition.y;
  27906. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27907. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27908. onClick();
  27909. }
  27910. this._drawingContext.beginPath();
  27911. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27912. this._drawingContext.fillStyle = getFillStyle();
  27913. this._drawingContext.globalAlpha = 0.5;
  27914. this._drawingContext.fill();
  27915. this._drawingContext.globalAlpha = 1.0;
  27916. this._drawingContext.strokeStyle = '#FFFFFF';
  27917. this._drawingContext.lineWidth = 1;
  27918. this._drawingContext.stroke();
  27919. this._drawingContext.fillStyle = "#FFFFFF";
  27920. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27921. this._drawingContext.beginPath();
  27922. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27923. this._drawingContext.fill();
  27924. }
  27925. };
  27926. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27927. if (!this._clickPosition) {
  27928. return false;
  27929. }
  27930. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27931. return false;
  27932. }
  27933. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27934. return false;
  27935. }
  27936. return true;
  27937. };
  27938. DebugLayer.prototype.isVisible = function () {
  27939. return this._enabled;
  27940. };
  27941. DebugLayer.prototype.hide = function () {
  27942. if (!this._enabled) {
  27943. return;
  27944. }
  27945. this._enabled = false;
  27946. var engine = this._scene.getEngine();
  27947. this._scene.unregisterBeforeRender(this._syncData);
  27948. this._scene.unregisterAfterRender(this._syncUI);
  27949. document.body.removeChild(this._globalDiv);
  27950. window.removeEventListener("resize", this._syncPositions);
  27951. this._scene.forceShowBoundingBoxes = false;
  27952. this._scene.forceWireframe = false;
  27953. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27954. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27955. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27956. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27957. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27958. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27959. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27960. this._scene.shadowsEnabled = true;
  27961. this._scene.particlesEnabled = true;
  27962. this._scene.postProcessesEnabled = true;
  27963. this._scene.collisionsEnabled = true;
  27964. this._scene.lightsEnabled = true;
  27965. this._scene.texturesEnabled = true;
  27966. this._scene.lensFlaresEnabled = true;
  27967. this._scene.proceduralTexturesEnabled = true;
  27968. this._scene.renderTargetsEnabled = true;
  27969. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27970. };
  27971. DebugLayer.prototype.show = function (showUI, camera) {
  27972. if (showUI === void 0) { showUI = true; }
  27973. if (camera === void 0) { camera = null; }
  27974. if (this._enabled) {
  27975. return;
  27976. }
  27977. this._enabled = true;
  27978. if (camera) {
  27979. this._camera = camera;
  27980. }
  27981. else {
  27982. this._camera = this._scene.activeCamera;
  27983. }
  27984. this._showUI = showUI;
  27985. var engine = this._scene.getEngine();
  27986. this._globalDiv = document.createElement("div");
  27987. document.body.appendChild(this._globalDiv);
  27988. this._generateDOMelements();
  27989. window.addEventListener("resize", this._syncPositions);
  27990. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27991. this._syncPositions();
  27992. this._scene.registerBeforeRender(this._syncData);
  27993. this._scene.registerAfterRender(this._syncUI);
  27994. };
  27995. DebugLayer.prototype._clearLabels = function () {
  27996. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27997. for (var index = 0; index < this._scene.meshes.length; index++) {
  27998. var mesh = this._scene.meshes[index];
  27999. mesh.renderOverlay = false;
  28000. }
  28001. };
  28002. DebugLayer.prototype._generateheader = function (root, text) {
  28003. var header = document.createElement("div");
  28004. header.innerHTML = text + "&nbsp;";
  28005. header.style.textAlign = "right";
  28006. header.style.width = "100%";
  28007. header.style.color = "white";
  28008. header.style.backgroundColor = "Black";
  28009. header.style.padding = "5px 5px 4px 0px";
  28010. header.style.marginLeft = "-5px";
  28011. header.style.fontWeight = "bold";
  28012. root.appendChild(header);
  28013. };
  28014. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28015. var label = document.createElement("label");
  28016. label.innerHTML = title;
  28017. label.style.color = color;
  28018. root.appendChild(label);
  28019. root.appendChild(document.createElement("br"));
  28020. };
  28021. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28022. if (tag === void 0) { tag = null; }
  28023. var label = document.createElement("label");
  28024. var boundingBoxesCheckbox = document.createElement("input");
  28025. boundingBoxesCheckbox.type = "checkbox";
  28026. boundingBoxesCheckbox.checked = initialState;
  28027. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28028. task(evt.target, tag);
  28029. });
  28030. label.appendChild(boundingBoxesCheckbox);
  28031. var container = document.createElement("span");
  28032. var leftPart = document.createElement("span");
  28033. var rightPart = document.createElement("span");
  28034. rightPart.style.cssFloat = "right";
  28035. leftPart.innerHTML = leftTitle;
  28036. rightPart.innerHTML = rightTitle;
  28037. rightPart.style.fontSize = "12px";
  28038. rightPart.style.maxWidth = "200px";
  28039. container.appendChild(leftPart);
  28040. container.appendChild(rightPart);
  28041. label.appendChild(container);
  28042. root.appendChild(label);
  28043. root.appendChild(document.createElement("br"));
  28044. };
  28045. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28046. if (tag === void 0) { tag = null; }
  28047. var label = document.createElement("label");
  28048. var checkBox = document.createElement("input");
  28049. checkBox.type = "checkbox";
  28050. checkBox.checked = initialState;
  28051. checkBox.addEventListener("change", function (evt) {
  28052. task(evt.target, tag);
  28053. });
  28054. label.appendChild(checkBox);
  28055. label.appendChild(document.createTextNode(title));
  28056. root.appendChild(label);
  28057. root.appendChild(document.createElement("br"));
  28058. };
  28059. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28060. if (tag === void 0) { tag = null; }
  28061. var button = document.createElement("button");
  28062. button.innerHTML = title;
  28063. button.style.height = "24px";
  28064. button.style.color = "#444444";
  28065. button.style.border = "1px solid white";
  28066. button.className = "debugLayerButton";
  28067. button.addEventListener("click", function (evt) {
  28068. task(evt.target, tag);
  28069. });
  28070. root.appendChild(button);
  28071. root.appendChild(document.createElement("br"));
  28072. };
  28073. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28074. if (tag === void 0) { tag = null; }
  28075. var label = document.createElement("label");
  28076. var boundingBoxesRadio = document.createElement("input");
  28077. boundingBoxesRadio.type = "radio";
  28078. boundingBoxesRadio.name = name;
  28079. boundingBoxesRadio.checked = initialState;
  28080. boundingBoxesRadio.addEventListener("change", function (evt) {
  28081. task(evt.target, tag);
  28082. });
  28083. label.appendChild(boundingBoxesRadio);
  28084. label.appendChild(document.createTextNode(title));
  28085. root.appendChild(label);
  28086. root.appendChild(document.createElement("br"));
  28087. };
  28088. DebugLayer.prototype._generateDOMelements = function () {
  28089. var _this = this;
  28090. this._globalDiv.id = "DebugLayer";
  28091. this._globalDiv.style.position = "absolute";
  28092. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28093. this._globalDiv.style.fontSize = "14px";
  28094. this._globalDiv.style.color = "white";
  28095. // Drawing canvas
  28096. this._drawingCanvas = document.createElement("canvas");
  28097. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28098. this._drawingCanvas.style.position = "absolute";
  28099. this._drawingCanvas.style.pointerEvents = "none";
  28100. this._drawingContext = this._drawingCanvas.getContext("2d");
  28101. this._globalDiv.appendChild(this._drawingCanvas);
  28102. if (this._showUI) {
  28103. var background = "rgba(128, 128, 128, 0.4)";
  28104. var border = "rgb(180, 180, 180) solid 1px";
  28105. // Stats
  28106. this._statsDiv = document.createElement("div");
  28107. this._statsDiv.id = "DebugLayerStats";
  28108. this._statsDiv.style.border = border;
  28109. this._statsDiv.style.position = "absolute";
  28110. this._statsDiv.style.background = background;
  28111. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28112. this._generateheader(this._statsDiv, "STATISTICS");
  28113. this._statsSubsetDiv = document.createElement("div");
  28114. this._statsSubsetDiv.style.paddingTop = "5px";
  28115. this._statsSubsetDiv.style.paddingBottom = "5px";
  28116. this._statsSubsetDiv.style.overflowY = "auto";
  28117. this._statsDiv.appendChild(this._statsSubsetDiv);
  28118. // Tree
  28119. this._treeDiv = document.createElement("div");
  28120. this._treeDiv.id = "DebugLayerTree";
  28121. this._treeDiv.style.border = border;
  28122. this._treeDiv.style.position = "absolute";
  28123. this._treeDiv.style.background = background;
  28124. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28125. this._treeDiv.style.display = "none";
  28126. this._generateheader(this._treeDiv, "MESHES TREE");
  28127. this._treeSubsetDiv = document.createElement("div");
  28128. this._treeSubsetDiv.style.paddingTop = "5px";
  28129. this._treeSubsetDiv.style.paddingRight = "5px";
  28130. this._treeSubsetDiv.style.overflowY = "auto";
  28131. this._treeSubsetDiv.style.maxHeight = "300px";
  28132. this._treeDiv.appendChild(this._treeSubsetDiv);
  28133. this._needToRefreshMeshesTree = true;
  28134. // Logs
  28135. this._logDiv = document.createElement("div");
  28136. this._logDiv.style.border = border;
  28137. this._logDiv.id = "DebugLayerLogs";
  28138. this._logDiv.style.position = "absolute";
  28139. this._logDiv.style.background = background;
  28140. this._logDiv.style.padding = "0px 0px 0px 5px";
  28141. this._logDiv.style.display = "none";
  28142. this._generateheader(this._logDiv, "LOGS");
  28143. this._logSubsetDiv = document.createElement("div");
  28144. this._logSubsetDiv.style.height = "127px";
  28145. this._logSubsetDiv.style.paddingTop = "5px";
  28146. this._logSubsetDiv.style.overflowY = "auto";
  28147. this._logSubsetDiv.style.fontSize = "12px";
  28148. this._logSubsetDiv.style.fontFamily = "consolas";
  28149. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28150. this._logDiv.appendChild(this._logSubsetDiv);
  28151. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28152. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28153. };
  28154. // Options
  28155. this._optionsDiv = document.createElement("div");
  28156. this._optionsDiv.id = "DebugLayerOptions";
  28157. this._optionsDiv.style.border = border;
  28158. this._optionsDiv.style.position = "absolute";
  28159. this._optionsDiv.style.background = background;
  28160. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28161. this._optionsDiv.style.overflowY = "auto";
  28162. this._generateheader(this._optionsDiv, "OPTIONS");
  28163. this._optionsSubsetDiv = document.createElement("div");
  28164. this._optionsSubsetDiv.style.paddingTop = "5px";
  28165. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28166. this._optionsSubsetDiv.style.overflowY = "auto";
  28167. this._optionsSubsetDiv.style.maxHeight = "200px";
  28168. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28169. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28170. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28171. _this._displayStatistics = element.checked;
  28172. });
  28173. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28174. _this._displayLogs = element.checked;
  28175. });
  28176. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28177. _this._displayTree = element.checked;
  28178. _this._needToRefreshMeshesTree = true;
  28179. });
  28180. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28181. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28182. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28183. _this._scene.forceShowBoundingBoxes = element.checked;
  28184. });
  28185. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28186. _this._labelsEnabled = element.checked;
  28187. if (!_this._labelsEnabled) {
  28188. _this._clearLabels();
  28189. }
  28190. });
  28191. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28192. if (element.checked) {
  28193. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28194. }
  28195. else {
  28196. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28197. }
  28198. });
  28199. ;
  28200. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28201. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28202. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28203. if (element.checked) {
  28204. _this._scene.forceWireframe = false;
  28205. _this._scene.forcePointsCloud = false;
  28206. }
  28207. });
  28208. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28209. if (element.checked) {
  28210. _this._scene.forceWireframe = true;
  28211. _this._scene.forcePointsCloud = false;
  28212. }
  28213. });
  28214. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28215. if (element.checked) {
  28216. _this._scene.forceWireframe = false;
  28217. _this._scene.forcePointsCloud = true;
  28218. }
  28219. });
  28220. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28221. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28222. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28223. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28224. });
  28225. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28226. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28227. });
  28228. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28229. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28230. });
  28231. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28232. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28233. });
  28234. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28235. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28236. });
  28237. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28238. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28239. });
  28240. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28241. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28242. });
  28243. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28244. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28245. });
  28246. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28247. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28248. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28249. _this._scene.animationsEnabled = element.checked;
  28250. });
  28251. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28252. _this._scene.collisionsEnabled = element.checked;
  28253. });
  28254. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28255. _this._scene.fogEnabled = element.checked;
  28256. });
  28257. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28258. _this._scene.lensFlaresEnabled = element.checked;
  28259. });
  28260. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28261. _this._scene.lightsEnabled = element.checked;
  28262. });
  28263. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28264. _this._scene.particlesEnabled = element.checked;
  28265. });
  28266. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28267. _this._scene.postProcessesEnabled = element.checked;
  28268. });
  28269. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28270. _this._scene.proceduralTexturesEnabled = element.checked;
  28271. });
  28272. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28273. _this._scene.renderTargetsEnabled = element.checked;
  28274. });
  28275. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28276. _this._scene.shadowsEnabled = element.checked;
  28277. });
  28278. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28279. _this._scene.skeletonsEnabled = element.checked;
  28280. });
  28281. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28282. _this._scene.spritesEnabled = element.checked;
  28283. });
  28284. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28285. _this._scene.texturesEnabled = element.checked;
  28286. });
  28287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28288. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28289. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28290. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28291. if (element.checked) {
  28292. _this._scene.headphone = true;
  28293. }
  28294. });
  28295. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28296. if (element.checked) {
  28297. _this._scene.headphone = false;
  28298. }
  28299. });
  28300. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28301. _this._scene.audioEnabled = !element.checked;
  28302. });
  28303. }
  28304. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28305. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28306. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28307. _this._scene.dumpNextRenderTargets = true;
  28308. });
  28309. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28310. this._globalDiv.appendChild(this._statsDiv);
  28311. this._globalDiv.appendChild(this._logDiv);
  28312. this._globalDiv.appendChild(this._optionsDiv);
  28313. this._globalDiv.appendChild(this._treeDiv);
  28314. }
  28315. };
  28316. DebugLayer.prototype._displayStats = function () {
  28317. var scene = this._scene;
  28318. var engine = scene.getEngine();
  28319. var glInfo = engine.getGlInfo();
  28320. 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>";
  28321. if (this.customStatsFunction) {
  28322. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28323. }
  28324. };
  28325. return DebugLayer;
  28326. })();
  28327. BABYLON.DebugLayer = DebugLayer;
  28328. })(BABYLON || (BABYLON = {}));
  28329. //# sourceMappingURL=babylon.debugLayer.js.map
  28330. var BABYLON;
  28331. (function (BABYLON) {
  28332. var RawTexture = (function (_super) {
  28333. __extends(RawTexture, _super);
  28334. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28335. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28336. if (invertY === void 0) { invertY = false; }
  28337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28338. _super.call(this, null, scene, !generateMipMaps, invertY);
  28339. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28340. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28341. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28342. }
  28343. // Statics
  28344. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28345. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28346. if (invertY === void 0) { invertY = false; }
  28347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28348. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28349. };
  28350. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28351. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28352. if (invertY === void 0) { invertY = false; }
  28353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28354. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28355. };
  28356. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28357. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28358. if (invertY === void 0) { invertY = false; }
  28359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28360. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28361. };
  28362. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28364. if (invertY === void 0) { invertY = false; }
  28365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28366. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28367. };
  28368. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28369. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28370. if (invertY === void 0) { invertY = false; }
  28371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28372. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28373. };
  28374. return RawTexture;
  28375. })(BABYLON.Texture);
  28376. BABYLON.RawTexture = RawTexture;
  28377. })(BABYLON || (BABYLON = {}));
  28378. //# sourceMappingURL=babylon.rawTexture.js.map
  28379. var BABYLON;
  28380. (function (BABYLON) {
  28381. var IndexedVector2 = (function (_super) {
  28382. __extends(IndexedVector2, _super);
  28383. function IndexedVector2(original, index) {
  28384. _super.call(this, original.x, original.y);
  28385. this.index = index;
  28386. }
  28387. return IndexedVector2;
  28388. })(BABYLON.Vector2);
  28389. var PolygonPoints = (function () {
  28390. function PolygonPoints() {
  28391. this.elements = new Array();
  28392. }
  28393. PolygonPoints.prototype.add = function (originalPoints) {
  28394. var _this = this;
  28395. var result = new Array();
  28396. originalPoints.forEach(function (point) {
  28397. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28398. var newPoint = new IndexedVector2(point, _this.elements.length);
  28399. result.push(newPoint);
  28400. _this.elements.push(newPoint);
  28401. }
  28402. });
  28403. return result;
  28404. };
  28405. PolygonPoints.prototype.computeBounds = function () {
  28406. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28407. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28408. this.elements.forEach(function (point) {
  28409. // x
  28410. if (point.x < lmin.x) {
  28411. lmin.x = point.x;
  28412. }
  28413. else if (point.x > lmax.x) {
  28414. lmax.x = point.x;
  28415. }
  28416. // y
  28417. if (point.y < lmin.y) {
  28418. lmin.y = point.y;
  28419. }
  28420. else if (point.y > lmax.y) {
  28421. lmax.y = point.y;
  28422. }
  28423. });
  28424. return {
  28425. min: lmin,
  28426. max: lmax,
  28427. width: lmax.x - lmin.x,
  28428. height: lmax.y - lmin.y
  28429. };
  28430. };
  28431. return PolygonPoints;
  28432. })();
  28433. var Polygon = (function () {
  28434. function Polygon() {
  28435. }
  28436. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28437. return [
  28438. new BABYLON.Vector2(xmin, ymin),
  28439. new BABYLON.Vector2(xmax, ymin),
  28440. new BABYLON.Vector2(xmax, ymax),
  28441. new BABYLON.Vector2(xmin, ymax)
  28442. ];
  28443. };
  28444. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28445. if (cx === void 0) { cx = 0; }
  28446. if (cy === void 0) { cy = 0; }
  28447. if (numberOfSides === void 0) { numberOfSides = 32; }
  28448. var result = new Array();
  28449. var angle = 0;
  28450. var increment = (Math.PI * 2) / numberOfSides;
  28451. for (var i = 0; i < numberOfSides; i++) {
  28452. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28453. angle -= increment;
  28454. }
  28455. return result;
  28456. };
  28457. Polygon.Parse = function (input) {
  28458. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28459. var i, result = [];
  28460. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28461. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28462. }
  28463. return result;
  28464. };
  28465. Polygon.StartingAt = function (x, y) {
  28466. return BABYLON.Path2.StartingAt(x, y);
  28467. };
  28468. return Polygon;
  28469. })();
  28470. BABYLON.Polygon = Polygon;
  28471. var PolygonMeshBuilder = (function () {
  28472. function PolygonMeshBuilder(name, contours, scene) {
  28473. this._points = new PolygonPoints();
  28474. if (!("poly2tri" in window)) {
  28475. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28476. }
  28477. this._name = name;
  28478. this._scene = scene;
  28479. var points;
  28480. if (contours instanceof BABYLON.Path2) {
  28481. points = contours.getPoints();
  28482. }
  28483. else {
  28484. points = contours;
  28485. }
  28486. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28487. }
  28488. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28489. this._swctx.addHole(this._points.add(hole));
  28490. return this;
  28491. };
  28492. PolygonMeshBuilder.prototype.build = function (updatable) {
  28493. if (updatable === void 0) { updatable = false; }
  28494. var result = new BABYLON.Mesh(this._name, this._scene);
  28495. var normals = [];
  28496. var positions = [];
  28497. var uvs = [];
  28498. var bounds = this._points.computeBounds();
  28499. this._points.elements.forEach(function (p) {
  28500. normals.push(0, 1.0, 0);
  28501. positions.push(p.x, 0, p.y);
  28502. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28503. });
  28504. var indices = [];
  28505. this._swctx.triangulate();
  28506. this._swctx.getTriangles().forEach(function (triangle) {
  28507. triangle.getPoints().forEach(function (point) {
  28508. indices.push(point.index);
  28509. });
  28510. });
  28511. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28512. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28513. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28514. result.setIndices(indices);
  28515. return result;
  28516. };
  28517. return PolygonMeshBuilder;
  28518. })();
  28519. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28520. })(BABYLON || (BABYLON = {}));
  28521. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28522. (function (BABYLON) {
  28523. var SimplificationSettings = (function () {
  28524. function SimplificationSettings(quality, distance, optimizeMesh) {
  28525. this.quality = quality;
  28526. this.distance = distance;
  28527. this.optimizeMesh = optimizeMesh;
  28528. }
  28529. return SimplificationSettings;
  28530. })();
  28531. BABYLON.SimplificationSettings = SimplificationSettings;
  28532. var SimplificationQueue = (function () {
  28533. function SimplificationQueue() {
  28534. this.running = false;
  28535. this._simplificationArray = [];
  28536. }
  28537. SimplificationQueue.prototype.addTask = function (task) {
  28538. this._simplificationArray.push(task);
  28539. };
  28540. SimplificationQueue.prototype.executeNext = function () {
  28541. var task = this._simplificationArray.pop();
  28542. if (task) {
  28543. this.running = true;
  28544. this.runSimplification(task);
  28545. }
  28546. else {
  28547. this.running = false;
  28548. }
  28549. };
  28550. SimplificationQueue.prototype.runSimplification = function (task) {
  28551. var _this = this;
  28552. if (task.parallelProcessing) {
  28553. //parallel simplifier
  28554. task.settings.forEach(function (setting) {
  28555. var simplifier = _this.getSimplifier(task);
  28556. simplifier.simplify(setting, function (newMesh) {
  28557. task.mesh.addLODLevel(setting.distance, newMesh);
  28558. newMesh.isVisible = true;
  28559. //check if it is the last
  28560. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28561. //all done, run the success callback.
  28562. task.successCallback();
  28563. }
  28564. _this.executeNext();
  28565. });
  28566. });
  28567. }
  28568. else {
  28569. //single simplifier.
  28570. var simplifier = this.getSimplifier(task);
  28571. var runDecimation = function (setting, callback) {
  28572. simplifier.simplify(setting, function (newMesh) {
  28573. task.mesh.addLODLevel(setting.distance, newMesh);
  28574. newMesh.isVisible = true;
  28575. //run the next quality level
  28576. callback();
  28577. });
  28578. };
  28579. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28580. runDecimation(task.settings[loop.index], function () {
  28581. loop.executeNext();
  28582. });
  28583. }, function () {
  28584. //execution ended, run the success callback.
  28585. if (task.successCallback) {
  28586. task.successCallback();
  28587. }
  28588. _this.executeNext();
  28589. });
  28590. }
  28591. };
  28592. SimplificationQueue.prototype.getSimplifier = function (task) {
  28593. switch (task.simplificationType) {
  28594. case 0 /* QUADRATIC */:
  28595. default:
  28596. return new QuadraticErrorSimplification(task.mesh);
  28597. }
  28598. };
  28599. return SimplificationQueue;
  28600. })();
  28601. BABYLON.SimplificationQueue = SimplificationQueue;
  28602. /**
  28603. * The implemented types of simplification.
  28604. * At the moment only Quadratic Error Decimation is implemented.
  28605. */
  28606. (function (SimplificationType) {
  28607. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28608. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28609. var SimplificationType = BABYLON.SimplificationType;
  28610. var DecimationTriangle = (function () {
  28611. function DecimationTriangle(vertices) {
  28612. this.vertices = vertices;
  28613. this.error = new Array(4);
  28614. this.deleted = false;
  28615. this.isDirty = false;
  28616. this.deletePending = false;
  28617. this.borderFactor = 0;
  28618. }
  28619. return DecimationTriangle;
  28620. })();
  28621. BABYLON.DecimationTriangle = DecimationTriangle;
  28622. var DecimationVertex = (function () {
  28623. function DecimationVertex(position, id) {
  28624. this.position = position;
  28625. this.id = id;
  28626. this.isBorder = true;
  28627. this.q = new QuadraticMatrix();
  28628. this.triangleCount = 0;
  28629. this.triangleStart = 0;
  28630. this.originalOffsets = [];
  28631. }
  28632. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28633. this.position.copyFrom(newPosition);
  28634. };
  28635. return DecimationVertex;
  28636. })();
  28637. BABYLON.DecimationVertex = DecimationVertex;
  28638. var QuadraticMatrix = (function () {
  28639. function QuadraticMatrix(data) {
  28640. this.data = new Array(10);
  28641. for (var i = 0; i < 10; ++i) {
  28642. if (data && data[i]) {
  28643. this.data[i] = data[i];
  28644. }
  28645. else {
  28646. this.data[i] = 0;
  28647. }
  28648. }
  28649. }
  28650. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28651. 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];
  28652. return det;
  28653. };
  28654. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28655. for (var i = 0; i < 10; ++i) {
  28656. this.data[i] += matrix.data[i];
  28657. }
  28658. };
  28659. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28660. for (var i = 0; i < 10; ++i) {
  28661. this.data[i] += data[i];
  28662. }
  28663. };
  28664. QuadraticMatrix.prototype.add = function (matrix) {
  28665. var m = new QuadraticMatrix();
  28666. for (var i = 0; i < 10; ++i) {
  28667. m.data[i] = this.data[i] + matrix.data[i];
  28668. }
  28669. return m;
  28670. };
  28671. QuadraticMatrix.FromData = function (a, b, c, d) {
  28672. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28673. };
  28674. //returning an array to avoid garbage collection
  28675. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28676. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28677. };
  28678. return QuadraticMatrix;
  28679. })();
  28680. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28681. var Reference = (function () {
  28682. function Reference(vertexId, triangleId) {
  28683. this.vertexId = vertexId;
  28684. this.triangleId = triangleId;
  28685. }
  28686. return Reference;
  28687. })();
  28688. BABYLON.Reference = Reference;
  28689. /**
  28690. * An implementation of the Quadratic Error simplification algorithm.
  28691. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28692. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28693. * @author RaananW
  28694. */
  28695. var QuadraticErrorSimplification = (function () {
  28696. function QuadraticErrorSimplification(_mesh) {
  28697. this._mesh = _mesh;
  28698. this.initialized = false;
  28699. this.syncIterations = 5000;
  28700. this.aggressiveness = 7;
  28701. this.decimationIterations = 100;
  28702. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28703. }
  28704. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28705. var _this = this;
  28706. this.initDecimatedMesh();
  28707. //iterating through the submeshes array, one after the other.
  28708. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28709. _this.initWithMesh(loop.index, function () {
  28710. _this.runDecimation(settings, loop.index, function () {
  28711. loop.executeNext();
  28712. });
  28713. }, settings.optimizeMesh);
  28714. }, function () {
  28715. setTimeout(function () {
  28716. successCallback(_this._reconstructedMesh);
  28717. }, 0);
  28718. });
  28719. };
  28720. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28721. var _this = this;
  28722. var gCount = 0;
  28723. triangle.vertices.forEach(function (vertex) {
  28724. var count = 0;
  28725. var vPos = vertex.position;
  28726. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28727. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28728. ++count;
  28729. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28730. ++count;
  28731. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28732. ++count;
  28733. if (count > 1) {
  28734. ++gCount;
  28735. }
  28736. ;
  28737. });
  28738. if (gCount > 1) {
  28739. console.log(triangle, gCount);
  28740. }
  28741. return gCount > 1;
  28742. };
  28743. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28744. var _this = this;
  28745. var targetCount = ~~(this.triangles.length * settings.quality);
  28746. var deletedTriangles = 0;
  28747. var triangleCount = this.triangles.length;
  28748. var iterationFunction = function (iteration, callback) {
  28749. setTimeout(function () {
  28750. if (iteration % 5 === 0) {
  28751. _this.updateMesh(iteration === 0);
  28752. }
  28753. for (var i = 0; i < _this.triangles.length; ++i) {
  28754. _this.triangles[i].isDirty = false;
  28755. }
  28756. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28757. var trianglesIterator = function (i) {
  28758. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28759. var t = _this.triangles[tIdx];
  28760. if (!t)
  28761. return;
  28762. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28763. return;
  28764. }
  28765. for (var j = 0; j < 3; ++j) {
  28766. if (t.error[j] < threshold) {
  28767. var deleted0 = [];
  28768. var deleted1 = [];
  28769. var v0 = t.vertices[j];
  28770. var v1 = t.vertices[(j + 1) % 3];
  28771. if (v0.isBorder !== v1.isBorder)
  28772. continue;
  28773. var p = BABYLON.Vector3.Zero();
  28774. var n = BABYLON.Vector3.Zero();
  28775. var uv = BABYLON.Vector2.Zero();
  28776. var color = new BABYLON.Color4(0, 0, 0, 1);
  28777. _this.calculateError(v0, v1, p, n, uv, color);
  28778. var delTr = [];
  28779. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28780. continue;
  28781. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28782. continue;
  28783. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28784. continue;
  28785. var uniqueArray = [];
  28786. delTr.forEach(function (deletedT) {
  28787. if (uniqueArray.indexOf(deletedT) === -1) {
  28788. deletedT.deletePending = true;
  28789. uniqueArray.push(deletedT);
  28790. }
  28791. });
  28792. if (uniqueArray.length % 2 != 0) {
  28793. continue;
  28794. }
  28795. v0.q = v1.q.add(v0.q);
  28796. v0.updatePosition(p);
  28797. var tStart = _this.references.length;
  28798. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28799. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28800. var tCount = _this.references.length - tStart;
  28801. if (tCount <= v0.triangleCount) {
  28802. if (tCount) {
  28803. for (var c = 0; c < tCount; c++) {
  28804. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28805. }
  28806. }
  28807. }
  28808. else {
  28809. v0.triangleStart = tStart;
  28810. }
  28811. v0.triangleCount = tCount;
  28812. break;
  28813. }
  28814. }
  28815. };
  28816. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28817. return (triangleCount - deletedTriangles <= targetCount);
  28818. });
  28819. }, 0);
  28820. };
  28821. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28822. if (triangleCount - deletedTriangles <= targetCount)
  28823. loop.breakLoop();
  28824. else {
  28825. iterationFunction(loop.index, function () {
  28826. loop.executeNext();
  28827. });
  28828. }
  28829. }, function () {
  28830. setTimeout(function () {
  28831. //reconstruct this part of the mesh
  28832. _this.reconstructMesh(submeshIndex);
  28833. successCallback();
  28834. }, 0);
  28835. });
  28836. };
  28837. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28838. var _this = this;
  28839. this.vertices = [];
  28840. this.triangles = [];
  28841. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28842. var indices = this._mesh.getIndices();
  28843. var submesh = this._mesh.subMeshes[submeshIndex];
  28844. var findInVertices = function (positionToSearch) {
  28845. if (optimizeMesh) {
  28846. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28847. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28848. return _this.vertices[ii];
  28849. }
  28850. }
  28851. }
  28852. return null;
  28853. };
  28854. var vertexReferences = [];
  28855. var vertexInit = function (i) {
  28856. var offset = i + submesh.verticesStart;
  28857. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28858. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28859. vertex.originalOffsets.push(offset);
  28860. if (vertex.id == _this.vertices.length) {
  28861. _this.vertices.push(vertex);
  28862. }
  28863. vertexReferences.push(vertex.id);
  28864. };
  28865. //var totalVertices = mesh.getTotalVertices();
  28866. var totalVertices = submesh.verticesCount;
  28867. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28868. var indicesInit = function (i) {
  28869. var offset = (submesh.indexStart / 3) + i;
  28870. var pos = (offset * 3);
  28871. var i0 = indices[pos + 0];
  28872. var i1 = indices[pos + 1];
  28873. var i2 = indices[pos + 2];
  28874. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28875. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28876. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28877. var triangle = new DecimationTriangle([v0, v1, v2]);
  28878. triangle.originalOffset = pos;
  28879. _this.triangles.push(triangle);
  28880. };
  28881. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28882. _this.init(callback);
  28883. });
  28884. });
  28885. };
  28886. QuadraticErrorSimplification.prototype.init = function (callback) {
  28887. var _this = this;
  28888. var triangleInit1 = function (i) {
  28889. var t = _this.triangles[i];
  28890. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28891. for (var j = 0; j < 3; j++) {
  28892. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  28893. }
  28894. };
  28895. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28896. var triangleInit2 = function (i) {
  28897. var t = _this.triangles[i];
  28898. for (var j = 0; j < 3; ++j) {
  28899. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28900. }
  28901. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28902. };
  28903. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28904. _this.initialized = true;
  28905. callback();
  28906. });
  28907. });
  28908. };
  28909. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28910. var newTriangles = [];
  28911. var i;
  28912. for (i = 0; i < this.vertices.length; ++i) {
  28913. this.vertices[i].triangleCount = 0;
  28914. }
  28915. var t;
  28916. var j;
  28917. for (i = 0; i < this.triangles.length; ++i) {
  28918. if (!this.triangles[i].deleted) {
  28919. t = this.triangles[i];
  28920. for (j = 0; j < 3; ++j) {
  28921. t.vertices[j].triangleCount = 1;
  28922. }
  28923. newTriangles.push(t);
  28924. }
  28925. }
  28926. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28927. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28928. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28929. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28930. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28931. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28932. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28933. var vertexCount = 0;
  28934. for (i = 0; i < this.vertices.length; ++i) {
  28935. var vertex = this.vertices[i];
  28936. vertex.id = vertexCount;
  28937. if (vertex.triangleCount) {
  28938. vertex.originalOffsets.forEach(function (originalOffset) {
  28939. newPositionData.push(vertex.position.x);
  28940. newPositionData.push(vertex.position.y);
  28941. newPositionData.push(vertex.position.z);
  28942. newNormalData.push(normalData[originalOffset * 3]);
  28943. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28944. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28945. if (uvs && uvs.length) {
  28946. newUVsData.push(uvs[(originalOffset * 2)]);
  28947. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28948. }
  28949. else if (colorsData && colorsData.length) {
  28950. newColorsData.push(colorsData[(originalOffset * 4)]);
  28951. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28952. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28953. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28954. }
  28955. ++vertexCount;
  28956. });
  28957. }
  28958. }
  28959. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28960. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28961. var submeshesArray = this._reconstructedMesh.subMeshes;
  28962. this._reconstructedMesh.subMeshes = [];
  28963. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28964. var originalIndices = this._mesh.getIndices();
  28965. for (i = 0; i < newTriangles.length; ++i) {
  28966. var t = newTriangles[i];
  28967. //now get the new referencing point for each vertex
  28968. [0, 1, 2].forEach(function (idx) {
  28969. var id = originalIndices[t.originalOffset + idx];
  28970. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28971. if (offset < 0)
  28972. offset = 0;
  28973. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28974. });
  28975. }
  28976. //overwriting the old vertex buffers and indices.
  28977. this._reconstructedMesh.setIndices(newIndicesArray);
  28978. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28979. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28980. if (newUVsData.length > 0)
  28981. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28982. if (newColorsData.length > 0)
  28983. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28984. //create submesh
  28985. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28986. if (submeshIndex > 0) {
  28987. this._reconstructedMesh.subMeshes = [];
  28988. submeshesArray.forEach(function (submesh) {
  28989. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28990. });
  28991. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28992. }
  28993. };
  28994. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28995. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28996. this._reconstructedMesh.material = this._mesh.material;
  28997. this._reconstructedMesh.parent = this._mesh.parent;
  28998. this._reconstructedMesh.isVisible = false;
  28999. };
  29000. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29001. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29002. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29003. if (t.deleted)
  29004. continue;
  29005. var s = this.references[vertex1.triangleStart + i].vertexId;
  29006. var v1 = t.vertices[(s + 1) % 3];
  29007. var v2 = t.vertices[(s + 2) % 3];
  29008. if ((v1 === vertex2 || v2 === vertex2)) {
  29009. deletedArray[i] = true;
  29010. delTr.push(t);
  29011. continue;
  29012. }
  29013. var d1 = v1.position.subtract(point);
  29014. d1 = d1.normalize();
  29015. var d2 = v2.position.subtract(point);
  29016. d2 = d2.normalize();
  29017. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29018. return true;
  29019. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29020. deletedArray[i] = false;
  29021. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29022. return true;
  29023. }
  29024. return false;
  29025. };
  29026. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29027. var newDeleted = deletedTriangles;
  29028. for (var i = 0; i < vertex.triangleCount; ++i) {
  29029. var ref = this.references[vertex.triangleStart + i];
  29030. var t = this.triangles[ref.triangleId];
  29031. if (t.deleted)
  29032. continue;
  29033. if (deletedArray[i] && t.deletePending) {
  29034. t.deleted = true;
  29035. newDeleted++;
  29036. continue;
  29037. }
  29038. t.vertices[ref.vertexId] = origVertex;
  29039. t.isDirty = true;
  29040. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29041. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29042. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29043. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29044. this.references.push(ref);
  29045. }
  29046. return newDeleted;
  29047. };
  29048. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29049. for (var i = 0; i < this.vertices.length; ++i) {
  29050. var vCount = [];
  29051. var vId = [];
  29052. var v = this.vertices[i];
  29053. var j;
  29054. for (j = 0; j < v.triangleCount; ++j) {
  29055. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29056. for (var ii = 0; ii < 3; ii++) {
  29057. var ofs = 0;
  29058. var vv = triangle.vertices[ii];
  29059. while (ofs < vCount.length) {
  29060. if (vId[ofs] === vv.id)
  29061. break;
  29062. ++ofs;
  29063. }
  29064. if (ofs === vCount.length) {
  29065. vCount.push(1);
  29066. vId.push(vv.id);
  29067. }
  29068. else {
  29069. vCount[ofs]++;
  29070. }
  29071. }
  29072. }
  29073. for (j = 0; j < vCount.length; ++j) {
  29074. if (vCount[j] === 1) {
  29075. this.vertices[vId[j]].isBorder = true;
  29076. }
  29077. else {
  29078. this.vertices[vId[j]].isBorder = false;
  29079. }
  29080. }
  29081. }
  29082. };
  29083. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29084. if (identifyBorders === void 0) { identifyBorders = false; }
  29085. var i;
  29086. if (!identifyBorders) {
  29087. var newTrianglesVector = [];
  29088. for (i = 0; i < this.triangles.length; ++i) {
  29089. if (!this.triangles[i].deleted) {
  29090. newTrianglesVector.push(this.triangles[i]);
  29091. }
  29092. }
  29093. this.triangles = newTrianglesVector;
  29094. }
  29095. for (i = 0; i < this.vertices.length; ++i) {
  29096. this.vertices[i].triangleCount = 0;
  29097. this.vertices[i].triangleStart = 0;
  29098. }
  29099. var t;
  29100. var j;
  29101. var v;
  29102. for (i = 0; i < this.triangles.length; ++i) {
  29103. t = this.triangles[i];
  29104. for (j = 0; j < 3; ++j) {
  29105. v = t.vertices[j];
  29106. v.triangleCount++;
  29107. }
  29108. }
  29109. var tStart = 0;
  29110. for (i = 0; i < this.vertices.length; ++i) {
  29111. this.vertices[i].triangleStart = tStart;
  29112. tStart += this.vertices[i].triangleCount;
  29113. this.vertices[i].triangleCount = 0;
  29114. }
  29115. var newReferences = new Array(this.triangles.length * 3);
  29116. for (i = 0; i < this.triangles.length; ++i) {
  29117. t = this.triangles[i];
  29118. for (j = 0; j < 3; ++j) {
  29119. v = t.vertices[j];
  29120. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29121. v.triangleCount++;
  29122. }
  29123. }
  29124. this.references = newReferences;
  29125. if (identifyBorders) {
  29126. this.identifyBorder();
  29127. }
  29128. };
  29129. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29130. var x = point.x;
  29131. var y = point.y;
  29132. var z = point.z;
  29133. 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];
  29134. };
  29135. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29136. var q = vertex1.q.add(vertex2.q);
  29137. var border = vertex1.isBorder && vertex2.isBorder;
  29138. var error = 0;
  29139. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29140. if (qDet !== 0 && !border) {
  29141. if (!pointResult) {
  29142. pointResult = BABYLON.Vector3.Zero();
  29143. }
  29144. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29145. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29146. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29147. error = this.vertexError(q, pointResult);
  29148. }
  29149. else {
  29150. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29151. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29152. var error1 = this.vertexError(q, vertex1.position);
  29153. var error2 = this.vertexError(q, vertex2.position);
  29154. var error3 = this.vertexError(q, p3);
  29155. error = Math.min(error1, error2, error3);
  29156. if (error === error1) {
  29157. if (pointResult) {
  29158. pointResult.copyFrom(vertex1.position);
  29159. }
  29160. }
  29161. else if (error === error2) {
  29162. if (pointResult) {
  29163. pointResult.copyFrom(vertex2.position);
  29164. }
  29165. }
  29166. else {
  29167. if (pointResult) {
  29168. pointResult.copyFrom(p3);
  29169. }
  29170. }
  29171. }
  29172. return error;
  29173. };
  29174. return QuadraticErrorSimplification;
  29175. })();
  29176. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29177. })(BABYLON || (BABYLON = {}));
  29178. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29179. (function (BABYLON) {
  29180. var Analyser = (function () {
  29181. function Analyser(scene) {
  29182. this.SMOOTHING = 0.75;
  29183. this.FFT_SIZE = 512;
  29184. this.BARGRAPHAMPLITUDE = 256;
  29185. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29186. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29187. this._scene = scene;
  29188. this._audioEngine = BABYLON.Engine.audioEngine;
  29189. if (this._audioEngine.canUseWebAudio) {
  29190. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29191. this._webAudioAnalyser.minDecibels = -140;
  29192. this._webAudioAnalyser.maxDecibels = 0;
  29193. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29194. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29195. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29196. }
  29197. }
  29198. Analyser.prototype.getFrequencyBinCount = function () {
  29199. if (this._audioEngine.canUseWebAudio) {
  29200. return this._webAudioAnalyser.frequencyBinCount;
  29201. }
  29202. else {
  29203. return 0;
  29204. }
  29205. };
  29206. Analyser.prototype.getByteFrequencyData = function () {
  29207. if (this._audioEngine.canUseWebAudio) {
  29208. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29209. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29210. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29211. }
  29212. return this._byteFreqs;
  29213. };
  29214. Analyser.prototype.getByteTimeDomainData = function () {
  29215. if (this._audioEngine.canUseWebAudio) {
  29216. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29217. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29218. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29219. }
  29220. return this._byteTime;
  29221. };
  29222. Analyser.prototype.getFloatFrequencyData = function () {
  29223. if (this._audioEngine.canUseWebAudio) {
  29224. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29225. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29226. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29227. }
  29228. return this._floatFreqs;
  29229. };
  29230. Analyser.prototype.drawDebugCanvas = function () {
  29231. var _this = this;
  29232. if (this._audioEngine.canUseWebAudio) {
  29233. if (!this._debugCanvas) {
  29234. this._debugCanvas = document.createElement("canvas");
  29235. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29236. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29237. this._debugCanvas.style.position = "absolute";
  29238. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29239. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29240. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29241. document.body.appendChild(this._debugCanvas);
  29242. this._registerFunc = function () {
  29243. _this.drawDebugCanvas();
  29244. };
  29245. this._scene.registerBeforeRender(this._registerFunc);
  29246. }
  29247. if (this._registerFunc) {
  29248. var workingArray = this.getByteFrequencyData();
  29249. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29250. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29251. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29252. var value = workingArray[i];
  29253. var percent = value / this.BARGRAPHAMPLITUDE;
  29254. var height = this.DEBUGCANVASSIZE.height * percent;
  29255. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29256. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29257. var hue = i / this.getFrequencyBinCount() * 360;
  29258. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29259. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29260. }
  29261. }
  29262. }
  29263. };
  29264. Analyser.prototype.stopDebugCanvas = function () {
  29265. if (this._debugCanvas) {
  29266. this._scene.unregisterBeforeRender(this._registerFunc);
  29267. this._registerFunc = null;
  29268. document.body.removeChild(this._debugCanvas);
  29269. this._debugCanvas = null;
  29270. this._debugCanvasContext = null;
  29271. }
  29272. };
  29273. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29274. if (this._audioEngine.canUseWebAudio) {
  29275. inputAudioNode.connect(this._webAudioAnalyser);
  29276. this._webAudioAnalyser.connect(outputAudioNode);
  29277. }
  29278. };
  29279. Analyser.prototype.dispose = function () {
  29280. if (this._audioEngine.canUseWebAudio) {
  29281. this._webAudioAnalyser.disconnect();
  29282. }
  29283. };
  29284. return Analyser;
  29285. })();
  29286. BABYLON.Analyser = Analyser;
  29287. })(BABYLON || (BABYLON = {}));
  29288. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29289. (function (BABYLON) {
  29290. var DepthRenderer = (function () {
  29291. function DepthRenderer(scene, type) {
  29292. var _this = this;
  29293. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29294. this._viewMatrix = BABYLON.Matrix.Zero();
  29295. this._projectionMatrix = BABYLON.Matrix.Zero();
  29296. this._transformMatrix = BABYLON.Matrix.Zero();
  29297. this._worldViewProjection = BABYLON.Matrix.Zero();
  29298. this._scene = scene;
  29299. var engine = scene.getEngine();
  29300. // Render target
  29301. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29302. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29303. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29304. this._depthMap.refreshRate = 1;
  29305. this._depthMap.renderParticles = false;
  29306. this._depthMap.renderList = null;
  29307. // Custom render function
  29308. var renderSubMesh = function (subMesh) {
  29309. var mesh = subMesh.getRenderingMesh();
  29310. var scene = _this._scene;
  29311. var engine = scene.getEngine();
  29312. // Culling
  29313. engine.setState(subMesh.getMaterial().backFaceCulling);
  29314. // Managing instances
  29315. var batch = mesh._getInstancesRenderList(subMesh._id);
  29316. if (batch.mustReturn) {
  29317. return;
  29318. }
  29319. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29320. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29321. engine.enableEffect(_this._effect);
  29322. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29323. var material = subMesh.getMaterial();
  29324. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29325. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29326. // Alpha test
  29327. if (material && material.needAlphaTesting()) {
  29328. var alphaTexture = material.getAlphaTestTexture();
  29329. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29330. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29331. }
  29332. // Bones
  29333. if (mesh.useBones) {
  29334. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29335. }
  29336. // Draw
  29337. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29338. }
  29339. };
  29340. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29341. var index;
  29342. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29343. renderSubMesh(opaqueSubMeshes.data[index]);
  29344. }
  29345. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29346. renderSubMesh(alphaTestSubMeshes.data[index]);
  29347. }
  29348. };
  29349. }
  29350. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29351. var defines = [];
  29352. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29353. var mesh = subMesh.getMesh();
  29354. var scene = mesh.getScene();
  29355. var material = subMesh.getMaterial();
  29356. // Alpha test
  29357. if (material && material.needAlphaTesting()) {
  29358. defines.push("#define ALPHATEST");
  29359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29360. attribs.push(BABYLON.VertexBuffer.UVKind);
  29361. defines.push("#define UV1");
  29362. }
  29363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29365. defines.push("#define UV2");
  29366. }
  29367. }
  29368. // Bones
  29369. if (mesh.useBones) {
  29370. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29371. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29372. defines.push("#define BONES");
  29373. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29374. }
  29375. // Instances
  29376. if (useInstances) {
  29377. defines.push("#define INSTANCES");
  29378. attribs.push("world0");
  29379. attribs.push("world1");
  29380. attribs.push("world2");
  29381. attribs.push("world3");
  29382. }
  29383. // Get correct effect
  29384. var join = defines.join("\n");
  29385. if (this._cachedDefines !== join) {
  29386. this._cachedDefines = join;
  29387. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29388. }
  29389. return this._effect.isReady();
  29390. };
  29391. DepthRenderer.prototype.getDepthMap = function () {
  29392. return this._depthMap;
  29393. };
  29394. // Methods
  29395. DepthRenderer.prototype.dispose = function () {
  29396. this._depthMap.dispose();
  29397. };
  29398. return DepthRenderer;
  29399. })();
  29400. BABYLON.DepthRenderer = DepthRenderer;
  29401. })(BABYLON || (BABYLON = {}));
  29402. //# sourceMappingURL=babylon.depthRenderer.js.map
  29403. var BABYLON;
  29404. (function (BABYLON) {
  29405. var SSAORenderingPipeline = (function (_super) {
  29406. __extends(SSAORenderingPipeline, _super);
  29407. /**
  29408. * @constructor
  29409. * @param {string} name - The rendering pipeline name
  29410. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29411. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  29412. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29413. */
  29414. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29415. var _this = this;
  29416. _super.call(this, scene.getEngine(), name);
  29417. // Members
  29418. /**
  29419. * The PassPostProcess id in the pipeline that contains the original scene color
  29420. * @type {string}
  29421. */
  29422. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29423. /**
  29424. * The SSAO PostProcess id in the pipeline
  29425. * @type {string}
  29426. */
  29427. this.SSAORenderEffect = "SSAORenderEffect";
  29428. /**
  29429. * The horizontal blur PostProcess id in the pipeline
  29430. * @type {string}
  29431. */
  29432. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29433. /**
  29434. * The vertical blur PostProcess id in the pipeline
  29435. * @type {string}
  29436. */
  29437. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29438. /**
  29439. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29440. * @type {string}
  29441. */
  29442. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29443. /**
  29444. * The output strength of the SSAO post-process. Default value is 1.0.
  29445. * @type {number}
  29446. */
  29447. this.totalStrength = 1.0;
  29448. /**
  29449. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29450. * @type {number}
  29451. */
  29452. this.radius = 0.0002;
  29453. /**
  29454. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29455. * Must not be equal to fallOff and superior to fallOff.
  29456. * Default value is 0.0075
  29457. * @type {number}
  29458. */
  29459. this.area = 0.0075;
  29460. /**
  29461. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29462. * Must not be equal to area and inferior to area.
  29463. * Default value is 0.0002
  29464. * @type {number}
  29465. */
  29466. this.fallOff = 0.0002;
  29467. this._firstUpdate = true;
  29468. this._scene = scene;
  29469. // Set up assets
  29470. this._createRandomTexture();
  29471. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29472. var ssaoRatio = ratio.ssaoRatio || ratio;
  29473. var combineRatio = ratio.combineRatio || ratio;
  29474. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29475. this._createSSAOPostProcess(ssaoRatio);
  29476. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29477. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29478. this._createSSAOCombinePostProcess(combineRatio);
  29479. // Set up pipeline
  29480. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29481. return _this._originalColorPostProcess;
  29482. }, true));
  29483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29484. return _this._ssaoPostProcess;
  29485. }, true));
  29486. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29487. return _this._blurHPostProcess;
  29488. }, true));
  29489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29490. return _this._blurVPostProcess;
  29491. }, true));
  29492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29493. return _this._ssaoCombinePostProcess;
  29494. }, true));
  29495. // Finish
  29496. scene.postProcessRenderPipelineManager.addPipeline(this);
  29497. if (cameras)
  29498. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29499. }
  29500. // Public Methods
  29501. /**
  29502. * Returns the horizontal blur PostProcess
  29503. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29504. */
  29505. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29506. return this._blurHPostProcess;
  29507. };
  29508. /**
  29509. * Returns the vertical blur PostProcess
  29510. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29511. */
  29512. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29513. return this._blurVPostProcess;
  29514. };
  29515. /**
  29516. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29517. */
  29518. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29519. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29520. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29521. this._originalColorPostProcess = undefined;
  29522. this._ssaoPostProcess = undefined;
  29523. this._blurHPostProcess = undefined;
  29524. this._blurVPostProcess = undefined;
  29525. this._ssaoCombinePostProcess = undefined;
  29526. this._randomTexture.dispose();
  29527. if (disableDepthRender)
  29528. this._scene.disableDepthRenderer();
  29529. };
  29530. // Private Methods
  29531. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29532. var _this = this;
  29533. var sampleSphere = [
  29534. 0.5381,
  29535. 0.1856,
  29536. -0.4319,
  29537. 0.1379,
  29538. 0.2486,
  29539. 0.4430,
  29540. 0.3371,
  29541. 0.5679,
  29542. -0.0057,
  29543. -0.6999,
  29544. -0.0451,
  29545. -0.0019,
  29546. 0.0689,
  29547. -0.1598,
  29548. -0.8547,
  29549. 0.0560,
  29550. 0.0069,
  29551. -0.1843,
  29552. -0.0146,
  29553. 0.1402,
  29554. 0.0762,
  29555. 0.0100,
  29556. -0.1924,
  29557. -0.0344,
  29558. -0.3577,
  29559. -0.5301,
  29560. -0.4358,
  29561. -0.3169,
  29562. 0.1063,
  29563. 0.0158,
  29564. 0.0103,
  29565. -0.5869,
  29566. 0.0046,
  29567. -0.0897,
  29568. -0.4940,
  29569. 0.3287,
  29570. 0.7119,
  29571. -0.0154,
  29572. -0.0918,
  29573. -0.0533,
  29574. 0.0596,
  29575. -0.5411,
  29576. 0.0352,
  29577. -0.0631,
  29578. 0.5460,
  29579. -0.4776,
  29580. 0.2847,
  29581. -0.0271
  29582. ];
  29583. var samplesFactor = 1.0 / 16.0;
  29584. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29585. this._ssaoPostProcess.onApply = function (effect) {
  29586. if (_this._firstUpdate) {
  29587. effect.setArray3("sampleSphere", sampleSphere);
  29588. effect.setFloat("samplesFactor", samplesFactor);
  29589. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29590. _this._firstUpdate = false;
  29591. }
  29592. effect.setFloat("totalStrength", _this.totalStrength);
  29593. effect.setFloat("radius", _this.radius);
  29594. effect.setFloat("area", _this.area);
  29595. effect.setFloat("fallOff", _this.fallOff);
  29596. effect.setTexture("textureSampler", _this._depthTexture);
  29597. effect.setTexture("randomSampler", _this._randomTexture);
  29598. };
  29599. };
  29600. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29601. var _this = this;
  29602. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29603. this._ssaoCombinePostProcess.onApply = function (effect) {
  29604. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29605. };
  29606. };
  29607. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29608. var size = 512;
  29609. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29610. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29611. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29612. var context = this._randomTexture.getContext();
  29613. var rand = function (min, max) {
  29614. return Math.random() * (max - min) + min;
  29615. };
  29616. for (var x = 0; x < size; x++) {
  29617. for (var y = 0; y < size; y++) {
  29618. var randVector = BABYLON.Vector3.Zero();
  29619. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29620. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29621. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29622. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29623. context.fillRect(x, y, 1, 1);
  29624. }
  29625. }
  29626. this._randomTexture.update(false);
  29627. };
  29628. return SSAORenderingPipeline;
  29629. })(BABYLON.PostProcessRenderPipeline);
  29630. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29631. })(BABYLON || (BABYLON = {}));
  29632. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29633. var BABYLON;
  29634. (function (BABYLON) {
  29635. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29636. var VolumetricLightScatteringPostProcess = (function (_super) {
  29637. __extends(VolumetricLightScatteringPostProcess, _super);
  29638. /**
  29639. * @constructor
  29640. * @param {string} name - The post-process name
  29641. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29642. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29643. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29644. * @param {number} samples - The post-process quality, default 100
  29645. * @param {number} samplingMode - The post-process filtering mode
  29646. * @param {BABYLON.Engine} engine - The babylon engine
  29647. * @param {boolean} reusable - If the post-process is reusable
  29648. */
  29649. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29650. var _this = this;
  29651. if (samples === void 0) { samples = 100; }
  29652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29653. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29654. this._screenCoordinates = BABYLON.Vector2.Zero();
  29655. /**
  29656. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29657. * @type {boolean}
  29658. */
  29659. this.useCustomMeshPosition = false;
  29660. /**
  29661. * If the post-process should inverse the light scattering direction
  29662. * @type {boolean}
  29663. */
  29664. this.invert = true;
  29665. /**
  29666. * Array containing the excluded meshes not rendered in the internal pass
  29667. */
  29668. this.excludedMeshes = new Array();
  29669. this.exposure = 0.3;
  29670. this.decay = 0.96815;
  29671. this.weight = 0.58767;
  29672. this.density = 0.926;
  29673. var scene = camera.getScene();
  29674. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29675. // Configure mesh
  29676. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29677. // Configure
  29678. this._createPass(scene, ratio.passRatio || ratio);
  29679. this.onApply = function (effect) {
  29680. _this._updateMeshScreenCoordinates(scene);
  29681. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29682. effect.setFloat("exposure", _this.exposure);
  29683. effect.setFloat("decay", _this.decay);
  29684. effect.setFloat("weight", _this.weight);
  29685. effect.setFloat("density", _this.density);
  29686. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29687. };
  29688. }
  29689. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29690. var mesh = subMesh.getMesh();
  29691. var defines = [];
  29692. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29693. var material = subMesh.getMaterial();
  29694. var needUV = false;
  29695. // Render this.mesh as default
  29696. if (mesh === this.mesh) {
  29697. defines.push("#define BASIC_RENDER");
  29698. defines.push("#define NEED_UV");
  29699. needUV = true;
  29700. }
  29701. // Alpha test
  29702. if (material) {
  29703. if (material.needAlphaTesting() || mesh === this.mesh)
  29704. defines.push("#define ALPHATEST");
  29705. if (material.opacityTexture !== undefined) {
  29706. defines.push("#define OPACITY");
  29707. if (material.opacityTexture.getAlphaFromRGB)
  29708. defines.push("#define OPACITYRGB");
  29709. if (!needUV)
  29710. defines.push("#define NEED_UV");
  29711. }
  29712. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29713. attribs.push(BABYLON.VertexBuffer.UVKind);
  29714. defines.push("#define UV1");
  29715. }
  29716. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29717. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29718. defines.push("#define UV2");
  29719. }
  29720. }
  29721. // Bones
  29722. if (mesh.useBones) {
  29723. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29724. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29725. defines.push("#define BONES");
  29726. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29727. }
  29728. // Instances
  29729. if (useInstances) {
  29730. defines.push("#define INSTANCES");
  29731. attribs.push("world0");
  29732. attribs.push("world1");
  29733. attribs.push("world2");
  29734. attribs.push("world3");
  29735. }
  29736. // Get correct effect
  29737. var join = defines.join("\n");
  29738. if (this._cachedDefines !== join) {
  29739. this._cachedDefines = join;
  29740. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29741. }
  29742. return this._volumetricLightScatteringPass.isReady();
  29743. };
  29744. /**
  29745. * Sets the new light position for light scattering effect
  29746. * @param {BABYLON.Vector3} The new custom light position
  29747. */
  29748. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29749. this._customMeshPosition = position;
  29750. };
  29751. /**
  29752. * Returns the light position for light scattering effect
  29753. * @return {BABYLON.Vector3} The custom light position
  29754. */
  29755. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29756. return this._customMeshPosition;
  29757. };
  29758. /**
  29759. * Disposes the internal assets and detaches the post-process from the camera
  29760. */
  29761. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29762. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29763. if (rttIndex !== -1) {
  29764. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29765. }
  29766. this._volumetricLightScatteringRTT.dispose();
  29767. _super.prototype.dispose.call(this, camera);
  29768. };
  29769. /**
  29770. * Returns the render target texture used by the post-process
  29771. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29772. */
  29773. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29774. return this._volumetricLightScatteringRTT;
  29775. };
  29776. // Private methods
  29777. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29778. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29779. return true;
  29780. }
  29781. return false;
  29782. };
  29783. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29784. var _this = this;
  29785. var engine = scene.getEngine();
  29786. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29787. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29788. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29789. this._volumetricLightScatteringRTT.renderList = null;
  29790. this._volumetricLightScatteringRTT.renderParticles = false;
  29791. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29792. // Custom render function for submeshes
  29793. var renderSubMesh = function (subMesh) {
  29794. var mesh = subMesh.getRenderingMesh();
  29795. if (_this._meshExcluded(mesh)) {
  29796. return;
  29797. }
  29798. var scene = mesh.getScene();
  29799. var engine = scene.getEngine();
  29800. // Culling
  29801. engine.setState(subMesh.getMaterial().backFaceCulling);
  29802. // Managing instances
  29803. var batch = mesh._getInstancesRenderList(subMesh._id);
  29804. if (batch.mustReturn) {
  29805. return;
  29806. }
  29807. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29808. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29809. engine.enableEffect(_this._volumetricLightScatteringPass);
  29810. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29811. var material = subMesh.getMaterial();
  29812. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29813. // Alpha test
  29814. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29815. var alphaTexture = material.getAlphaTestTexture();
  29816. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29817. if (alphaTexture) {
  29818. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29819. }
  29820. if (material.opacityTexture !== undefined) {
  29821. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29822. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29823. }
  29824. }
  29825. // Bones
  29826. if (mesh.useBones) {
  29827. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29828. }
  29829. // Draw
  29830. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29831. }
  29832. };
  29833. // Render target texture callbacks
  29834. var savedSceneClearColor;
  29835. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29836. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29837. savedSceneClearColor = scene.clearColor;
  29838. scene.clearColor = sceneClearColor;
  29839. };
  29840. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29841. scene.clearColor = savedSceneClearColor;
  29842. };
  29843. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29844. var engine = scene.getEngine();
  29845. var index;
  29846. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29847. renderSubMesh(opaqueSubMeshes.data[index]);
  29848. }
  29849. engine.setAlphaTesting(true);
  29850. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29851. renderSubMesh(alphaTestSubMeshes.data[index]);
  29852. }
  29853. engine.setAlphaTesting(false);
  29854. if (transparentSubMeshes.length) {
  29855. for (index = 0; index < transparentSubMeshes.length; index++) {
  29856. var submesh = transparentSubMeshes.data[index];
  29857. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29858. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29859. }
  29860. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29861. sortedArray.sort(function (a, b) {
  29862. // Alpha index first
  29863. if (a._alphaIndex > b._alphaIndex) {
  29864. return 1;
  29865. }
  29866. if (a._alphaIndex < b._alphaIndex) {
  29867. return -1;
  29868. }
  29869. // Then distance to camera
  29870. if (a._distanceToCamera < b._distanceToCamera) {
  29871. return 1;
  29872. }
  29873. if (a._distanceToCamera > b._distanceToCamera) {
  29874. return -1;
  29875. }
  29876. return 0;
  29877. });
  29878. // Render sub meshes
  29879. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29880. for (index = 0; index < sortedArray.length; index++) {
  29881. renderSubMesh(sortedArray[index]);
  29882. }
  29883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29884. }
  29885. };
  29886. };
  29887. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29888. var transform = scene.getTransformMatrix();
  29889. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29890. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29891. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29892. if (this.invert)
  29893. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29894. };
  29895. // Static methods
  29896. /**
  29897. * Creates a default mesh for the Volumeric Light Scattering post-process
  29898. * @param {string} The mesh name
  29899. * @param {BABYLON.Scene} The scene where to create the mesh
  29900. * @return {BABYLON.Mesh} the default mesh
  29901. */
  29902. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29903. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29904. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29905. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29906. return mesh;
  29907. };
  29908. return VolumetricLightScatteringPostProcess;
  29909. })(BABYLON.PostProcess);
  29910. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29911. })(BABYLON || (BABYLON = {}));
  29912. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29913. var BABYLON;
  29914. (function (BABYLON) {
  29915. var LensRenderingPipeline = (function (_super) {
  29916. __extends(LensRenderingPipeline, _super);
  29917. /**
  29918. * @constructor
  29919. *
  29920. * Effect parameters are as follow:
  29921. * {
  29922. * chromatic_aberration: number; // from 0 to x (1 for realism)
  29923. * edge_blur: number; // from 0 to x (1 for realism)
  29924. * distortion: number; // from 0 to x (1 for realism)
  29925. * grain_amount: number; // from 0 to 1
  29926. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29927. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  29928. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29929. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29930. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  29931. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  29932. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29933. * }
  29934. * Note: if an effect parameter is unset, effect is disabled
  29935. *
  29936. * @param {string} name - The rendering pipeline name
  29937. * @param {object} parameters - An object containing all parameters (see above)
  29938. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29939. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29940. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29941. */
  29942. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29943. var _this = this;
  29944. if (ratio === void 0) { ratio = 1.0; }
  29945. _super.call(this, scene.getEngine(), name);
  29946. // Lens effects can be of the following:
  29947. // - chromatic aberration (slight shift of RGB colors)
  29948. // - blur on the edge of the lens
  29949. // - lens distortion
  29950. // - depth-of-field blur & highlights enhancing
  29951. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  29952. // - grain effect (noise or custom texture)
  29953. // Two additional texture samplers are needed:
  29954. // - depth map (for depth-of-field)
  29955. // - grain texture
  29956. /**
  29957. * The chromatic aberration PostProcess id in the pipeline
  29958. * @type {string}
  29959. */
  29960. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29961. /**
  29962. * The highlights enhancing PostProcess id in the pipeline
  29963. * @type {string}
  29964. */
  29965. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  29966. /**
  29967. * The depth-of-field PostProcess id in the pipeline
  29968. * @type {string}
  29969. */
  29970. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29971. this._scene = scene;
  29972. // Fetch texture samplers
  29973. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29974. if (parameters.grain_texture) {
  29975. this._grainTexture = parameters.grain_texture;
  29976. }
  29977. else {
  29978. this._createGrainTexture();
  29979. }
  29980. // save parameters
  29981. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29982. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29983. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29984. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29985. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  29986. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29987. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29988. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29989. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29990. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29991. // Create effects
  29992. this._createChromaticAberrationPostProcess(ratio);
  29993. this._createHighlightsPostProcess(ratio);
  29994. this._createDepthOfFieldPostProcess(ratio);
  29995. // Set up pipeline
  29996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29997. return _this._chromaticAberrationPostProcess;
  29998. }, true));
  29999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30000. return _this._highlightsPostProcess;
  30001. }, true));
  30002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30003. return _this._depthOfFieldPostProcess;
  30004. }, true));
  30005. if (this._highlightsGain == -1) {
  30006. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30007. }
  30008. // Finish
  30009. scene.postProcessRenderPipelineManager.addPipeline(this);
  30010. if (cameras) {
  30011. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30012. }
  30013. }
  30014. // public methods (self explanatory)
  30015. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30016. this._edgeBlur = amount;
  30017. };
  30018. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30019. this._edgeBlur = 0;
  30020. };
  30021. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30022. this._grainAmount = amount;
  30023. };
  30024. LensRenderingPipeline.prototype.disableGrain = function () {
  30025. this._grainAmount = 0;
  30026. };
  30027. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30028. this._chromaticAberration = amount;
  30029. };
  30030. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30031. this._chromaticAberration = 0;
  30032. };
  30033. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30034. this._distortion = amount;
  30035. };
  30036. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30037. this._distortion = 0;
  30038. };
  30039. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30040. this._dofDepth = amount;
  30041. };
  30042. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30043. this._dofDepth = -1;
  30044. };
  30045. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30046. this._dofAperture = amount;
  30047. };
  30048. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30049. this._dofPentagon = true;
  30050. };
  30051. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30052. this._dofPentagon = false;
  30053. };
  30054. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30055. this._blurNoise = true;
  30056. };
  30057. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30058. this._blurNoise = false;
  30059. };
  30060. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30061. this._highlightsGain = amount;
  30062. };
  30063. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30064. if (this._highlightsGain == -1) {
  30065. this._highlightsGain = 1.0;
  30066. }
  30067. this._highlightsThreshold = amount;
  30068. };
  30069. LensRenderingPipeline.prototype.disableHighlights = function () {
  30070. this._highlightsGain = -1;
  30071. };
  30072. /**
  30073. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30074. */
  30075. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30076. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30077. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30078. this._chromaticAberrationPostProcess = undefined;
  30079. this._highlightsPostProcess = undefined;
  30080. this._depthOfFieldPostProcess = undefined;
  30081. this._grainTexture.dispose();
  30082. if (disableDepthRender)
  30083. this._scene.disableDepthRenderer();
  30084. };
  30085. // colors shifting and distortion
  30086. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30087. var _this = this;
  30088. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30089. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30090. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30091. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30092. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30093. };
  30094. };
  30095. // highlights enhancing
  30096. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30097. var _this = this;
  30098. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30099. this._highlightsPostProcess.onApply = function (effect) {
  30100. effect.setFloat('gain', _this._highlightsGain);
  30101. effect.setFloat('threshold', _this._highlightsThreshold);
  30102. effect.setBool('pentagon', _this._dofPentagon);
  30103. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30104. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30105. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30106. };
  30107. };
  30108. // colors shifting and distortion
  30109. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30110. var _this = this;
  30111. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30112. "focus_depth",
  30113. "aperture",
  30114. "pentagon",
  30115. "maxZ",
  30116. "edge_blur",
  30117. "chromatic_aberration",
  30118. "distortion",
  30119. "blur_noise",
  30120. "grain_amount",
  30121. "screen_width",
  30122. "screen_height",
  30123. "highlights"
  30124. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30125. this._depthOfFieldPostProcess.onApply = function (effect) {
  30126. effect.setBool('blur_noise', _this._blurNoise);
  30127. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30128. effect.setFloat('grain_amount', _this._grainAmount);
  30129. effect.setTexture("depthSampler", _this._depthTexture);
  30130. effect.setTexture("grainSampler", _this._grainTexture);
  30131. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30132. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30133. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30134. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30135. effect.setFloat('distortion', _this._distortion);
  30136. effect.setFloat('focus_depth', _this._dofDepth);
  30137. effect.setFloat('aperture', _this._dofAperture);
  30138. effect.setFloat('edge_blur', _this._edgeBlur);
  30139. effect.setBool('highlights', (_this._highlightsGain != -1));
  30140. };
  30141. };
  30142. // creates a black and white random noise texture, 512x512
  30143. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30144. var size = 512;
  30145. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30146. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30147. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30148. var context = this._grainTexture.getContext();
  30149. var rand = function (min, max) {
  30150. return Math.random() * (max - min) + min;
  30151. };
  30152. var value;
  30153. for (var x = 0; x < size; x++) {
  30154. for (var y = 0; y < size; y++) {
  30155. value = Math.floor(rand(0.42, 0.58) * 255);
  30156. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30157. context.fillRect(x, y, 1, 1);
  30158. }
  30159. }
  30160. this._grainTexture.update(false);
  30161. };
  30162. return LensRenderingPipeline;
  30163. })(BABYLON.PostProcessRenderPipeline);
  30164. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30165. })(BABYLON || (BABYLON = {}));
  30166. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30167. // This post-process allows the modification of rendered colors by using
  30168. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30169. //
  30170. // The object needs to be provided an url to a texture containing the color
  30171. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30172. // Use an image editing software to tweak the LUT to match your needs.
  30173. //
  30174. // For an example of a color LUT, see here:
  30175. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30176. // For explanations on color grading, see here:
  30177. // http://udn.epicgames.com/Three/ColorGrading.html
  30178. //
  30179. var BABYLON;
  30180. (function (BABYLON) {
  30181. var ColorCorrectionPostProcess = (function (_super) {
  30182. __extends(ColorCorrectionPostProcess, _super);
  30183. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30184. var _this = this;
  30185. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30186. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30187. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30188. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30189. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30190. this.onApply = function (effect) {
  30191. effect.setTexture("colorTable", _this._colorTableTexture);
  30192. };
  30193. }
  30194. return ColorCorrectionPostProcess;
  30195. })(BABYLON.PostProcess);
  30196. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30197. })(BABYLON || (BABYLON = {}));
  30198. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30199. (function (BABYLON) {
  30200. var SmartCollection = (function () {
  30201. function SmartCollection(capacity) {
  30202. if (capacity === void 0) { capacity = 10; }
  30203. this.count = 0;
  30204. this._initialCapacity = capacity;
  30205. this.items = {};
  30206. this._keys = new Array(this._initialCapacity);
  30207. }
  30208. SmartCollection.prototype.add = function (key, item) {
  30209. if (this.items[key] != undefined) {
  30210. return -1;
  30211. }
  30212. this.items[key] = item;
  30213. //literal keys are always strings, but we keep source type of key in _keys array
  30214. this._keys[this.count++] = key;
  30215. if (this.count > this._keys.length) {
  30216. this._keys.length *= 2;
  30217. }
  30218. return this.count;
  30219. };
  30220. SmartCollection.prototype.remove = function (key) {
  30221. if (this.items[key] == undefined) {
  30222. return -1;
  30223. }
  30224. return this.removeItemOfIndex(this.indexOf(key));
  30225. };
  30226. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30227. if (index < this.count && index > -1) {
  30228. delete this.items[this._keys[index]];
  30229. while (index < this.count) {
  30230. this._keys[index] = this._keys[index + 1];
  30231. index++;
  30232. }
  30233. }
  30234. else {
  30235. return -1;
  30236. }
  30237. return --this.count;
  30238. };
  30239. SmartCollection.prototype.indexOf = function (key) {
  30240. for (var i = 0; i !== this.count; i++) {
  30241. if (this._keys[i] === key) {
  30242. return i;
  30243. }
  30244. }
  30245. return -1;
  30246. };
  30247. SmartCollection.prototype.item = function (key) {
  30248. return this.items[key];
  30249. };
  30250. SmartCollection.prototype.getAllKeys = function () {
  30251. if (this.count > 0) {
  30252. var keys = new Array(this.count);
  30253. for (var i = 0; i < this.count; i++) {
  30254. keys[i] = this._keys[i];
  30255. }
  30256. return keys;
  30257. }
  30258. else {
  30259. return undefined;
  30260. }
  30261. };
  30262. SmartCollection.prototype.getKeyByIndex = function (index) {
  30263. if (index < this.count && index > -1) {
  30264. return this._keys[index];
  30265. }
  30266. else {
  30267. return undefined;
  30268. }
  30269. };
  30270. SmartCollection.prototype.getItemByIndex = function (index) {
  30271. if (index < this.count && index > -1) {
  30272. return this.items[this._keys[index]];
  30273. }
  30274. else {
  30275. return undefined;
  30276. }
  30277. };
  30278. SmartCollection.prototype.empty = function () {
  30279. if (this.count > 0) {
  30280. this.count = 0;
  30281. this.items = {};
  30282. this._keys = new Array(this._initialCapacity);
  30283. }
  30284. };
  30285. return SmartCollection;
  30286. })();
  30287. BABYLON.SmartCollection = SmartCollection;
  30288. })(BABYLON || (BABYLON = {}));
  30289. //# sourceMappingURL=babylon.smartCollection.js.map