babylon.2.1-alpha.debug.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511
  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.reciprocalApproximation(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.reciprocalSqrtApproximation(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.reciprocalSqrtApproximation(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.reciprocalSqrtApproximation(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.reciprocalSqrtApproximation(tmp));
  1895. var zero = SIMD.float32x4.splat(0.0);
  1896. s = SIMD.float32x4.neg(s);
  1897. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1898. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1899. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1900. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1901. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1902. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1903. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1905. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1906. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1907. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1908. var b3 = SIMD.float32x4.neg(eye);
  1909. b3 = SIMD.float32x4.withW(b3, 1.0);
  1910. 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)))));
  1911. 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)))));
  1912. 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)))));
  1913. 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)))));
  1914. };
  1915. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1916. var matrix = Matrix.Zero();
  1917. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1918. return matrix;
  1919. };
  1920. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1921. var hw = 2.0 / width;
  1922. var hh = 2.0 / height;
  1923. var id = 1.0 / (zfar - znear);
  1924. var nid = znear / (znear - zfar);
  1925. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1926. };
  1927. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1933. result.m[0] = 2.0 / (right - left);
  1934. result.m[1] = result.m[2] = result.m[3] = 0;
  1935. result.m[5] = 2.0 / (top - bottom);
  1936. result.m[4] = result.m[6] = result.m[7] = 0;
  1937. result.m[10] = -1.0 / (znear - zfar);
  1938. result.m[8] = result.m[9] = result.m[11] = 0;
  1939. result.m[12] = (left + right) / (left - right);
  1940. result.m[13] = (top + bottom) / (bottom - top);
  1941. result.m[14] = znear / (znear - zfar);
  1942. result.m[15] = 1.0;
  1943. };
  1944. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1945. var matrix = Matrix.Zero();
  1946. matrix.m[0] = (2.0 * znear) / width;
  1947. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1948. matrix.m[5] = (2.0 * znear) / height;
  1949. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1950. matrix.m[10] = -zfar / (znear - zfar);
  1951. matrix.m[8] = matrix.m[9] = 0.0;
  1952. matrix.m[11] = 1.0;
  1953. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1954. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1958. var matrix = Matrix.Zero();
  1959. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1960. return matrix;
  1961. };
  1962. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1963. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1964. var tan = 1.0 / (Math.tan(fov * 0.5));
  1965. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1966. if (v_fixed) {
  1967. result.m[0] = tan / aspect;
  1968. }
  1969. else {
  1970. result.m[0] = tan;
  1971. }
  1972. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1973. if (v_fixed) {
  1974. result.m[5] = tan;
  1975. }
  1976. else {
  1977. result.m[5] = tan * aspect;
  1978. }
  1979. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1980. result.m[8] = result.m[9] = 0.0;
  1981. result.m[10] = -zfar / (znear - zfar);
  1982. result.m[11] = 1.0;
  1983. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1984. result.m[14] = (znear * zfar) / (znear - zfar);
  1985. };
  1986. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1987. var cw = viewport.width;
  1988. var ch = viewport.height;
  1989. var cx = viewport.x;
  1990. var cy = viewport.y;
  1991. 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);
  1992. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1993. };
  1994. Matrix.Transpose = function (matrix) {
  1995. var result = new Matrix();
  1996. result.m[0] = matrix.m[0];
  1997. result.m[1] = matrix.m[4];
  1998. result.m[2] = matrix.m[8];
  1999. result.m[3] = matrix.m[12];
  2000. result.m[4] = matrix.m[1];
  2001. result.m[5] = matrix.m[5];
  2002. result.m[6] = matrix.m[9];
  2003. result.m[7] = matrix.m[13];
  2004. result.m[8] = matrix.m[2];
  2005. result.m[9] = matrix.m[6];
  2006. result.m[10] = matrix.m[10];
  2007. result.m[11] = matrix.m[14];
  2008. result.m[12] = matrix.m[3];
  2009. result.m[13] = matrix.m[7];
  2010. result.m[14] = matrix.m[11];
  2011. result.m[15] = matrix.m[15];
  2012. return result;
  2013. };
  2014. Matrix.Reflection = function (plane) {
  2015. var matrix = new Matrix();
  2016. Matrix.ReflectionToRef(plane, matrix);
  2017. return matrix;
  2018. };
  2019. Matrix.ReflectionToRef = function (plane, result) {
  2020. plane.normalize();
  2021. var x = plane.normal.x;
  2022. var y = plane.normal.y;
  2023. var z = plane.normal.z;
  2024. var temp = -2 * x;
  2025. var temp2 = -2 * y;
  2026. var temp3 = -2 * z;
  2027. result.m[0] = (temp * x) + 1;
  2028. result.m[1] = temp2 * x;
  2029. result.m[2] = temp3 * x;
  2030. result.m[3] = 0.0;
  2031. result.m[4] = temp * y;
  2032. result.m[5] = (temp2 * y) + 1;
  2033. result.m[6] = temp3 * y;
  2034. result.m[7] = 0.0;
  2035. result.m[8] = temp * z;
  2036. result.m[9] = temp2 * z;
  2037. result.m[10] = (temp3 * z) + 1;
  2038. result.m[11] = 0.0;
  2039. result.m[12] = temp * plane.d;
  2040. result.m[13] = temp2 * plane.d;
  2041. result.m[14] = temp3 * plane.d;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix._tempQuaternion = new Quaternion();
  2045. Matrix._xAxis = Vector3.Zero();
  2046. Matrix._yAxis = Vector3.Zero();
  2047. Matrix._zAxis = Vector3.Zero();
  2048. return Matrix;
  2049. })();
  2050. BABYLON.Matrix = Matrix;
  2051. var Plane = (function () {
  2052. function Plane(a, b, c, d) {
  2053. this.normal = new Vector3(a, b, c);
  2054. this.d = d;
  2055. }
  2056. Plane.prototype.asArray = function () {
  2057. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2058. };
  2059. // Methods
  2060. Plane.prototype.clone = function () {
  2061. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2062. };
  2063. Plane.prototype.normalize = function () {
  2064. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2065. var magnitude = 0;
  2066. if (norm !== 0) {
  2067. magnitude = 1.0 / norm;
  2068. }
  2069. this.normal.x *= magnitude;
  2070. this.normal.y *= magnitude;
  2071. this.normal.z *= magnitude;
  2072. this.d *= magnitude;
  2073. return this;
  2074. };
  2075. Plane.prototype.transform = function (transformation) {
  2076. var transposedMatrix = Matrix.Transpose(transformation);
  2077. var x = this.normal.x;
  2078. var y = this.normal.y;
  2079. var z = this.normal.z;
  2080. var d = this.d;
  2081. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2082. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2083. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2084. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2085. return new Plane(normalX, normalY, normalZ, finalD);
  2086. };
  2087. Plane.prototype.dotCoordinate = function (point) {
  2088. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2089. };
  2090. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2091. var x1 = point2.x - point1.x;
  2092. var y1 = point2.y - point1.y;
  2093. var z1 = point2.z - point1.z;
  2094. var x2 = point3.x - point1.x;
  2095. var y2 = point3.y - point1.y;
  2096. var z2 = point3.z - point1.z;
  2097. var yz = (y1 * z2) - (z1 * y2);
  2098. var xz = (z1 * x2) - (x1 * z2);
  2099. var xy = (x1 * y2) - (y1 * x2);
  2100. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2101. var invPyth;
  2102. if (pyth !== 0) {
  2103. invPyth = 1.0 / pyth;
  2104. }
  2105. else {
  2106. invPyth = 0;
  2107. }
  2108. this.normal.x = yz * invPyth;
  2109. this.normal.y = xz * invPyth;
  2110. this.normal.z = xy * invPyth;
  2111. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2112. return this;
  2113. };
  2114. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2115. var dot = Vector3.Dot(this.normal, direction);
  2116. return (dot <= epsilon);
  2117. };
  2118. Plane.prototype.signedDistanceTo = function (point) {
  2119. return Vector3.Dot(point, this.normal) + this.d;
  2120. };
  2121. // Statics
  2122. Plane.FromArray = function (array) {
  2123. return new Plane(array[0], array[1], array[2], array[3]);
  2124. };
  2125. Plane.FromPoints = function (point1, point2, point3) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. result.copyFromPoints(point1, point2, point3);
  2128. return result;
  2129. };
  2130. Plane.FromPositionAndNormal = function (origin, normal) {
  2131. var result = new Plane(0, 0, 0, 0);
  2132. normal.normalize();
  2133. result.normal = normal;
  2134. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2135. return result;
  2136. };
  2137. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2138. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2139. return Vector3.Dot(point, normal) + d;
  2140. };
  2141. return Plane;
  2142. })();
  2143. BABYLON.Plane = Plane;
  2144. var Viewport = (function () {
  2145. function Viewport(x, y, width, height) {
  2146. this.x = x;
  2147. this.y = y;
  2148. this.width = width;
  2149. this.height = height;
  2150. }
  2151. Viewport.prototype.toGlobal = function (engine) {
  2152. var width = engine.getRenderWidth();
  2153. var height = engine.getRenderHeight();
  2154. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2155. };
  2156. return Viewport;
  2157. })();
  2158. BABYLON.Viewport = Viewport;
  2159. var Frustum = (function () {
  2160. function Frustum() {
  2161. }
  2162. Frustum.GetPlanes = function (transform) {
  2163. var frustumPlanes = [];
  2164. for (var index = 0; index < 6; index++) {
  2165. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2166. }
  2167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2168. return frustumPlanes;
  2169. };
  2170. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2171. // Near
  2172. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2173. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2174. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2175. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2176. frustumPlanes[0].normalize();
  2177. // Far
  2178. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2179. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2180. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2181. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2182. frustumPlanes[1].normalize();
  2183. // Left
  2184. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2185. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2186. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2187. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2188. frustumPlanes[2].normalize();
  2189. // Right
  2190. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2191. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2192. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2193. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2194. frustumPlanes[3].normalize();
  2195. // Top
  2196. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2197. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2198. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2199. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2200. frustumPlanes[4].normalize();
  2201. // Bottom
  2202. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2203. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2204. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2205. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2206. frustumPlanes[5].normalize();
  2207. };
  2208. return Frustum;
  2209. })();
  2210. BABYLON.Frustum = Frustum;
  2211. var Ray = (function () {
  2212. function Ray(origin, direction, length) {
  2213. if (length === void 0) { length = Number.MAX_VALUE; }
  2214. this.origin = origin;
  2215. this.direction = direction;
  2216. this.length = length;
  2217. }
  2218. // Methods
  2219. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2220. var d = 0.0;
  2221. var maxValue = Number.MAX_VALUE;
  2222. if (Math.abs(this.direction.x) < 0.0000001) {
  2223. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2224. return false;
  2225. }
  2226. }
  2227. else {
  2228. var inv = 1.0 / this.direction.x;
  2229. var min = (minimum.x - this.origin.x) * inv;
  2230. var max = (maximum.x - this.origin.x) * inv;
  2231. if (max === -Infinity) {
  2232. max = Infinity;
  2233. }
  2234. if (min > max) {
  2235. var temp = min;
  2236. min = max;
  2237. max = temp;
  2238. }
  2239. d = Math.max(min, d);
  2240. maxValue = Math.min(max, maxValue);
  2241. if (d > maxValue) {
  2242. return false;
  2243. }
  2244. }
  2245. if (Math.abs(this.direction.y) < 0.0000001) {
  2246. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2247. return false;
  2248. }
  2249. }
  2250. else {
  2251. inv = 1.0 / this.direction.y;
  2252. min = (minimum.y - this.origin.y) * inv;
  2253. max = (maximum.y - this.origin.y) * inv;
  2254. if (max === -Infinity) {
  2255. max = Infinity;
  2256. }
  2257. if (min > max) {
  2258. temp = min;
  2259. min = max;
  2260. max = temp;
  2261. }
  2262. d = Math.max(min, d);
  2263. maxValue = Math.min(max, maxValue);
  2264. if (d > maxValue) {
  2265. return false;
  2266. }
  2267. }
  2268. if (Math.abs(this.direction.z) < 0.0000001) {
  2269. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2270. return false;
  2271. }
  2272. }
  2273. else {
  2274. inv = 1.0 / this.direction.z;
  2275. min = (minimum.z - this.origin.z) * inv;
  2276. max = (maximum.z - this.origin.z) * inv;
  2277. if (max === -Infinity) {
  2278. max = Infinity;
  2279. }
  2280. if (min > max) {
  2281. temp = min;
  2282. min = max;
  2283. max = temp;
  2284. }
  2285. d = Math.max(min, d);
  2286. maxValue = Math.min(max, maxValue);
  2287. if (d > maxValue) {
  2288. return false;
  2289. }
  2290. }
  2291. return true;
  2292. };
  2293. Ray.prototype.intersectsBox = function (box) {
  2294. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2295. };
  2296. Ray.prototype.intersectsSphere = function (sphere) {
  2297. var x = sphere.center.x - this.origin.x;
  2298. var y = sphere.center.y - this.origin.y;
  2299. var z = sphere.center.z - this.origin.z;
  2300. var pyth = (x * x) + (y * y) + (z * z);
  2301. var rr = sphere.radius * sphere.radius;
  2302. if (pyth <= rr) {
  2303. return true;
  2304. }
  2305. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2306. if (dot < 0.0) {
  2307. return false;
  2308. }
  2309. var temp = pyth - (dot * dot);
  2310. return temp <= rr;
  2311. };
  2312. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2313. if (!this._edge1) {
  2314. this._edge1 = Vector3.Zero();
  2315. this._edge2 = Vector3.Zero();
  2316. this._pvec = Vector3.Zero();
  2317. this._tvec = Vector3.Zero();
  2318. this._qvec = Vector3.Zero();
  2319. }
  2320. vertex1.subtractToRef(vertex0, this._edge1);
  2321. vertex2.subtractToRef(vertex0, this._edge2);
  2322. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2323. var det = Vector3.Dot(this._edge1, this._pvec);
  2324. if (det === 0) {
  2325. return null;
  2326. }
  2327. var invdet = 1 / det;
  2328. this.origin.subtractToRef(vertex0, this._tvec);
  2329. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2330. if (bu < 0 || bu > 1.0) {
  2331. return null;
  2332. }
  2333. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2334. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2335. if (bv < 0 || bu + bv > 1.0) {
  2336. return null;
  2337. }
  2338. //check if the distance is longer than the predefined length.
  2339. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2340. if (distance > this.length) {
  2341. return null;
  2342. }
  2343. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2344. };
  2345. // Statics
  2346. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2347. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2348. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2349. var direction = end.subtract(start);
  2350. direction.normalize();
  2351. return new Ray(start, direction);
  2352. };
  2353. /**
  2354. * 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
  2355. * transformed to the given world matrix.
  2356. * @param origin The origin point
  2357. * @param end The end point
  2358. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2359. */
  2360. Ray.CreateNewFromTo = function (origin, end, world) {
  2361. if (world === void 0) { world = Matrix.Identity(); }
  2362. var direction = end.subtract(origin);
  2363. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2364. direction.normalize();
  2365. return Ray.Transform(new Ray(origin, direction, length), world);
  2366. };
  2367. Ray.Transform = function (ray, matrix) {
  2368. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2369. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2370. return new Ray(newOrigin, newDirection, ray.length);
  2371. };
  2372. return Ray;
  2373. })();
  2374. BABYLON.Ray = Ray;
  2375. (function (Space) {
  2376. Space[Space["LOCAL"] = 0] = "LOCAL";
  2377. Space[Space["WORLD"] = 1] = "WORLD";
  2378. })(BABYLON.Space || (BABYLON.Space = {}));
  2379. var Space = BABYLON.Space;
  2380. var Axis = (function () {
  2381. function Axis() {
  2382. }
  2383. Axis.X = new Vector3(1, 0, 0);
  2384. Axis.Y = new Vector3(0, 1, 0);
  2385. Axis.Z = new Vector3(0, 0, 1);
  2386. return Axis;
  2387. })();
  2388. BABYLON.Axis = Axis;
  2389. ;
  2390. var BezierCurve = (function () {
  2391. function BezierCurve() {
  2392. }
  2393. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2394. // Extract X (which is equal to time here)
  2395. var f0 = 1 - 3 * x2 + 3 * x1;
  2396. var f1 = 3 * x2 - 6 * x1;
  2397. var f2 = 3 * x1;
  2398. var refinedT = t;
  2399. for (var i = 0; i < 5; i++) {
  2400. var refinedT2 = refinedT * refinedT;
  2401. var refinedT3 = refinedT2 * refinedT;
  2402. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2403. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2404. refinedT -= (x - t) * slope;
  2405. refinedT = Math.min(1, Math.max(0, refinedT));
  2406. }
  2407. // Resolve cubic bezier for the given x
  2408. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2409. };
  2410. return BezierCurve;
  2411. })();
  2412. BABYLON.BezierCurve = BezierCurve;
  2413. (function (Orientation) {
  2414. Orientation[Orientation["CW"] = 0] = "CW";
  2415. Orientation[Orientation["CCW"] = 1] = "CCW";
  2416. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2417. var Orientation = BABYLON.Orientation;
  2418. var Angle = (function () {
  2419. function Angle(radians) {
  2420. var _this = this;
  2421. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2422. this.radians = function () { return _this._radians; };
  2423. this._radians = radians;
  2424. if (this._radians < 0)
  2425. this._radians += (2 * Math.PI);
  2426. }
  2427. Angle.BetweenTwoPoints = function (a, b) {
  2428. var delta = b.subtract(a);
  2429. var theta = Math.atan2(delta.y, delta.x);
  2430. return new Angle(theta);
  2431. };
  2432. Angle.FromRadians = function (radians) {
  2433. return new Angle(radians);
  2434. };
  2435. Angle.FromDegrees = function (degrees) {
  2436. return new Angle(degrees * Math.PI / 180);
  2437. };
  2438. return Angle;
  2439. })();
  2440. BABYLON.Angle = Angle;
  2441. var Arc2 = (function () {
  2442. function Arc2(startPoint, midPoint, endPoint) {
  2443. this.startPoint = startPoint;
  2444. this.midPoint = midPoint;
  2445. this.endPoint = endPoint;
  2446. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2447. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2448. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2449. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2450. 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);
  2451. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2452. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2453. var a1 = this.startAngle.degrees();
  2454. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2455. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2456. // angles correction
  2457. if (a2 - a1 > +180.0)
  2458. a2 -= 360.0;
  2459. if (a2 - a1 < -180.0)
  2460. a2 += 360.0;
  2461. if (a3 - a2 > +180.0)
  2462. a3 -= 360.0;
  2463. if (a3 - a2 < -180.0)
  2464. a3 += 360.0;
  2465. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2466. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2467. }
  2468. return Arc2;
  2469. })();
  2470. BABYLON.Arc2 = Arc2;
  2471. var PathCursor = (function () {
  2472. function PathCursor(path) {
  2473. this.path = path;
  2474. this._onchange = new Array();
  2475. this.value = 0;
  2476. this.animations = new Array();
  2477. }
  2478. PathCursor.prototype.getPoint = function () {
  2479. var point = this.path.getPointAtLengthPosition(this.value);
  2480. return new Vector3(point.x, 0, point.y);
  2481. };
  2482. PathCursor.prototype.moveAhead = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.moveBack = function (step) {
  2488. if (step === void 0) { step = 0.002; }
  2489. this.move(-step);
  2490. return this;
  2491. };
  2492. PathCursor.prototype.move = function (step) {
  2493. if (Math.abs(step) > 1) {
  2494. throw "step size should be less than 1.";
  2495. }
  2496. this.value += step;
  2497. this.ensureLimits();
  2498. this.raiseOnChange();
  2499. return this;
  2500. };
  2501. PathCursor.prototype.ensureLimits = function () {
  2502. while (this.value > 1) {
  2503. this.value -= 1;
  2504. }
  2505. while (this.value < 0) {
  2506. this.value += 1;
  2507. }
  2508. return this;
  2509. };
  2510. // used by animation engine
  2511. PathCursor.prototype.markAsDirty = function (propertyName) {
  2512. this.ensureLimits();
  2513. this.raiseOnChange();
  2514. return this;
  2515. };
  2516. PathCursor.prototype.raiseOnChange = function () {
  2517. var _this = this;
  2518. this._onchange.forEach(function (f) { return f(_this); });
  2519. return this;
  2520. };
  2521. PathCursor.prototype.onchange = function (f) {
  2522. this._onchange.push(f);
  2523. return this;
  2524. };
  2525. return PathCursor;
  2526. })();
  2527. BABYLON.PathCursor = PathCursor;
  2528. var Path2 = (function () {
  2529. function Path2(x, y) {
  2530. this._points = new Array();
  2531. this._length = 0;
  2532. this.closed = false;
  2533. this._points.push(new Vector2(x, y));
  2534. }
  2535. Path2.prototype.addLineTo = function (x, y) {
  2536. if (closed) {
  2537. BABYLON.Tools.Error("cannot add lines to closed paths");
  2538. return this;
  2539. }
  2540. var newPoint = new Vector2(x, y);
  2541. var previousPoint = this._points[this._points.length - 1];
  2542. this._points.push(newPoint);
  2543. this._length += newPoint.subtract(previousPoint).length();
  2544. return this;
  2545. };
  2546. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2547. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2550. return this;
  2551. }
  2552. var startPoint = this._points[this._points.length - 1];
  2553. var midPoint = new Vector2(midX, midY);
  2554. var endPoint = new Vector2(endX, endY);
  2555. var arc = new Arc2(startPoint, midPoint, endPoint);
  2556. var increment = arc.angle.radians() / numberOfSegments;
  2557. if (arc.orientation === 0 /* CW */)
  2558. increment *= -1;
  2559. var currentAngle = arc.startAngle.radians() + increment;
  2560. for (var i = 0; i < numberOfSegments; i++) {
  2561. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2562. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2563. this.addLineTo(x, y);
  2564. currentAngle += increment;
  2565. }
  2566. return this;
  2567. };
  2568. Path2.prototype.close = function () {
  2569. this.closed = true;
  2570. return this;
  2571. };
  2572. Path2.prototype.length = function () {
  2573. var result = this._length;
  2574. if (!this.closed) {
  2575. var lastPoint = this._points[this._points.length - 1];
  2576. var firstPoint = this._points[0];
  2577. result += (firstPoint.subtract(lastPoint).length());
  2578. }
  2579. return result;
  2580. };
  2581. Path2.prototype.getPoints = function () {
  2582. return this._points;
  2583. };
  2584. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2585. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2586. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2587. return Vector2.Zero();
  2588. }
  2589. var lengthPosition = normalizedLengthPosition * this.length();
  2590. var previousOffset = 0;
  2591. for (var i = 0; i < this._points.length; i++) {
  2592. var j = (i + 1) % this._points.length;
  2593. var a = this._points[i];
  2594. var b = this._points[j];
  2595. var bToA = b.subtract(a);
  2596. var nextOffset = (bToA.length() + previousOffset);
  2597. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2598. var dir = bToA.normalize();
  2599. var localOffset = lengthPosition - previousOffset;
  2600. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2601. }
  2602. previousOffset = nextOffset;
  2603. }
  2604. BABYLON.Tools.Error("internal error");
  2605. return Vector2.Zero();
  2606. };
  2607. Path2.StartingAt = function (x, y) {
  2608. return new Path2(x, y);
  2609. };
  2610. return Path2;
  2611. })();
  2612. BABYLON.Path2 = Path2;
  2613. var Path3D = (function () {
  2614. function Path3D(path) {
  2615. this.path = path;
  2616. this._curve = new Array();
  2617. this._distances = new Array();
  2618. this._tangents = new Array();
  2619. this._normals = new Array();
  2620. this._binormals = new Array();
  2621. this._curve = path.slice(); // copy array
  2622. this._compute();
  2623. }
  2624. Path3D.prototype.getCurve = function () {
  2625. return this._curve;
  2626. };
  2627. Path3D.prototype.getTangents = function () {
  2628. return this._tangents;
  2629. };
  2630. Path3D.prototype.getNormals = function () {
  2631. return this._normals;
  2632. };
  2633. Path3D.prototype.getBinormals = function () {
  2634. return this._binormals;
  2635. };
  2636. Path3D.prototype.getDistances = function () {
  2637. return this._distances;
  2638. };
  2639. Path3D.prototype.update = function (path) {
  2640. for (var i = 0; i < path.length; i++) {
  2641. this._curve[i] = path[i];
  2642. }
  2643. this._compute();
  2644. return this;
  2645. };
  2646. // private function compute() : computes tangents, normals and binormals
  2647. Path3D.prototype._compute = function () {
  2648. var l = this._curve.length;
  2649. // first and last tangents
  2650. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2651. this._tangents[0].normalize();
  2652. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2653. this._tangents[l - 1].normalize();
  2654. // normals and binormals at first point : arbitrary vector with _normalVector()
  2655. var tg0 = this._tangents[0];
  2656. var pp0 = this._normalVector(this._curve[0], tg0);
  2657. this._normals[0] = pp0;
  2658. this._normals[0].normalize();
  2659. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2660. this._normals[0].normalize();
  2661. this._distances[0] = 0;
  2662. // normals and binormals : next points
  2663. var prev; // previous vector (segment)
  2664. var cur; // current vector (segment)
  2665. var curTang; // current tangent
  2666. var prevNorm; // previous normal
  2667. var prevBinor; // previous binormal
  2668. for (var i = 1; i < l; i++) {
  2669. // tangents
  2670. prev = this._curve[i].subtract(this._curve[i - 1]);
  2671. if (i < l - 1) {
  2672. cur = this._curve[i + 1].subtract(this._curve[i]);
  2673. this._tangents[i] = prev.add(cur);
  2674. this._tangents[i].normalize();
  2675. }
  2676. this._distances[i] = this._distances[i - 1] + prev.length();
  2677. // normals and binormals
  2678. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2679. curTang = this._tangents[i];
  2680. prevNorm = this._normals[i - 1];
  2681. prevBinor = this._binormals[i - 1];
  2682. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2683. this._normals[i].normalize();
  2684. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2685. this._binormals[i].normalize();
  2686. }
  2687. };
  2688. // private function normalVector(v0, vt) :
  2689. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2690. Path3D.prototype._normalVector = function (v0, vt) {
  2691. var point;
  2692. if (vt.x !== 1) {
  2693. point = new Vector3(1, 0, 0);
  2694. }
  2695. else if (vt.y !== 1) {
  2696. point = new Vector3(0, 1, 0);
  2697. }
  2698. else if (vt.z !== 1) {
  2699. point = new Vector3(0, 0, 1);
  2700. }
  2701. var normal0 = Vector3.Cross(vt, point);
  2702. normal0.normalize();
  2703. return normal0;
  2704. };
  2705. return Path3D;
  2706. })();
  2707. BABYLON.Path3D = Path3D;
  2708. var Curve3 = (function () {
  2709. function Curve3(points) {
  2710. this._points = points;
  2711. }
  2712. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2713. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2714. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2715. var bez = new Array();
  2716. var step = 1 / nbPoints;
  2717. var equation = function (t, val0, val1, val2) {
  2718. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2719. return res;
  2720. };
  2721. for (var i = 0; i <= 1; i += step) {
  2722. 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)));
  2723. }
  2724. return new Curve3(bez);
  2725. };
  2726. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2727. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2728. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2729. var bez = new Array();
  2730. var step = 1 / nbPoints;
  2731. var equation = function (t, val0, val1, val2, val3) {
  2732. 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;
  2733. return res;
  2734. };
  2735. for (var i = 0; i <= 1; i += step) {
  2736. 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)));
  2737. }
  2738. return new Curve3(bez);
  2739. };
  2740. Curve3.prototype.getPoints = function () {
  2741. return this._points;
  2742. };
  2743. Curve3.prototype.continue = function (curve) {
  2744. var lastPoint = this._points[this._points.length - 1];
  2745. var continuedPoints = this._points.slice();
  2746. var curvePoints = curve.getPoints();
  2747. for (var i = 1; i < curvePoints.length; i++) {
  2748. continuedPoints.push(curvePoints[i].add(lastPoint));
  2749. }
  2750. return new Curve3(continuedPoints);
  2751. };
  2752. return Curve3;
  2753. })();
  2754. BABYLON.Curve3 = Curve3;
  2755. // Vertex formats
  2756. var PositionNormalVertex = (function () {
  2757. function PositionNormalVertex(position, normal) {
  2758. if (position === void 0) { position = Vector3.Zero(); }
  2759. if (normal === void 0) { normal = Vector3.Up(); }
  2760. this.position = position;
  2761. this.normal = normal;
  2762. }
  2763. PositionNormalVertex.prototype.clone = function () {
  2764. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2765. };
  2766. return PositionNormalVertex;
  2767. })();
  2768. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2769. var PositionNormalTextureVertex = (function () {
  2770. function PositionNormalTextureVertex(position, normal, uv) {
  2771. if (position === void 0) { position = Vector3.Zero(); }
  2772. if (normal === void 0) { normal = Vector3.Up(); }
  2773. if (uv === void 0) { uv = Vector2.Zero(); }
  2774. this.position = position;
  2775. this.normal = normal;
  2776. this.uv = uv;
  2777. }
  2778. PositionNormalTextureVertex.prototype.clone = function () {
  2779. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2780. };
  2781. return PositionNormalTextureVertex;
  2782. })();
  2783. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2784. // SIMD
  2785. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2786. var previousInvertToRef = Matrix.prototype.invertToRef;
  2787. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2788. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2789. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2790. var SIMDHelper = (function () {
  2791. function SIMDHelper() {
  2792. }
  2793. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2794. get: function () {
  2795. return SIMDHelper._isEnabled;
  2796. },
  2797. enumerable: true,
  2798. configurable: true
  2799. });
  2800. SIMDHelper.DisableSIMD = function () {
  2801. // Replace functions
  2802. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2803. Matrix.prototype.invertToRef = previousInvertToRef;
  2804. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2805. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2806. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2807. SIMDHelper._isEnabled = false;
  2808. };
  2809. SIMDHelper.EnableSIMD = function () {
  2810. if (window.SIMD === undefined) {
  2811. return;
  2812. }
  2813. // Replace functions
  2814. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2815. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2816. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2817. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2818. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2819. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2820. get: function () {
  2821. return this._data[0];
  2822. },
  2823. set: function (value) {
  2824. if (!this._data) {
  2825. this._data = new Float32Array(3);
  2826. }
  2827. this._data[0] = value;
  2828. }
  2829. });
  2830. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2831. get: function () {
  2832. return this._data[1];
  2833. },
  2834. set: function (value) {
  2835. this._data[1] = value;
  2836. }
  2837. });
  2838. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2839. get: function () {
  2840. return this._data[2];
  2841. },
  2842. set: function (value) {
  2843. this._data[2] = value;
  2844. }
  2845. });
  2846. SIMDHelper._isEnabled = true;
  2847. };
  2848. SIMDHelper._isEnabled = false;
  2849. return SIMDHelper;
  2850. })();
  2851. BABYLON.SIMDHelper = SIMDHelper;
  2852. if (window.SIMD !== undefined) {
  2853. SIMDHelper.EnableSIMD();
  2854. }
  2855. })(BABYLON || (BABYLON = {}));
  2856. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2857. (function (BABYLON) {
  2858. // Screenshots
  2859. var screenshotCanvas;
  2860. var cloneValue = function (source, destinationObject) {
  2861. if (!source)
  2862. return null;
  2863. if (source instanceof BABYLON.Mesh) {
  2864. return null;
  2865. }
  2866. if (source instanceof BABYLON.SubMesh) {
  2867. return source.clone(destinationObject);
  2868. }
  2869. else if (source.clone) {
  2870. return source.clone();
  2871. }
  2872. return null;
  2873. };
  2874. var Tools = (function () {
  2875. function Tools() {
  2876. }
  2877. Tools.GetFilename = function (path) {
  2878. var index = path.lastIndexOf("/");
  2879. if (index < 0)
  2880. return path;
  2881. return path.substring(index + 1);
  2882. };
  2883. Tools.GetDOMTextContent = function (element) {
  2884. var result = "";
  2885. var child = element.firstChild;
  2886. while (child) {
  2887. if (child.nodeType === 3) {
  2888. result += child.textContent;
  2889. }
  2890. child = child.nextSibling;
  2891. }
  2892. return result;
  2893. };
  2894. Tools.ToDegrees = function (angle) {
  2895. return angle * 180 / Math.PI;
  2896. };
  2897. Tools.ToRadians = function (angle) {
  2898. return angle * Math.PI / 180;
  2899. };
  2900. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2903. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2904. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2907. }
  2908. return {
  2909. minimum: minimum,
  2910. maximum: maximum
  2911. };
  2912. };
  2913. Tools.ExtractMinAndMax = function (positions, start, count) {
  2914. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2915. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2916. for (var index = start; index < start + count; index++) {
  2917. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2918. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2919. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2920. }
  2921. return {
  2922. minimum: minimum,
  2923. maximum: maximum
  2924. };
  2925. };
  2926. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2927. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2928. return undefined;
  2929. return Array.isArray(obj) ? obj : [obj];
  2930. };
  2931. // Misc.
  2932. Tools.GetPointerPrefix = function () {
  2933. var eventPrefix = "pointer";
  2934. // Check if hand.js is referenced or if the browser natively supports pointer events
  2935. if (!navigator.pointerEnabled) {
  2936. eventPrefix = "mouse";
  2937. }
  2938. return eventPrefix;
  2939. };
  2940. Tools.QueueNewFrame = function (func) {
  2941. if (window.requestAnimationFrame)
  2942. window.requestAnimationFrame(func);
  2943. else if (window.msRequestAnimationFrame)
  2944. window.msRequestAnimationFrame(func);
  2945. else if (window.webkitRequestAnimationFrame)
  2946. window.webkitRequestAnimationFrame(func);
  2947. else if (window.mozRequestAnimationFrame)
  2948. window.mozRequestAnimationFrame(func);
  2949. else if (window.oRequestAnimationFrame)
  2950. window.oRequestAnimationFrame(func);
  2951. else {
  2952. window.setTimeout(func, 16);
  2953. }
  2954. };
  2955. Tools.RequestFullscreen = function (element) {
  2956. if (element.requestFullscreen)
  2957. element.requestFullscreen();
  2958. else if (element.msRequestFullscreen)
  2959. element.msRequestFullscreen();
  2960. else if (element.webkitRequestFullscreen)
  2961. element.webkitRequestFullscreen();
  2962. else if (element.mozRequestFullScreen)
  2963. element.mozRequestFullScreen();
  2964. };
  2965. Tools.ExitFullscreen = function () {
  2966. if (document.exitFullscreen) {
  2967. document.exitFullscreen();
  2968. }
  2969. else if (document.mozCancelFullScreen) {
  2970. document.mozCancelFullScreen();
  2971. }
  2972. else if (document.webkitCancelFullScreen) {
  2973. document.webkitCancelFullScreen();
  2974. }
  2975. else if (document.msCancelFullScreen) {
  2976. document.msCancelFullScreen();
  2977. }
  2978. };
  2979. // External files
  2980. Tools.CleanUrl = function (url) {
  2981. url = url.replace(/#/mg, "%23");
  2982. return url;
  2983. };
  2984. Tools.LoadImage = function (url, onload, onerror, database) {
  2985. url = Tools.CleanUrl(url);
  2986. var img = new Image();
  2987. if (url.substr(0, 5) !== "data:")
  2988. img.crossOrigin = 'anonymous';
  2989. img.onload = function () {
  2990. onload(img);
  2991. };
  2992. img.onerror = function (err) {
  2993. onerror(img, err);
  2994. };
  2995. var noIndexedDB = function () {
  2996. img.src = url;
  2997. };
  2998. var loadFromIndexedDB = function () {
  2999. database.loadImageFromDB(url, img);
  3000. };
  3001. //ANY database to do!
  3002. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3003. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3004. }
  3005. else {
  3006. if (url.indexOf("file:") === -1) {
  3007. noIndexedDB();
  3008. }
  3009. else {
  3010. try {
  3011. var textureName = url.substring(5);
  3012. var blobURL;
  3013. try {
  3014. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3015. }
  3016. catch (ex) {
  3017. // Chrome doesn't support oneTimeOnly parameter
  3018. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3019. }
  3020. img.src = blobURL;
  3021. }
  3022. catch (e) {
  3023. Tools.Log("Error while trying to load texture: " + textureName);
  3024. img.src = null;
  3025. }
  3026. }
  3027. }
  3028. return img;
  3029. };
  3030. //ANY
  3031. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3032. url = Tools.CleanUrl(url);
  3033. var noIndexedDB = function () {
  3034. var request = new XMLHttpRequest();
  3035. var loadUrl = Tools.BaseUrl + url;
  3036. request.open('GET', loadUrl, true);
  3037. if (useArrayBuffer) {
  3038. request.responseType = "arraybuffer";
  3039. }
  3040. request.onprogress = progressCallBack;
  3041. request.onreadystatechange = function () {
  3042. if (request.readyState === 4) {
  3043. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3044. callback(!useArrayBuffer ? request.responseText : request.response);
  3045. }
  3046. else {
  3047. if (onError) {
  3048. onError();
  3049. }
  3050. else {
  3051. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3052. }
  3053. }
  3054. }
  3055. };
  3056. request.send(null);
  3057. };
  3058. var loadFromIndexedDB = function () {
  3059. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3060. };
  3061. if (url.indexOf("file:") !== -1) {
  3062. var fileName = url.substring(5);
  3063. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3064. }
  3065. else {
  3066. // Caching all files
  3067. if (database && database.enableSceneOffline) {
  3068. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3069. }
  3070. else {
  3071. noIndexedDB();
  3072. }
  3073. }
  3074. };
  3075. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3076. var reader = new FileReader();
  3077. reader.onload = function (e) {
  3078. //target doesn't have result from ts 1.3
  3079. callback(e.target['result']);
  3080. };
  3081. reader.onprogress = progressCallback;
  3082. reader.readAsDataURL(fileToLoad);
  3083. };
  3084. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3085. var reader = new FileReader();
  3086. reader.onerror = function (e) {
  3087. Tools.Log("Error while reading file: " + fileToLoad.name);
  3088. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3089. };
  3090. reader.onload = function (e) {
  3091. //target doesn't have result from ts 1.3
  3092. callback(e.target['result']);
  3093. };
  3094. reader.onprogress = progressCallBack;
  3095. if (!useArrayBuffer) {
  3096. // Asynchronous read
  3097. reader.readAsText(fileToLoad);
  3098. }
  3099. else {
  3100. reader.readAsArrayBuffer(fileToLoad);
  3101. }
  3102. };
  3103. // Misc.
  3104. Tools.Clamp = function (value, min, max) {
  3105. if (min === void 0) { min = 0; }
  3106. if (max === void 0) { max = 1; }
  3107. return Math.min(max, Math.max(min, value));
  3108. };
  3109. // Returns -1 when value is a negative number and
  3110. // +1 when value is a positive number.
  3111. Tools.Sign = function (value) {
  3112. value = +value; // convert to a number
  3113. if (value === 0 || isNaN(value))
  3114. return value;
  3115. return value > 0 ? 1 : -1;
  3116. };
  3117. Tools.Format = function (value, decimals) {
  3118. if (decimals === void 0) { decimals = 2; }
  3119. return value.toFixed(decimals);
  3120. };
  3121. Tools.CheckExtends = function (v, min, max) {
  3122. if (v.x < min.x)
  3123. min.x = v.x;
  3124. if (v.y < min.y)
  3125. min.y = v.y;
  3126. if (v.z < min.z)
  3127. min.z = v.z;
  3128. if (v.x > max.x)
  3129. max.x = v.x;
  3130. if (v.y > max.y)
  3131. max.y = v.y;
  3132. if (v.z > max.z)
  3133. max.z = v.z;
  3134. };
  3135. Tools.WithinEpsilon = function (a, b, epsilon) {
  3136. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3137. var num = a - b;
  3138. return -epsilon <= num && num <= epsilon;
  3139. };
  3140. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3141. for (var prop in source) {
  3142. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3143. continue;
  3144. }
  3145. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3146. continue;
  3147. }
  3148. var sourceValue = source[prop];
  3149. var typeOfSourceValue = typeof sourceValue;
  3150. if (typeOfSourceValue === "function") {
  3151. continue;
  3152. }
  3153. if (typeOfSourceValue === "object") {
  3154. if (sourceValue instanceof Array) {
  3155. destination[prop] = [];
  3156. if (sourceValue.length > 0) {
  3157. if (typeof sourceValue[0] == "object") {
  3158. for (var index = 0; index < sourceValue.length; index++) {
  3159. var clonedValue = cloneValue(sourceValue[index], destination);
  3160. if (destination[prop].indexOf(clonedValue) === -1) {
  3161. destination[prop].push(clonedValue);
  3162. }
  3163. }
  3164. }
  3165. else {
  3166. destination[prop] = sourceValue.slice(0);
  3167. }
  3168. }
  3169. }
  3170. else {
  3171. destination[prop] = cloneValue(sourceValue, destination);
  3172. }
  3173. }
  3174. else {
  3175. destination[prop] = sourceValue;
  3176. }
  3177. }
  3178. };
  3179. Tools.IsEmpty = function (obj) {
  3180. for (var i in obj) {
  3181. return false;
  3182. }
  3183. return true;
  3184. };
  3185. Tools.RegisterTopRootEvents = function (events) {
  3186. for (var index = 0; index < events.length; index++) {
  3187. var event = events[index];
  3188. window.addEventListener(event.name, event.handler, false);
  3189. try {
  3190. if (window.parent) {
  3191. window.parent.addEventListener(event.name, event.handler, false);
  3192. }
  3193. }
  3194. catch (e) {
  3195. }
  3196. }
  3197. };
  3198. Tools.UnregisterTopRootEvents = function (events) {
  3199. for (var index = 0; index < events.length; index++) {
  3200. var event = events[index];
  3201. window.removeEventListener(event.name, event.handler);
  3202. try {
  3203. if (window.parent) {
  3204. window.parent.removeEventListener(event.name, event.handler);
  3205. }
  3206. }
  3207. catch (e) {
  3208. }
  3209. }
  3210. };
  3211. Tools.DumpFramebuffer = function (width, height, engine) {
  3212. // Read the contents of the framebuffer
  3213. var numberOfChannelsByLine = width * 4;
  3214. var halfHeight = height / 2;
  3215. //Reading datas from WebGL
  3216. var data = engine.readPixels(0, 0, width, height);
  3217. for (var i = 0; i < halfHeight; i++) {
  3218. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3219. var currentCell = j + i * numberOfChannelsByLine;
  3220. var targetLine = height - i - 1;
  3221. var targetCell = j + targetLine * numberOfChannelsByLine;
  3222. var temp = data[currentCell];
  3223. data[currentCell] = data[targetCell];
  3224. data[targetCell] = temp;
  3225. }
  3226. }
  3227. // Create a 2D canvas to store the result
  3228. if (!screenshotCanvas) {
  3229. screenshotCanvas = document.createElement('canvas');
  3230. }
  3231. screenshotCanvas.width = width;
  3232. screenshotCanvas.height = height;
  3233. var context = screenshotCanvas.getContext('2d');
  3234. // Copy the pixels to a 2D canvas
  3235. var imageData = context.createImageData(width, height);
  3236. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3237. var castData = imageData.data;
  3238. castData.set(data);
  3239. context.putImageData(imageData, 0, 0);
  3240. var base64Image = screenshotCanvas.toDataURL();
  3241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3242. if (("download" in document.createElement("a"))) {
  3243. var a = window.document.createElement("a");
  3244. a.href = base64Image;
  3245. var date = new Date();
  3246. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3247. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3248. window.document.body.appendChild(a);
  3249. a.addEventListener("click", function () {
  3250. a.parentElement.removeChild(a);
  3251. });
  3252. a.click();
  3253. }
  3254. else {
  3255. var newWindow = window.open("");
  3256. var img = newWindow.document.createElement("img");
  3257. img.src = base64Image;
  3258. newWindow.document.body.appendChild(img);
  3259. }
  3260. };
  3261. Tools.CreateScreenshot = function (engine, camera, size) {
  3262. var width;
  3263. var height;
  3264. var scene = camera.getScene();
  3265. var previousCamera = null;
  3266. if (scene.activeCamera !== camera) {
  3267. previousCamera = scene.activeCamera;
  3268. scene.activeCamera = camera;
  3269. }
  3270. //If a precision value is specified
  3271. if (size.precision) {
  3272. width = Math.round(engine.getRenderWidth() * size.precision);
  3273. height = Math.round(width / engine.getAspectRatio(camera));
  3274. size = { width: width, height: height };
  3275. }
  3276. else if (size.width && size.height) {
  3277. width = size.width;
  3278. height = size.height;
  3279. }
  3280. else if (size.width && !size.height) {
  3281. width = size.width;
  3282. height = Math.round(width / engine.getAspectRatio(camera));
  3283. size = { width: width, height: height };
  3284. }
  3285. else if (size.height && !size.width) {
  3286. height = size.height;
  3287. width = Math.round(height * engine.getAspectRatio(camera));
  3288. size = { width: width, height: height };
  3289. }
  3290. else if (!isNaN(size)) {
  3291. height = size;
  3292. width = size;
  3293. }
  3294. else {
  3295. Tools.Error("Invalid 'size' parameter !");
  3296. return;
  3297. }
  3298. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3299. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3300. texture.renderList = scene.meshes;
  3301. texture.onAfterRender = function () {
  3302. Tools.DumpFramebuffer(width, height, engine);
  3303. };
  3304. scene.incrementRenderId();
  3305. texture.render(true);
  3306. texture.dispose();
  3307. if (previousCamera) {
  3308. scene.activeCamera = previousCamera;
  3309. }
  3310. };
  3311. // XHR response validator for local file scenario
  3312. Tools.ValidateXHRData = function (xhr, dataType) {
  3313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3314. if (dataType === void 0) { dataType = 7; }
  3315. try {
  3316. if (dataType & 1) {
  3317. if (xhr.responseText && xhr.responseText.length > 0) {
  3318. return true;
  3319. }
  3320. else if (dataType === 1) {
  3321. return false;
  3322. }
  3323. }
  3324. if (dataType & 2) {
  3325. // Check header width and height since there is no "TGA" magic number
  3326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3328. return true;
  3329. }
  3330. else if (dataType === 2) {
  3331. return false;
  3332. }
  3333. }
  3334. if (dataType & 4) {
  3335. // Check for the "DDS" magic number
  3336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3338. return true;
  3339. }
  3340. else {
  3341. return false;
  3342. }
  3343. }
  3344. }
  3345. catch (e) {
  3346. }
  3347. return false;
  3348. };
  3349. Object.defineProperty(Tools, "NoneLogLevel", {
  3350. get: function () {
  3351. return Tools._NoneLogLevel;
  3352. },
  3353. enumerable: true,
  3354. configurable: true
  3355. });
  3356. Object.defineProperty(Tools, "MessageLogLevel", {
  3357. get: function () {
  3358. return Tools._MessageLogLevel;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(Tools, "WarningLogLevel", {
  3364. get: function () {
  3365. return Tools._WarningLogLevel;
  3366. },
  3367. enumerable: true,
  3368. configurable: true
  3369. });
  3370. Object.defineProperty(Tools, "ErrorLogLevel", {
  3371. get: function () {
  3372. return Tools._ErrorLogLevel;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(Tools, "AllLogLevel", {
  3378. get: function () {
  3379. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Tools._AddLogEntry = function (entry) {
  3385. Tools._LogCache = entry + Tools._LogCache;
  3386. if (Tools.OnNewCacheEntry) {
  3387. Tools.OnNewCacheEntry(entry);
  3388. }
  3389. };
  3390. Tools._FormatMessage = function (message) {
  3391. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3392. var date = new Date();
  3393. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3394. };
  3395. Tools._LogDisabled = function (message) {
  3396. // nothing to do
  3397. };
  3398. Tools._LogEnabled = function (message) {
  3399. var formattedMessage = Tools._FormatMessage(message);
  3400. console.log("BJS - " + formattedMessage);
  3401. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3402. Tools._AddLogEntry(entry);
  3403. };
  3404. Tools._WarnDisabled = function (message) {
  3405. // nothing to do
  3406. };
  3407. Tools._WarnEnabled = function (message) {
  3408. var formattedMessage = Tools._FormatMessage(message);
  3409. console.warn("BJS - " + formattedMessage);
  3410. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3411. Tools._AddLogEntry(entry);
  3412. };
  3413. Tools._ErrorDisabled = function (message) {
  3414. // nothing to do
  3415. };
  3416. Tools._ErrorEnabled = function (message) {
  3417. var formattedMessage = Tools._FormatMessage(message);
  3418. console.error("BJS - " + formattedMessage);
  3419. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3420. Tools._AddLogEntry(entry);
  3421. };
  3422. Object.defineProperty(Tools, "LogCache", {
  3423. get: function () {
  3424. return Tools._LogCache;
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Object.defineProperty(Tools, "LogLevels", {
  3430. set: function (level) {
  3431. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3432. Tools.Log = Tools._LogEnabled;
  3433. }
  3434. else {
  3435. Tools.Log = Tools._LogDisabled;
  3436. }
  3437. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3438. Tools.Warn = Tools._WarnEnabled;
  3439. }
  3440. else {
  3441. Tools.Warn = Tools._WarnDisabled;
  3442. }
  3443. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3444. Tools.Error = Tools._ErrorEnabled;
  3445. }
  3446. else {
  3447. Tools.Error = Tools._ErrorDisabled;
  3448. }
  3449. },
  3450. enumerable: true,
  3451. configurable: true
  3452. });
  3453. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3454. get: function () {
  3455. return Tools._PerformanceNoneLogLevel;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3461. get: function () {
  3462. return Tools._PerformanceUserMarkLogLevel;
  3463. },
  3464. enumerable: true,
  3465. configurable: true
  3466. });
  3467. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3468. get: function () {
  3469. return Tools._PerformanceConsoleLogLevel;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3475. set: function (level) {
  3476. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3477. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3478. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3479. return;
  3480. }
  3481. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3482. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3483. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3484. return;
  3485. }
  3486. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3487. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3493. };
  3494. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3495. };
  3496. Tools._StartUserMark = function (counterName, condition) {
  3497. if (condition === void 0) { condition = true; }
  3498. if (!condition || !Tools._performance.mark) {
  3499. return;
  3500. }
  3501. Tools._performance.mark(counterName + "-Begin");
  3502. };
  3503. Tools._EndUserMark = function (counterName, condition) {
  3504. if (condition === void 0) { condition = true; }
  3505. if (!condition || !Tools._performance.mark) {
  3506. return;
  3507. }
  3508. Tools._performance.mark(counterName + "-End");
  3509. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3510. };
  3511. Tools._StartPerformanceConsole = function (counterName, condition) {
  3512. if (condition === void 0) { condition = true; }
  3513. if (!condition) {
  3514. return;
  3515. }
  3516. Tools._StartUserMark(counterName, condition);
  3517. if (console.time) {
  3518. console.time(counterName);
  3519. }
  3520. };
  3521. Tools._EndPerformanceConsole = function (counterName, condition) {
  3522. if (condition === void 0) { condition = true; }
  3523. if (!condition) {
  3524. return;
  3525. }
  3526. Tools._EndUserMark(counterName, condition);
  3527. if (console.time) {
  3528. console.timeEnd(counterName);
  3529. }
  3530. };
  3531. Object.defineProperty(Tools, "Now", {
  3532. get: function () {
  3533. if (window.performance && window.performance.now) {
  3534. return window.performance.now();
  3535. }
  3536. return new Date().getTime();
  3537. },
  3538. enumerable: true,
  3539. configurable: true
  3540. });
  3541. // Deprecated
  3542. Tools.GetFps = function () {
  3543. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3544. return 0;
  3545. };
  3546. Tools.BaseUrl = "";
  3547. Tools.GetExponantOfTwo = function (value, max) {
  3548. var count = 1;
  3549. do {
  3550. count *= 2;
  3551. } while (count < value);
  3552. if (count > max)
  3553. count = max;
  3554. return count;
  3555. };
  3556. // Logs
  3557. Tools._NoneLogLevel = 0;
  3558. Tools._MessageLogLevel = 1;
  3559. Tools._WarningLogLevel = 2;
  3560. Tools._ErrorLogLevel = 4;
  3561. Tools._LogCache = "";
  3562. Tools.Log = Tools._LogEnabled;
  3563. Tools.Warn = Tools._WarnEnabled;
  3564. Tools.Error = Tools._ErrorEnabled;
  3565. // Performances
  3566. Tools._PerformanceNoneLogLevel = 0;
  3567. Tools._PerformanceUserMarkLogLevel = 1;
  3568. Tools._PerformanceConsoleLogLevel = 2;
  3569. Tools._performance = window.performance;
  3570. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3571. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3572. return Tools;
  3573. })();
  3574. BABYLON.Tools = Tools;
  3575. /**
  3576. * An implementation of a loop for asynchronous functions.
  3577. */
  3578. var AsyncLoop = (function () {
  3579. /**
  3580. * Constroctor.
  3581. * @param iterations the number of iterations.
  3582. * @param _fn the function to run each iteration
  3583. * @param _successCallback the callback that will be called upon succesful execution
  3584. * @param offset starting offset.
  3585. */
  3586. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3587. if (offset === void 0) { offset = 0; }
  3588. this.iterations = iterations;
  3589. this._fn = _fn;
  3590. this._successCallback = _successCallback;
  3591. this.index = offset - 1;
  3592. this._done = false;
  3593. }
  3594. /**
  3595. * Execute the next iteration. Must be called after the last iteration was finished.
  3596. */
  3597. AsyncLoop.prototype.executeNext = function () {
  3598. if (!this._done) {
  3599. if (this.index + 1 < this.iterations) {
  3600. ++this.index;
  3601. this._fn(this);
  3602. }
  3603. else {
  3604. this.breakLoop();
  3605. }
  3606. }
  3607. };
  3608. /**
  3609. * Break the loop and run the success callback.
  3610. */
  3611. AsyncLoop.prototype.breakLoop = function () {
  3612. this._done = true;
  3613. this._successCallback();
  3614. };
  3615. /**
  3616. * Helper function
  3617. */
  3618. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3619. if (offset === void 0) { offset = 0; }
  3620. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3621. loop.executeNext();
  3622. return loop;
  3623. };
  3624. /**
  3625. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3626. * @param iterations total number of iterations
  3627. * @param syncedIterations number of synchronous iterations in each async iteration.
  3628. * @param fn the function to call each iteration.
  3629. * @param callback a success call back that will be called when iterating stops.
  3630. * @param breakFunction a break condition (optional)
  3631. * @param timeout timeout settings for the setTimeout function. default - 0.
  3632. * @constructor
  3633. */
  3634. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3635. if (timeout === void 0) { timeout = 0; }
  3636. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3637. if (breakFunction && breakFunction())
  3638. loop.breakLoop();
  3639. else {
  3640. setTimeout(function () {
  3641. for (var i = 0; i < syncedIterations; ++i) {
  3642. var iteration = (loop.index * syncedIterations) + i;
  3643. if (iteration >= iterations)
  3644. break;
  3645. fn(iteration);
  3646. if (breakFunction && breakFunction()) {
  3647. loop.breakLoop();
  3648. break;
  3649. }
  3650. }
  3651. loop.executeNext();
  3652. }, timeout);
  3653. }
  3654. }, callback);
  3655. };
  3656. return AsyncLoop;
  3657. })();
  3658. BABYLON.AsyncLoop = AsyncLoop;
  3659. })(BABYLON || (BABYLON = {}));
  3660. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3661. (function (BABYLON) {
  3662. var _DepthCullingState = (function () {
  3663. function _DepthCullingState() {
  3664. this._isDepthTestDirty = false;
  3665. this._isDepthMaskDirty = false;
  3666. this._isDepthFuncDirty = false;
  3667. this._isCullFaceDirty = false;
  3668. this._isCullDirty = false;
  3669. this._isZOffsetDirty = false;
  3670. }
  3671. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3672. get: function () {
  3673. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3679. get: function () {
  3680. return this._zOffset;
  3681. },
  3682. set: function (value) {
  3683. if (this._zOffset === value) {
  3684. return;
  3685. }
  3686. this._zOffset = value;
  3687. this._isZOffsetDirty = true;
  3688. },
  3689. enumerable: true,
  3690. configurable: true
  3691. });
  3692. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3693. get: function () {
  3694. return this._cullFace;
  3695. },
  3696. set: function (value) {
  3697. if (this._cullFace === value) {
  3698. return;
  3699. }
  3700. this._cullFace = value;
  3701. this._isCullFaceDirty = true;
  3702. },
  3703. enumerable: true,
  3704. configurable: true
  3705. });
  3706. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3707. get: function () {
  3708. return this._cull;
  3709. },
  3710. set: function (value) {
  3711. if (this._cull === value) {
  3712. return;
  3713. }
  3714. this._cull = value;
  3715. this._isCullDirty = true;
  3716. },
  3717. enumerable: true,
  3718. configurable: true
  3719. });
  3720. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3721. get: function () {
  3722. return this._depthFunc;
  3723. },
  3724. set: function (value) {
  3725. if (this._depthFunc === value) {
  3726. return;
  3727. }
  3728. this._depthFunc = value;
  3729. this._isDepthFuncDirty = true;
  3730. },
  3731. enumerable: true,
  3732. configurable: true
  3733. });
  3734. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3735. get: function () {
  3736. return this._depthMask;
  3737. },
  3738. set: function (value) {
  3739. if (this._depthMask === value) {
  3740. return;
  3741. }
  3742. this._depthMask = value;
  3743. this._isDepthMaskDirty = true;
  3744. },
  3745. enumerable: true,
  3746. configurable: true
  3747. });
  3748. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3749. get: function () {
  3750. return this._depthTest;
  3751. },
  3752. set: function (value) {
  3753. if (this._depthTest === value) {
  3754. return;
  3755. }
  3756. this._depthTest = value;
  3757. this._isDepthTestDirty = true;
  3758. },
  3759. enumerable: true,
  3760. configurable: true
  3761. });
  3762. _DepthCullingState.prototype.reset = function () {
  3763. this._depthMask = true;
  3764. this._depthTest = true;
  3765. this._depthFunc = null;
  3766. this._cull = null;
  3767. this._cullFace = null;
  3768. this._zOffset = 0;
  3769. this._isDepthTestDirty = true;
  3770. this._isDepthMaskDirty = true;
  3771. this._isDepthFuncDirty = false;
  3772. this._isCullFaceDirty = false;
  3773. this._isCullDirty = false;
  3774. this._isZOffsetDirty = false;
  3775. };
  3776. _DepthCullingState.prototype.apply = function (gl) {
  3777. if (!this.isDirty) {
  3778. return;
  3779. }
  3780. // Cull
  3781. if (this._isCullDirty) {
  3782. if (this.cull) {
  3783. gl.enable(gl.CULL_FACE);
  3784. }
  3785. else {
  3786. gl.disable(gl.CULL_FACE);
  3787. }
  3788. this._isCullDirty = false;
  3789. }
  3790. // Cull face
  3791. if (this._isCullFaceDirty) {
  3792. gl.cullFace(this.cullFace);
  3793. this._isCullFaceDirty = false;
  3794. }
  3795. // Depth mask
  3796. if (this._isDepthMaskDirty) {
  3797. gl.depthMask(this.depthMask);
  3798. this._isDepthMaskDirty = false;
  3799. }
  3800. // Depth test
  3801. if (this._isDepthTestDirty) {
  3802. if (this.depthTest) {
  3803. gl.enable(gl.DEPTH_TEST);
  3804. }
  3805. else {
  3806. gl.disable(gl.DEPTH_TEST);
  3807. }
  3808. this._isDepthTestDirty = false;
  3809. }
  3810. // Depth func
  3811. if (this._isDepthFuncDirty) {
  3812. gl.depthFunc(this.depthFunc);
  3813. this._isDepthFuncDirty = false;
  3814. }
  3815. // zOffset
  3816. if (this._isZOffsetDirty) {
  3817. if (this.zOffset) {
  3818. gl.enable(gl.POLYGON_OFFSET_FILL);
  3819. gl.polygonOffset(this.zOffset, 0);
  3820. }
  3821. else {
  3822. gl.disable(gl.POLYGON_OFFSET_FILL);
  3823. }
  3824. this._isZOffsetDirty = false;
  3825. }
  3826. };
  3827. return _DepthCullingState;
  3828. })();
  3829. BABYLON._DepthCullingState = _DepthCullingState;
  3830. var _AlphaState = (function () {
  3831. function _AlphaState() {
  3832. this._isAlphaBlendDirty = false;
  3833. this._isBlendFunctionParametersDirty = false;
  3834. this._alphaBlend = false;
  3835. this._blendFunctionParameters = new Array(4);
  3836. }
  3837. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3838. get: function () {
  3839. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3840. },
  3841. enumerable: true,
  3842. configurable: true
  3843. });
  3844. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3845. get: function () {
  3846. return this._alphaBlend;
  3847. },
  3848. set: function (value) {
  3849. if (this._alphaBlend === value) {
  3850. return;
  3851. }
  3852. this._alphaBlend = value;
  3853. this._isAlphaBlendDirty = true;
  3854. },
  3855. enumerable: true,
  3856. configurable: true
  3857. });
  3858. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3859. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3860. return;
  3861. }
  3862. this._blendFunctionParameters[0] = value0;
  3863. this._blendFunctionParameters[1] = value1;
  3864. this._blendFunctionParameters[2] = value2;
  3865. this._blendFunctionParameters[3] = value3;
  3866. this._isBlendFunctionParametersDirty = true;
  3867. };
  3868. _AlphaState.prototype.reset = function () {
  3869. this._alphaBlend = false;
  3870. this._blendFunctionParameters[0] = null;
  3871. this._blendFunctionParameters[1] = null;
  3872. this._blendFunctionParameters[2] = null;
  3873. this._blendFunctionParameters[3] = null;
  3874. this._isAlphaBlendDirty = true;
  3875. this._isBlendFunctionParametersDirty = false;
  3876. };
  3877. _AlphaState.prototype.apply = function (gl) {
  3878. if (!this.isDirty) {
  3879. return;
  3880. }
  3881. // Alpha blend
  3882. if (this._isAlphaBlendDirty) {
  3883. if (this._alphaBlend) {
  3884. gl.enable(gl.BLEND);
  3885. }
  3886. else {
  3887. gl.disable(gl.BLEND);
  3888. }
  3889. this._isAlphaBlendDirty = false;
  3890. }
  3891. // Alpha function
  3892. if (this._isBlendFunctionParametersDirty) {
  3893. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3894. this._isBlendFunctionParametersDirty = false;
  3895. }
  3896. };
  3897. return _AlphaState;
  3898. })();
  3899. BABYLON._AlphaState = _AlphaState;
  3900. var compileShader = function (gl, source, type, defines) {
  3901. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3902. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3903. gl.compileShader(shader);
  3904. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3905. throw new Error(gl.getShaderInfoLog(shader));
  3906. }
  3907. return shader;
  3908. };
  3909. var getWebGLTextureType = function (gl, type) {
  3910. var textureType = gl.UNSIGNED_BYTE;
  3911. if (type === Engine.TEXTURETYPE_FLOAT)
  3912. textureType = gl.FLOAT;
  3913. return textureType;
  3914. };
  3915. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3916. var magFilter = gl.NEAREST;
  3917. var minFilter = gl.NEAREST;
  3918. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3919. magFilter = gl.LINEAR;
  3920. if (generateMipMaps) {
  3921. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3922. }
  3923. else {
  3924. minFilter = gl.LINEAR;
  3925. }
  3926. }
  3927. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3928. magFilter = gl.LINEAR;
  3929. if (generateMipMaps) {
  3930. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3931. }
  3932. else {
  3933. minFilter = gl.LINEAR;
  3934. }
  3935. }
  3936. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3937. magFilter = gl.NEAREST;
  3938. if (generateMipMaps) {
  3939. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3940. }
  3941. else {
  3942. minFilter = gl.NEAREST;
  3943. }
  3944. }
  3945. return {
  3946. min: minFilter,
  3947. mag: magFilter
  3948. };
  3949. };
  3950. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3952. var engine = scene.getEngine();
  3953. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3954. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3955. gl.bindTexture(gl.TEXTURE_2D, texture);
  3956. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3957. texture._baseWidth = width;
  3958. texture._baseHeight = height;
  3959. texture._width = potWidth;
  3960. texture._height = potHeight;
  3961. texture.isReady = true;
  3962. processFunction(potWidth, potHeight);
  3963. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3966. if (!noMipmap && !isCompressed) {
  3967. gl.generateMipmap(gl.TEXTURE_2D);
  3968. }
  3969. gl.bindTexture(gl.TEXTURE_2D, null);
  3970. engine._activeTexturesCache = [];
  3971. texture.samplingMode = samplingMode;
  3972. scene._removePendingData(texture);
  3973. };
  3974. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3975. var onload = function () {
  3976. loadedImages[index] = img;
  3977. loadedImages._internalCount++;
  3978. scene._removePendingData(img);
  3979. if (loadedImages._internalCount === 6) {
  3980. onfinish(loadedImages);
  3981. }
  3982. };
  3983. var onerror = function () {
  3984. scene._removePendingData(img);
  3985. };
  3986. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3987. scene._addPendingData(img);
  3988. };
  3989. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3990. var loadedImages = [];
  3991. loadedImages._internalCount = 0;
  3992. for (var index = 0; index < 6; index++) {
  3993. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3994. }
  3995. };
  3996. var EngineCapabilities = (function () {
  3997. function EngineCapabilities() {
  3998. }
  3999. return EngineCapabilities;
  4000. })();
  4001. BABYLON.EngineCapabilities = EngineCapabilities;
  4002. /**
  4003. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4004. */
  4005. var Engine = (function () {
  4006. /**
  4007. * @constructor
  4008. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4009. * @param {boolean} [antialias] - enable antialias
  4010. * @param options - further options to be sent to the getContext function
  4011. */
  4012. function Engine(canvas, antialias, options) {
  4013. var _this = this;
  4014. // Public members
  4015. this.isFullscreen = false;
  4016. this.isPointerLock = false;
  4017. this.cullBackFaces = true;
  4018. this.renderEvenInBackground = true;
  4019. this.scenes = new Array();
  4020. this._windowIsBackground = false;
  4021. this._loadingDivBackgroundColor = "black";
  4022. this._drawCalls = 0;
  4023. this._renderingQueueLaunched = false;
  4024. this._activeRenderLoops = [];
  4025. // FPS
  4026. this.fpsRange = 60;
  4027. this.previousFramesDuration = [];
  4028. this.fps = 60;
  4029. this.deltaTime = 0;
  4030. // States
  4031. this._depthCullingState = new _DepthCullingState();
  4032. this._alphaState = new _AlphaState();
  4033. this._alphaMode = Engine.ALPHA_DISABLE;
  4034. // Cache
  4035. this._loadedTexturesCache = new Array();
  4036. this._activeTexturesCache = new Array();
  4037. this._compiledEffects = {};
  4038. this._uintIndicesCurrentlySet = false;
  4039. this._renderingCanvas = canvas;
  4040. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4041. options = options || {};
  4042. options.antialias = antialias;
  4043. try {
  4044. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4045. }
  4046. catch (e) {
  4047. throw new Error("WebGL not supported");
  4048. }
  4049. if (!this._gl) {
  4050. throw new Error("WebGL not supported");
  4051. }
  4052. this._onBlur = function () {
  4053. _this._windowIsBackground = true;
  4054. };
  4055. this._onFocus = function () {
  4056. _this._windowIsBackground = false;
  4057. };
  4058. window.addEventListener("blur", this._onBlur);
  4059. window.addEventListener("focus", this._onFocus);
  4060. // Viewport
  4061. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4062. this.resize();
  4063. // Caps
  4064. this._caps = new EngineCapabilities();
  4065. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4066. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4067. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4068. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4069. // Infos
  4070. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4071. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4072. if (rendererInfo != null) {
  4073. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4074. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4075. }
  4076. if (!this._glVendor) {
  4077. this._glVendor = "Unknown vendor";
  4078. }
  4079. if (!this._glRenderer) {
  4080. this._glRenderer = "Unknown renderer";
  4081. }
  4082. // Extensions
  4083. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4084. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4085. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4086. 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');
  4087. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4088. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4089. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4090. this._caps.highPrecisionShaderSupported = true;
  4091. if (this._gl.getShaderPrecisionFormat) {
  4092. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  4093. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  4094. }
  4095. // Depth buffer
  4096. this.setDepthBuffer(true);
  4097. this.setDepthFunctionToLessOrEqual();
  4098. this.setDepthWrite(true);
  4099. // Fullscreen
  4100. this._onFullscreenChange = function () {
  4101. if (document.fullscreen !== undefined) {
  4102. _this.isFullscreen = document.fullscreen;
  4103. }
  4104. else if (document.mozFullScreen !== undefined) {
  4105. _this.isFullscreen = document.mozFullScreen;
  4106. }
  4107. else if (document.webkitIsFullScreen !== undefined) {
  4108. _this.isFullscreen = document.webkitIsFullScreen;
  4109. }
  4110. else if (document.msIsFullScreen !== undefined) {
  4111. _this.isFullscreen = document.msIsFullScreen;
  4112. }
  4113. // Pointer lock
  4114. if (_this.isFullscreen && _this._pointerLockRequested) {
  4115. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4116. if (canvas.requestPointerLock) {
  4117. canvas.requestPointerLock();
  4118. }
  4119. }
  4120. };
  4121. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4122. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4123. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4124. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4125. // Pointer lock
  4126. this._onPointerLockChange = function () {
  4127. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4128. };
  4129. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4130. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4131. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4132. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4133. if (!Engine.audioEngine) {
  4134. Engine.audioEngine = new BABYLON.AudioEngine();
  4135. }
  4136. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4137. }
  4138. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4139. get: function () {
  4140. return Engine._ALPHA_DISABLE;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "ALPHA_ADD", {
  4146. get: function () {
  4147. return Engine._ALPHA_ADD;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4153. get: function () {
  4154. return Engine._ALPHA_COMBINE;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4160. get: function () {
  4161. return Engine._DELAYLOADSTATE_NONE;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4167. get: function () {
  4168. return Engine._DELAYLOADSTATE_LOADED;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4174. get: function () {
  4175. return Engine._DELAYLOADSTATE_LOADING;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4181. get: function () {
  4182. return Engine._DELAYLOADSTATE_NOTLOADED;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_ALPHA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4195. get: function () {
  4196. return Engine._TEXTUREFORMAT_LUMINANCE;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4202. get: function () {
  4203. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4209. get: function () {
  4210. return Engine._TEXTUREFORMAT_RGB;
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4216. get: function () {
  4217. return Engine._TEXTUREFORMAT_RGBA;
  4218. },
  4219. enumerable: true,
  4220. configurable: true
  4221. });
  4222. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4223. get: function () {
  4224. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4225. },
  4226. enumerable: true,
  4227. configurable: true
  4228. });
  4229. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4230. get: function () {
  4231. return Engine._TEXTURETYPE_FLOAT;
  4232. },
  4233. enumerable: true,
  4234. configurable: true
  4235. });
  4236. Object.defineProperty(Engine, "Version", {
  4237. get: function () {
  4238. return "2.1.0 alpha";
  4239. },
  4240. enumerable: true,
  4241. configurable: true
  4242. });
  4243. Engine.prototype._prepareWorkingCanvas = function () {
  4244. if (this._workingCanvas) {
  4245. return;
  4246. }
  4247. this._workingCanvas = document.createElement("canvas");
  4248. this._workingContext = this._workingCanvas.getContext("2d");
  4249. };
  4250. Engine.prototype.getGlInfo = function () {
  4251. return {
  4252. vendor: this._glVendor,
  4253. renderer: this._glRenderer,
  4254. version: this._glVersion
  4255. };
  4256. };
  4257. Engine.prototype.getAspectRatio = function (camera) {
  4258. var viewport = camera.viewport;
  4259. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4260. };
  4261. Engine.prototype.getRenderWidth = function () {
  4262. if (this._currentRenderTarget) {
  4263. return this._currentRenderTarget._width;
  4264. }
  4265. return this._renderingCanvas.width;
  4266. };
  4267. Engine.prototype.getRenderHeight = function () {
  4268. if (this._currentRenderTarget) {
  4269. return this._currentRenderTarget._height;
  4270. }
  4271. return this._renderingCanvas.height;
  4272. };
  4273. Engine.prototype.getRenderingCanvas = function () {
  4274. return this._renderingCanvas;
  4275. };
  4276. Engine.prototype.getRenderingCanvasClientRect = function () {
  4277. return this._renderingCanvas.getBoundingClientRect();
  4278. };
  4279. Engine.prototype.setHardwareScalingLevel = function (level) {
  4280. this._hardwareScalingLevel = level;
  4281. this.resize();
  4282. };
  4283. Engine.prototype.getHardwareScalingLevel = function () {
  4284. return this._hardwareScalingLevel;
  4285. };
  4286. Engine.prototype.getLoadedTexturesCache = function () {
  4287. return this._loadedTexturesCache;
  4288. };
  4289. Engine.prototype.getCaps = function () {
  4290. return this._caps;
  4291. };
  4292. Object.defineProperty(Engine.prototype, "drawCalls", {
  4293. get: function () {
  4294. return this._drawCalls;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. // Methods
  4300. Engine.prototype.resetDrawCalls = function () {
  4301. this._drawCalls = 0;
  4302. };
  4303. Engine.prototype.setDepthFunctionToGreater = function () {
  4304. this._depthCullingState.depthFunc = this._gl.GREATER;
  4305. };
  4306. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4307. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4308. };
  4309. Engine.prototype.setDepthFunctionToLess = function () {
  4310. this._depthCullingState.depthFunc = this._gl.LESS;
  4311. };
  4312. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4313. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4314. };
  4315. /**
  4316. * stop executing a render loop function and remove it from the execution array
  4317. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4318. */
  4319. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4320. if (!renderFunction) {
  4321. this._activeRenderLoops = [];
  4322. return;
  4323. }
  4324. var index = this._activeRenderLoops.indexOf(renderFunction);
  4325. if (index >= 0) {
  4326. this._activeRenderLoops.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype._renderLoop = function () {
  4330. var _this = this;
  4331. var shouldRender = true;
  4332. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4333. shouldRender = false;
  4334. }
  4335. if (shouldRender) {
  4336. // Start new frame
  4337. this.beginFrame();
  4338. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4339. var renderFunction = this._activeRenderLoops[index];
  4340. renderFunction();
  4341. }
  4342. // Present
  4343. this.endFrame();
  4344. }
  4345. if (this._activeRenderLoops.length > 0) {
  4346. // Register new frame
  4347. BABYLON.Tools.QueueNewFrame(function () {
  4348. _this._renderLoop();
  4349. });
  4350. }
  4351. else {
  4352. this._renderingQueueLaunched = false;
  4353. }
  4354. };
  4355. /**
  4356. * Register and execute a render loop. The engine can have more than one render function.
  4357. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4358. * @example
  4359. * engine.runRenderLoop(function () {
  4360. * scene.render()
  4361. * })
  4362. */
  4363. Engine.prototype.runRenderLoop = function (renderFunction) {
  4364. var _this = this;
  4365. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4366. return;
  4367. }
  4368. this._activeRenderLoops.push(renderFunction);
  4369. if (!this._renderingQueueLaunched) {
  4370. this._renderingQueueLaunched = true;
  4371. BABYLON.Tools.QueueNewFrame(function () {
  4372. _this._renderLoop();
  4373. });
  4374. }
  4375. };
  4376. /**
  4377. * Toggle full screen mode.
  4378. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4379. */
  4380. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4381. if (this.isFullscreen) {
  4382. BABYLON.Tools.ExitFullscreen();
  4383. }
  4384. else {
  4385. this._pointerLockRequested = requestPointerLock;
  4386. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4387. }
  4388. };
  4389. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4390. this.applyStates();
  4391. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4392. if (this._depthCullingState.depthMask) {
  4393. this._gl.clearDepth(1.0);
  4394. }
  4395. var mode = 0;
  4396. if (backBuffer)
  4397. mode |= this._gl.COLOR_BUFFER_BIT;
  4398. if (depthStencil && this._depthCullingState.depthMask)
  4399. mode |= this._gl.DEPTH_BUFFER_BIT;
  4400. this._gl.clear(mode);
  4401. };
  4402. /**
  4403. * Set the WebGL's viewport
  4404. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4405. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4406. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4407. */
  4408. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4409. var width = requiredWidth || this._renderingCanvas.width;
  4410. var height = requiredHeight || this._renderingCanvas.height;
  4411. var x = viewport.x || 0;
  4412. var y = viewport.y || 0;
  4413. this._cachedViewport = viewport;
  4414. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4415. };
  4416. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4417. this._cachedViewport = null;
  4418. this._gl.viewport(x, y, width, height);
  4419. };
  4420. Engine.prototype.beginFrame = function () {
  4421. this._measureFps();
  4422. };
  4423. Engine.prototype.endFrame = function () {
  4424. //this.flushFramebuffer();
  4425. };
  4426. /**
  4427. * resize the view according to the canvas' size.
  4428. * @example
  4429. * window.addEventListener("resize", function () {
  4430. * engine.resize();
  4431. * });
  4432. */
  4433. Engine.prototype.resize = function () {
  4434. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4435. };
  4436. /**
  4437. * force a specific size of the canvas
  4438. * @param {number} width - the new canvas' width
  4439. * @param {number} height - the new canvas' height
  4440. */
  4441. Engine.prototype.setSize = function (width, height) {
  4442. this._renderingCanvas.width = width;
  4443. this._renderingCanvas.height = height;
  4444. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4445. };
  4446. Engine.prototype.bindFramebuffer = function (texture) {
  4447. this._currentRenderTarget = texture;
  4448. var gl = this._gl;
  4449. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4450. this._gl.viewport(0, 0, texture._width, texture._height);
  4451. this.wipeCaches();
  4452. };
  4453. Engine.prototype.unBindFramebuffer = function (texture) {
  4454. this._currentRenderTarget = null;
  4455. if (texture.generateMipMaps) {
  4456. var gl = this._gl;
  4457. gl.bindTexture(gl.TEXTURE_2D, texture);
  4458. gl.generateMipmap(gl.TEXTURE_2D);
  4459. gl.bindTexture(gl.TEXTURE_2D, null);
  4460. }
  4461. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4462. };
  4463. Engine.prototype.flushFramebuffer = function () {
  4464. this._gl.flush();
  4465. };
  4466. Engine.prototype.restoreDefaultFramebuffer = function () {
  4467. this._currentRenderTarget = null;
  4468. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4469. this.setViewport(this._cachedViewport);
  4470. this.wipeCaches();
  4471. };
  4472. // VBOs
  4473. Engine.prototype._resetVertexBufferBinding = function () {
  4474. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4475. this._cachedVertexBuffers = null;
  4476. };
  4477. Engine.prototype.createVertexBuffer = function (vertices) {
  4478. var vbo = this._gl.createBuffer();
  4479. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4480. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4481. this._resetVertexBufferBinding();
  4482. vbo.references = 1;
  4483. return vbo;
  4484. };
  4485. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4486. var vbo = this._gl.createBuffer();
  4487. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4488. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4489. this._resetVertexBufferBinding();
  4490. vbo.references = 1;
  4491. return vbo;
  4492. };
  4493. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4494. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4495. if (offset === undefined) {
  4496. offset = 0;
  4497. }
  4498. if (vertices instanceof Float32Array) {
  4499. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4500. }
  4501. else {
  4502. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4503. }
  4504. this._resetVertexBufferBinding();
  4505. };
  4506. Engine.prototype._resetIndexBufferBinding = function () {
  4507. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4508. this._cachedIndexBuffer = null;
  4509. };
  4510. Engine.prototype.createIndexBuffer = function (indices) {
  4511. var vbo = this._gl.createBuffer();
  4512. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4513. // Check for 32 bits indices
  4514. var arrayBuffer;
  4515. var need32Bits = false;
  4516. if (this._caps.uintIndices) {
  4517. for (var index = 0; index < indices.length; index++) {
  4518. if (indices[index] > 65535) {
  4519. need32Bits = true;
  4520. break;
  4521. }
  4522. }
  4523. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4524. }
  4525. else {
  4526. arrayBuffer = new Uint16Array(indices);
  4527. }
  4528. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4529. this._resetIndexBufferBinding();
  4530. vbo.references = 1;
  4531. vbo.is32Bits = need32Bits;
  4532. return vbo;
  4533. };
  4534. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4535. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4536. this._cachedVertexBuffers = vertexBuffer;
  4537. this._cachedEffectForVertexBuffers = effect;
  4538. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4539. var offset = 0;
  4540. for (var index = 0; index < vertexDeclaration.length; index++) {
  4541. var order = effect.getAttributeLocation(index);
  4542. if (order >= 0) {
  4543. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4544. }
  4545. offset += vertexDeclaration[index] * 4;
  4546. }
  4547. }
  4548. if (this._cachedIndexBuffer !== indexBuffer) {
  4549. this._cachedIndexBuffer = indexBuffer;
  4550. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4551. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4552. }
  4553. };
  4554. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4555. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4556. this._cachedVertexBuffers = vertexBuffers;
  4557. this._cachedEffectForVertexBuffers = effect;
  4558. var attributes = effect.getAttributesNames();
  4559. for (var index = 0; index < attributes.length; index++) {
  4560. var order = effect.getAttributeLocation(index);
  4561. if (order >= 0) {
  4562. var vertexBuffer = vertexBuffers[attributes[index]];
  4563. if (!vertexBuffer) {
  4564. continue;
  4565. }
  4566. var stride = vertexBuffer.getStrideSize();
  4567. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4568. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4569. }
  4570. }
  4571. }
  4572. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4573. this._cachedIndexBuffer = indexBuffer;
  4574. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4575. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4576. }
  4577. };
  4578. Engine.prototype._releaseBuffer = function (buffer) {
  4579. buffer.references--;
  4580. if (buffer.references === 0) {
  4581. this._gl.deleteBuffer(buffer);
  4582. return true;
  4583. }
  4584. return false;
  4585. };
  4586. Engine.prototype.createInstancesBuffer = function (capacity) {
  4587. var buffer = this._gl.createBuffer();
  4588. buffer.capacity = capacity;
  4589. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4590. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4591. return buffer;
  4592. };
  4593. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4594. this._gl.deleteBuffer(buffer);
  4595. };
  4596. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4597. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4598. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4599. for (var index = 0; index < 4; index++) {
  4600. var offsetLocation = offsetLocations[index];
  4601. this._gl.enableVertexAttribArray(offsetLocation);
  4602. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4603. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4604. }
  4605. };
  4606. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4607. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4608. for (var index = 0; index < 4; index++) {
  4609. var offsetLocation = offsetLocations[index];
  4610. this._gl.disableVertexAttribArray(offsetLocation);
  4611. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4612. }
  4613. };
  4614. Engine.prototype.applyStates = function () {
  4615. this._depthCullingState.apply(this._gl);
  4616. this._alphaState.apply(this._gl);
  4617. };
  4618. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4619. // Apply states
  4620. this.applyStates();
  4621. this._drawCalls++;
  4622. // Render
  4623. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4624. if (instancesCount) {
  4625. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4626. return;
  4627. }
  4628. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4629. };
  4630. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4631. // Apply states
  4632. this.applyStates();
  4633. this._drawCalls++;
  4634. if (instancesCount) {
  4635. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4636. return;
  4637. }
  4638. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4639. };
  4640. // Shaders
  4641. Engine.prototype._releaseEffect = function (effect) {
  4642. if (this._compiledEffects[effect._key]) {
  4643. delete this._compiledEffects[effect._key];
  4644. if (effect.getProgram()) {
  4645. this._gl.deleteProgram(effect.getProgram());
  4646. }
  4647. }
  4648. };
  4649. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4650. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4651. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4652. var name = vertex + "+" + fragment + "@" + defines;
  4653. if (this._compiledEffects[name]) {
  4654. return this._compiledEffects[name];
  4655. }
  4656. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4657. effect._key = name;
  4658. this._compiledEffects[name] = effect;
  4659. return effect;
  4660. };
  4661. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4662. if (uniformsNames === void 0) { uniformsNames = []; }
  4663. if (samplers === void 0) { samplers = []; }
  4664. if (defines === void 0) { defines = ""; }
  4665. return this.createEffect({
  4666. vertex: "particles",
  4667. fragmentElement: fragmentName
  4668. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4669. };
  4670. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4671. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4672. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4673. var shaderProgram = this._gl.createProgram();
  4674. this._gl.attachShader(shaderProgram, vertexShader);
  4675. this._gl.attachShader(shaderProgram, fragmentShader);
  4676. this._gl.linkProgram(shaderProgram);
  4677. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4678. if (!linked) {
  4679. var error = this._gl.getProgramInfoLog(shaderProgram);
  4680. if (error) {
  4681. throw new Error(error);
  4682. }
  4683. }
  4684. this._gl.deleteShader(vertexShader);
  4685. this._gl.deleteShader(fragmentShader);
  4686. return shaderProgram;
  4687. };
  4688. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4689. var results = [];
  4690. for (var index = 0; index < uniformsNames.length; index++) {
  4691. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4692. }
  4693. return results;
  4694. };
  4695. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4696. var results = [];
  4697. for (var index = 0; index < attributesNames.length; index++) {
  4698. try {
  4699. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4700. }
  4701. catch (e) {
  4702. results.push(-1);
  4703. }
  4704. }
  4705. return results;
  4706. };
  4707. Engine.prototype.enableEffect = function (effect) {
  4708. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4709. if (effect && effect.onBind) {
  4710. effect.onBind(effect);
  4711. }
  4712. return;
  4713. }
  4714. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4715. // Use program
  4716. this._gl.useProgram(effect.getProgram());
  4717. for (var i in this._vertexAttribArrays) {
  4718. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4719. continue;
  4720. }
  4721. this._vertexAttribArrays[i] = false;
  4722. this._gl.disableVertexAttribArray(i);
  4723. }
  4724. var attributesCount = effect.getAttributesCount();
  4725. for (var index = 0; index < attributesCount; index++) {
  4726. // Attributes
  4727. var order = effect.getAttributeLocation(index);
  4728. if (order >= 0) {
  4729. this._vertexAttribArrays[order] = true;
  4730. this._gl.enableVertexAttribArray(order);
  4731. }
  4732. }
  4733. this._currentEffect = effect;
  4734. if (effect.onBind) {
  4735. effect.onBind(effect);
  4736. }
  4737. };
  4738. Engine.prototype.setArray = function (uniform, array) {
  4739. if (!uniform)
  4740. return;
  4741. this._gl.uniform1fv(uniform, array);
  4742. };
  4743. Engine.prototype.setArray2 = function (uniform, array) {
  4744. if (!uniform || array.length % 2 !== 0)
  4745. return;
  4746. this._gl.uniform2fv(uniform, array);
  4747. };
  4748. Engine.prototype.setArray3 = function (uniform, array) {
  4749. if (!uniform || array.length % 3 !== 0)
  4750. return;
  4751. this._gl.uniform3fv(uniform, array);
  4752. };
  4753. Engine.prototype.setArray4 = function (uniform, array) {
  4754. if (!uniform || array.length % 4 !== 0)
  4755. return;
  4756. this._gl.uniform4fv(uniform, array);
  4757. };
  4758. Engine.prototype.setMatrices = function (uniform, matrices) {
  4759. if (!uniform)
  4760. return;
  4761. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4762. };
  4763. Engine.prototype.setMatrix = function (uniform, matrix) {
  4764. if (!uniform)
  4765. return;
  4766. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4767. };
  4768. Engine.prototype.setFloat = function (uniform, value) {
  4769. if (!uniform)
  4770. return;
  4771. this._gl.uniform1f(uniform, value);
  4772. };
  4773. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4774. if (!uniform)
  4775. return;
  4776. this._gl.uniform2f(uniform, x, y);
  4777. };
  4778. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4779. if (!uniform)
  4780. return;
  4781. this._gl.uniform3f(uniform, x, y, z);
  4782. };
  4783. Engine.prototype.setBool = function (uniform, bool) {
  4784. if (!uniform)
  4785. return;
  4786. this._gl.uniform1i(uniform, bool);
  4787. };
  4788. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4789. if (!uniform)
  4790. return;
  4791. this._gl.uniform4f(uniform, x, y, z, w);
  4792. };
  4793. Engine.prototype.setColor3 = function (uniform, color3) {
  4794. if (!uniform)
  4795. return;
  4796. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4797. };
  4798. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4799. if (!uniform)
  4800. return;
  4801. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4802. };
  4803. // States
  4804. Engine.prototype.setState = function (culling, zOffset, force) {
  4805. if (zOffset === void 0) { zOffset = 0; }
  4806. // Culling
  4807. if (this._depthCullingState.cull !== culling || force) {
  4808. if (culling) {
  4809. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4810. this._depthCullingState.cull = true;
  4811. }
  4812. else {
  4813. this._depthCullingState.cull = false;
  4814. }
  4815. }
  4816. // Z offset
  4817. this._depthCullingState.zOffset = zOffset;
  4818. };
  4819. Engine.prototype.setDepthBuffer = function (enable) {
  4820. this._depthCullingState.depthTest = enable;
  4821. };
  4822. Engine.prototype.getDepthWrite = function () {
  4823. return this._depthCullingState.depthMask;
  4824. };
  4825. Engine.prototype.setDepthWrite = function (enable) {
  4826. this._depthCullingState.depthMask = enable;
  4827. };
  4828. Engine.prototype.setColorWrite = function (enable) {
  4829. this._gl.colorMask(enable, enable, enable, enable);
  4830. };
  4831. Engine.prototype.setAlphaMode = function (mode) {
  4832. switch (mode) {
  4833. case Engine.ALPHA_DISABLE:
  4834. this.setDepthWrite(true);
  4835. this._alphaState.alphaBlend = false;
  4836. break;
  4837. case Engine.ALPHA_COMBINE:
  4838. this.setDepthWrite(false);
  4839. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4840. this._alphaState.alphaBlend = true;
  4841. break;
  4842. case Engine.ALPHA_ADD:
  4843. this.setDepthWrite(false);
  4844. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4845. this._alphaState.alphaBlend = true;
  4846. break;
  4847. }
  4848. this._alphaMode = mode;
  4849. };
  4850. Engine.prototype.getAlphaMode = function () {
  4851. return this._alphaMode;
  4852. };
  4853. Engine.prototype.setAlphaTesting = function (enable) {
  4854. this._alphaTest = enable;
  4855. };
  4856. Engine.prototype.getAlphaTesting = function () {
  4857. return this._alphaTest;
  4858. };
  4859. // Textures
  4860. Engine.prototype.wipeCaches = function () {
  4861. this._activeTexturesCache = [];
  4862. this._currentEffect = null;
  4863. this._depthCullingState.reset();
  4864. this._alphaState.reset();
  4865. this._cachedVertexBuffers = null;
  4866. this._cachedIndexBuffer = null;
  4867. this._cachedEffectForVertexBuffers = null;
  4868. };
  4869. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4870. var gl = this._gl;
  4871. gl.bindTexture(gl.TEXTURE_2D, texture);
  4872. var magFilter = gl.NEAREST;
  4873. var minFilter = gl.NEAREST;
  4874. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4875. magFilter = gl.LINEAR;
  4876. minFilter = gl.LINEAR;
  4877. }
  4878. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4879. magFilter = gl.LINEAR;
  4880. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4881. }
  4882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4884. gl.bindTexture(gl.TEXTURE_2D, null);
  4885. texture.samplingMode = samplingMode;
  4886. };
  4887. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4888. var _this = this;
  4889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4890. if (onLoad === void 0) { onLoad = null; }
  4891. if (onError === void 0) { onError = null; }
  4892. if (buffer === void 0) { buffer = null; }
  4893. var texture = this._gl.createTexture();
  4894. var extension;
  4895. var fromData = false;
  4896. if (url.substr(0, 5) === "data:") {
  4897. fromData = true;
  4898. }
  4899. if (!fromData)
  4900. extension = url.substr(url.length - 4, 4).toLowerCase();
  4901. else {
  4902. var oldUrl = url;
  4903. fromData = oldUrl.split(':');
  4904. url = oldUrl;
  4905. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4906. }
  4907. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4908. var isTGA = (extension === ".tga");
  4909. scene._addPendingData(texture);
  4910. texture.url = url;
  4911. texture.noMipmap = noMipmap;
  4912. texture.references = 1;
  4913. this._loadedTexturesCache.push(texture);
  4914. var onerror = function () {
  4915. scene._removePendingData(texture);
  4916. if (onError) {
  4917. onError();
  4918. }
  4919. };
  4920. if (isTGA) {
  4921. var callback = function (arrayBuffer) {
  4922. var data = new Uint8Array(arrayBuffer);
  4923. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4924. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4925. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4926. if (onLoad) {
  4927. onLoad();
  4928. }
  4929. }, samplingMode);
  4930. };
  4931. if (!(fromData instanceof Array))
  4932. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4933. callback(arrayBuffer);
  4934. }, onerror, scene.database, true);
  4935. else
  4936. callback(buffer);
  4937. }
  4938. else if (isDDS) {
  4939. callback = function (data) {
  4940. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4942. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4943. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4944. if (onLoad) {
  4945. onLoad();
  4946. }
  4947. }, samplingMode);
  4948. };
  4949. if (!(fromData instanceof Array))
  4950. BABYLON.Tools.LoadFile(url, function (data) {
  4951. callback(data);
  4952. }, onerror, scene.database, true);
  4953. else
  4954. callback(buffer);
  4955. }
  4956. else {
  4957. var onload = function (img) {
  4958. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4959. var isPot = (img.width === potWidth && img.height === potHeight);
  4960. if (!isPot) {
  4961. _this._prepareWorkingCanvas();
  4962. _this._workingCanvas.width = potWidth;
  4963. _this._workingCanvas.height = potHeight;
  4964. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4965. _this._workingContext.imageSmoothingEnabled = false;
  4966. _this._workingContext.mozImageSmoothingEnabled = false;
  4967. _this._workingContext.oImageSmoothingEnabled = false;
  4968. _this._workingContext.webkitImageSmoothingEnabled = false;
  4969. _this._workingContext.msImageSmoothingEnabled = false;
  4970. }
  4971. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4972. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4973. _this._workingContext.imageSmoothingEnabled = true;
  4974. _this._workingContext.mozImageSmoothingEnabled = true;
  4975. _this._workingContext.oImageSmoothingEnabled = true;
  4976. _this._workingContext.webkitImageSmoothingEnabled = true;
  4977. _this._workingContext.msImageSmoothingEnabled = true;
  4978. }
  4979. }
  4980. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4981. if (onLoad) {
  4982. onLoad();
  4983. }
  4984. }, samplingMode);
  4985. };
  4986. if (!(fromData instanceof Array))
  4987. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4988. else
  4989. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4990. }
  4991. return texture;
  4992. };
  4993. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4994. var texture = this._gl.createTexture();
  4995. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4996. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4997. // Format
  4998. var internalFormat = this._gl.RGBA;
  4999. switch (format) {
  5000. case Engine.TEXTUREFORMAT_ALPHA:
  5001. internalFormat = this._gl.ALPHA;
  5002. break;
  5003. case Engine.TEXTUREFORMAT_LUMINANCE:
  5004. internalFormat = this._gl.LUMINANCE;
  5005. break;
  5006. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5007. internalFormat = this._gl.LUMINANCE_ALPHA;
  5008. break;
  5009. case Engine.TEXTUREFORMAT_RGB:
  5010. internalFormat = this._gl.RGB;
  5011. break;
  5012. case Engine.TEXTUREFORMAT_RGBA:
  5013. internalFormat = this._gl.RGBA;
  5014. break;
  5015. }
  5016. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5017. if (generateMipMaps) {
  5018. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5019. }
  5020. // Filters
  5021. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5023. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5024. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5025. this._activeTexturesCache = [];
  5026. texture._baseWidth = width;
  5027. texture._baseHeight = height;
  5028. texture._width = width;
  5029. texture._height = height;
  5030. texture.isReady = true;
  5031. texture.references = 1;
  5032. texture.samplingMode = samplingMode;
  5033. this._loadedTexturesCache.push(texture);
  5034. return texture;
  5035. };
  5036. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5037. var texture = this._gl.createTexture();
  5038. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5039. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5040. this._activeTexturesCache = [];
  5041. texture._baseWidth = width;
  5042. texture._baseHeight = height;
  5043. texture._width = width;
  5044. texture._height = height;
  5045. texture.isReady = false;
  5046. texture.generateMipMaps = generateMipMaps;
  5047. texture.references = 1;
  5048. texture.samplingMode = samplingMode;
  5049. this.updateTextureSamplingMode(samplingMode, texture);
  5050. this._loadedTexturesCache.push(texture);
  5051. return texture;
  5052. };
  5053. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5054. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5055. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5056. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5058. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5059. };
  5060. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5061. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5062. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5063. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5064. if (texture.generateMipMaps) {
  5065. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5066. }
  5067. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5068. this._activeTexturesCache = [];
  5069. texture.isReady = true;
  5070. };
  5071. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5072. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5073. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5074. // Scale the video if it is a NPOT using the current working canvas
  5075. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5076. if (!texture._workingCanvas) {
  5077. texture._workingCanvas = document.createElement("canvas");
  5078. texture._workingContext = texture._workingCanvas.getContext("2d");
  5079. texture._workingCanvas.width = texture._width;
  5080. texture._workingCanvas.height = texture._height;
  5081. }
  5082. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5083. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5084. }
  5085. else {
  5086. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5087. }
  5088. if (texture.generateMipMaps) {
  5089. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5090. }
  5091. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5092. this._activeTexturesCache = [];
  5093. texture.isReady = true;
  5094. };
  5095. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5096. // old version had a "generateMipMaps" arg instead of options.
  5097. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5098. // in the same way, generateDepthBuffer is defaulted to true
  5099. var generateMipMaps = false;
  5100. var generateDepthBuffer = true;
  5101. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5102. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5103. if (options !== undefined) {
  5104. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5105. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5106. type = options.type === undefined ? type : options.type;
  5107. if (options.samplingMode !== undefined) {
  5108. samplingMode = options.samplingMode;
  5109. }
  5110. if (type === Engine.TEXTURETYPE_FLOAT) {
  5111. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5112. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5113. }
  5114. }
  5115. var gl = this._gl;
  5116. var texture = gl.createTexture();
  5117. gl.bindTexture(gl.TEXTURE_2D, texture);
  5118. var width = size.width || size;
  5119. var height = size.height || size;
  5120. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5121. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5122. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5123. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5124. }
  5125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5129. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5130. var depthBuffer;
  5131. // Create the depth buffer
  5132. if (generateDepthBuffer) {
  5133. depthBuffer = gl.createRenderbuffer();
  5134. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5135. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5136. }
  5137. // Create the framebuffer
  5138. var framebuffer = gl.createFramebuffer();
  5139. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5141. if (generateDepthBuffer) {
  5142. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5143. }
  5144. // Unbind
  5145. gl.bindTexture(gl.TEXTURE_2D, null);
  5146. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5147. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5148. texture._framebuffer = framebuffer;
  5149. if (generateDepthBuffer) {
  5150. texture._depthBuffer = depthBuffer;
  5151. }
  5152. texture._width = width;
  5153. texture._height = height;
  5154. texture.isReady = true;
  5155. texture.generateMipMaps = generateMipMaps;
  5156. texture.references = 1;
  5157. texture.samplingMode = samplingMode;
  5158. this._activeTexturesCache = [];
  5159. this._loadedTexturesCache.push(texture);
  5160. return texture;
  5161. };
  5162. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5163. var _this = this;
  5164. var gl = this._gl;
  5165. var texture = gl.createTexture();
  5166. texture.isCube = true;
  5167. texture.url = rootUrl;
  5168. texture.references = 1;
  5169. this._loadedTexturesCache.push(texture);
  5170. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5171. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5172. if (isDDS) {
  5173. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5174. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5175. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5176. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5177. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5178. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5179. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5180. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5181. }
  5182. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5183. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5186. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5187. _this._activeTexturesCache = [];
  5188. texture._width = info.width;
  5189. texture._height = info.height;
  5190. texture.isReady = true;
  5191. }, null, null, true);
  5192. }
  5193. else {
  5194. cascadeLoad(rootUrl, scene, function (imgs) {
  5195. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5196. var height = width;
  5197. _this._prepareWorkingCanvas();
  5198. _this._workingCanvas.width = width;
  5199. _this._workingCanvas.height = height;
  5200. var faces = [
  5201. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5202. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5203. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5204. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5205. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5206. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5207. ];
  5208. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5210. for (var index = 0; index < faces.length; index++) {
  5211. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5212. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5213. }
  5214. if (!noMipmap) {
  5215. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5216. }
  5217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5221. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5222. _this._activeTexturesCache = [];
  5223. texture._width = width;
  5224. texture._height = height;
  5225. texture.isReady = true;
  5226. }, extensions);
  5227. }
  5228. return texture;
  5229. };
  5230. Engine.prototype._releaseTexture = function (texture) {
  5231. var gl = this._gl;
  5232. if (texture._framebuffer) {
  5233. gl.deleteFramebuffer(texture._framebuffer);
  5234. }
  5235. if (texture._depthBuffer) {
  5236. gl.deleteRenderbuffer(texture._depthBuffer);
  5237. }
  5238. gl.deleteTexture(texture);
  5239. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5240. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5241. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5242. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5243. this._activeTexturesCache[channel] = null;
  5244. }
  5245. var index = this._loadedTexturesCache.indexOf(texture);
  5246. if (index !== -1) {
  5247. this._loadedTexturesCache.splice(index, 1);
  5248. }
  5249. };
  5250. Engine.prototype.bindSamplers = function (effect) {
  5251. this._gl.useProgram(effect.getProgram());
  5252. var samplers = effect.getSamplers();
  5253. for (var index = 0; index < samplers.length; index++) {
  5254. var uniform = effect.getUniform(samplers[index]);
  5255. this._gl.uniform1i(uniform, index);
  5256. }
  5257. this._currentEffect = null;
  5258. };
  5259. Engine.prototype._bindTexture = function (channel, texture) {
  5260. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5261. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5262. this._activeTexturesCache[channel] = null;
  5263. };
  5264. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5265. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5266. };
  5267. Engine.prototype.setTexture = function (channel, texture) {
  5268. if (channel < 0) {
  5269. return;
  5270. }
  5271. // Not ready?
  5272. if (!texture || !texture.isReady()) {
  5273. if (this._activeTexturesCache[channel] != null) {
  5274. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5275. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5276. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5277. this._activeTexturesCache[channel] = null;
  5278. }
  5279. return;
  5280. }
  5281. // Video
  5282. if (texture instanceof BABYLON.VideoTexture) {
  5283. if (texture.update()) {
  5284. this._activeTexturesCache[channel] = null;
  5285. }
  5286. }
  5287. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5288. texture.delayLoad();
  5289. return;
  5290. }
  5291. if (this._activeTexturesCache[channel] === texture) {
  5292. return;
  5293. }
  5294. this._activeTexturesCache[channel] = texture;
  5295. var internalTexture = texture.getInternalTexture();
  5296. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5297. if (internalTexture.isCube) {
  5298. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5299. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5300. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5301. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5302. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5303. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5304. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5305. }
  5306. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5307. }
  5308. else {
  5309. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5310. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5311. internalTexture._cachedWrapU = texture.wrapU;
  5312. switch (texture.wrapU) {
  5313. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5315. break;
  5316. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5317. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5318. break;
  5319. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5321. break;
  5322. }
  5323. }
  5324. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5325. internalTexture._cachedWrapV = texture.wrapV;
  5326. switch (texture.wrapV) {
  5327. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5329. break;
  5330. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5332. break;
  5333. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5334. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5335. break;
  5336. }
  5337. }
  5338. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5339. }
  5340. };
  5341. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5342. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5343. var value = texture.anisotropicFilteringLevel;
  5344. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5345. value = 1;
  5346. }
  5347. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5348. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5349. texture._cachedAnisotropicFilteringLevel = value;
  5350. }
  5351. };
  5352. Engine.prototype.readPixels = function (x, y, width, height) {
  5353. var data = new Uint8Array(height * width * 4);
  5354. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5355. return data;
  5356. };
  5357. // Dispose
  5358. Engine.prototype.dispose = function () {
  5359. this.hideLoadingUI();
  5360. this.stopRenderLoop();
  5361. while (this.scenes.length) {
  5362. this.scenes[0].dispose();
  5363. }
  5364. // Release audio engine
  5365. Engine.audioEngine.dispose();
  5366. for (var name in this._compiledEffects) {
  5367. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5368. }
  5369. for (var i in this._vertexAttribArrays) {
  5370. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5371. continue;
  5372. }
  5373. this._gl.disableVertexAttribArray(i);
  5374. }
  5375. // Events
  5376. window.removeEventListener("blur", this._onBlur);
  5377. window.removeEventListener("focus", this._onFocus);
  5378. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5379. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5380. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5381. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5382. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5383. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5384. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5385. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5386. };
  5387. // Loading screen
  5388. Engine.prototype.displayLoadingUI = function () {
  5389. var _this = this;
  5390. this._loadingDiv = document.createElement("div");
  5391. this._loadingDiv.style.opacity = "0";
  5392. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5393. // Loading text
  5394. this._loadingTextDiv = document.createElement("div");
  5395. this._loadingTextDiv.style.position = "absolute";
  5396. this._loadingTextDiv.style.left = "0";
  5397. this._loadingTextDiv.style.top = "50%";
  5398. this._loadingTextDiv.style.marginTop = "80px";
  5399. this._loadingTextDiv.style.width = "100%";
  5400. this._loadingTextDiv.style.height = "20px";
  5401. this._loadingTextDiv.style.fontFamily = "Arial";
  5402. this._loadingTextDiv.style.fontSize = "14px";
  5403. this._loadingTextDiv.style.color = "white";
  5404. this._loadingTextDiv.style.textAlign = "center";
  5405. this._loadingTextDiv.innerHTML = "Loading";
  5406. this._loadingDiv.appendChild(this._loadingTextDiv);
  5407. // Loading img
  5408. var imgBack = new Image();
  5409. 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==";
  5410. imgBack.style.position = "absolute";
  5411. imgBack.style.left = "50%";
  5412. imgBack.style.top = "50%";
  5413. imgBack.style.marginLeft = "-50px";
  5414. imgBack.style.marginTop = "-50px";
  5415. imgBack.style.transition = "transform 1.0s ease";
  5416. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5417. var deg = 360;
  5418. var onTransitionEnd = function () {
  5419. deg += 360;
  5420. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5421. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5422. };
  5423. imgBack.addEventListener("transitionend", onTransitionEnd);
  5424. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5425. this._loadingDiv.appendChild(imgBack);
  5426. // front image
  5427. var imgFront = new Image();
  5428. 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=";
  5429. imgFront.style.position = "absolute";
  5430. imgFront.style.left = "50%";
  5431. imgFront.style.top = "50%";
  5432. imgFront.style.marginLeft = "-50px";
  5433. imgFront.style.marginTop = "-50px";
  5434. this._loadingDiv.appendChild(imgFront);
  5435. // Resize
  5436. this._resizeLoadingUI = function () {
  5437. var canvasRect = _this.getRenderingCanvasClientRect();
  5438. _this._loadingDiv.style.position = "absolute";
  5439. _this._loadingDiv.style.left = canvasRect.left + "px";
  5440. _this._loadingDiv.style.top = canvasRect.top + "px";
  5441. _this._loadingDiv.style.width = canvasRect.width + "px";
  5442. _this._loadingDiv.style.height = canvasRect.height + "px";
  5443. };
  5444. this._resizeLoadingUI();
  5445. window.addEventListener("resize", this._resizeLoadingUI);
  5446. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5447. document.body.appendChild(this._loadingDiv);
  5448. setTimeout(function () {
  5449. _this._loadingDiv.style.opacity = "1";
  5450. imgBack.style.transform = "rotateZ(360deg)";
  5451. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5452. }, 0);
  5453. };
  5454. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5455. set: function (text) {
  5456. if (!this._loadingDiv) {
  5457. return;
  5458. }
  5459. this._loadingTextDiv.innerHTML = text;
  5460. },
  5461. enumerable: true,
  5462. configurable: true
  5463. });
  5464. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5465. get: function () {
  5466. return this._loadingDivBackgroundColor;
  5467. },
  5468. set: function (color) {
  5469. this._loadingDivBackgroundColor = color;
  5470. if (!this._loadingDiv) {
  5471. return;
  5472. }
  5473. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5474. },
  5475. enumerable: true,
  5476. configurable: true
  5477. });
  5478. Engine.prototype.hideLoadingUI = function () {
  5479. var _this = this;
  5480. if (!this._loadingDiv) {
  5481. return;
  5482. }
  5483. var onTransitionEnd = function () {
  5484. if (!_this._loadingDiv) {
  5485. return;
  5486. }
  5487. document.body.removeChild(_this._loadingDiv);
  5488. window.removeEventListener("resize", _this._resizeLoadingUI);
  5489. _this._loadingDiv = null;
  5490. };
  5491. this._loadingDiv.style.opacity = "0";
  5492. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5493. };
  5494. // FPS
  5495. Engine.prototype.getFps = function () {
  5496. return this.fps;
  5497. };
  5498. Engine.prototype.getDeltaTime = function () {
  5499. return this.deltaTime;
  5500. };
  5501. Engine.prototype._measureFps = function () {
  5502. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5503. var length = this.previousFramesDuration.length;
  5504. if (length >= 2) {
  5505. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5506. }
  5507. if (length >= this.fpsRange) {
  5508. if (length > this.fpsRange) {
  5509. this.previousFramesDuration.splice(0, 1);
  5510. length = this.previousFramesDuration.length;
  5511. }
  5512. var sum = 0;
  5513. for (var id = 0; id < length - 1; id++) {
  5514. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5515. }
  5516. this.fps = 1000.0 / (sum / (length - 1));
  5517. }
  5518. };
  5519. // Statics
  5520. Engine.isSupported = function () {
  5521. try {
  5522. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5523. if (navigator.isCocoonJS) {
  5524. return true;
  5525. }
  5526. var tempcanvas = document.createElement("canvas");
  5527. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5528. return gl != null && !!window.WebGLRenderingContext;
  5529. }
  5530. catch (e) {
  5531. return false;
  5532. }
  5533. };
  5534. // Const statics
  5535. Engine._ALPHA_DISABLE = 0;
  5536. Engine._ALPHA_ADD = 1;
  5537. Engine._ALPHA_COMBINE = 2;
  5538. Engine._DELAYLOADSTATE_NONE = 0;
  5539. Engine._DELAYLOADSTATE_LOADED = 1;
  5540. Engine._DELAYLOADSTATE_LOADING = 2;
  5541. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5542. Engine._TEXTUREFORMAT_ALPHA = 0;
  5543. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5544. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5545. Engine._TEXTUREFORMAT_RGB = 4;
  5546. Engine._TEXTUREFORMAT_RGBA = 4;
  5547. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5548. Engine._TEXTURETYPE_FLOAT = 1;
  5549. // Updatable statics so stick with vars here
  5550. Engine.Epsilon = 0.001;
  5551. Engine.CollisionsEpsilon = 0.001;
  5552. Engine.ShadersRepository = "Babylon/Shaders/";
  5553. return Engine;
  5554. })();
  5555. BABYLON.Engine = Engine;
  5556. })(BABYLON || (BABYLON = {}));
  5557. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5558. (function (BABYLON) {
  5559. /**
  5560. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5561. */
  5562. var Node = (function () {
  5563. /**
  5564. * @constructor
  5565. * @param {string} name - the name and id to be given to this node
  5566. * @param {BABYLON.Scene} the scene this node will be added to
  5567. */
  5568. function Node(name, scene) {
  5569. this.state = "";
  5570. this.animations = new Array();
  5571. this._childrenFlag = -1;
  5572. this._isEnabled = true;
  5573. this._isReady = true;
  5574. this._currentRenderId = -1;
  5575. this._parentRenderId = -1;
  5576. this.name = name;
  5577. this.id = name;
  5578. this._scene = scene;
  5579. this._initCache();
  5580. }
  5581. Node.prototype.getScene = function () {
  5582. return this._scene;
  5583. };
  5584. Node.prototype.getEngine = function () {
  5585. return this._scene.getEngine();
  5586. };
  5587. // override it in derived class
  5588. Node.prototype.getWorldMatrix = function () {
  5589. return BABYLON.Matrix.Identity();
  5590. };
  5591. // override it in derived class if you add new variables to the cache
  5592. // and call the parent class method
  5593. Node.prototype._initCache = function () {
  5594. this._cache = {};
  5595. this._cache.parent = undefined;
  5596. };
  5597. Node.prototype.updateCache = function (force) {
  5598. if (!force && this.isSynchronized())
  5599. return;
  5600. this._cache.parent = this.parent;
  5601. this._updateCache();
  5602. };
  5603. // override it in derived class if you add new variables to the cache
  5604. // and call the parent class method if !ignoreParentClass
  5605. Node.prototype._updateCache = function (ignoreParentClass) {
  5606. };
  5607. // override it in derived class if you add new variables to the cache
  5608. Node.prototype._isSynchronized = function () {
  5609. return true;
  5610. };
  5611. Node.prototype.isSynchronizedWithParent = function () {
  5612. if (!this.parent) {
  5613. return true;
  5614. }
  5615. if (this._parentRenderId !== this.parent._currentRenderId) {
  5616. this._parentRenderId = this.parent._currentRenderId;
  5617. return false;
  5618. }
  5619. return this.parent.isSynchronized();
  5620. };
  5621. Node.prototype.isSynchronized = function (updateCache) {
  5622. var check = this.hasNewParent();
  5623. check = check || !this.isSynchronizedWithParent();
  5624. check = check || !this._isSynchronized();
  5625. if (updateCache)
  5626. this.updateCache(true);
  5627. return !check;
  5628. };
  5629. Node.prototype.hasNewParent = function (update) {
  5630. if (this._cache.parent === this.parent)
  5631. return false;
  5632. if (update)
  5633. this._cache.parent = this.parent;
  5634. return true;
  5635. };
  5636. /**
  5637. * Is this node ready to be used/rendered
  5638. * @return {boolean} is it ready
  5639. */
  5640. Node.prototype.isReady = function () {
  5641. return this._isReady;
  5642. };
  5643. /**
  5644. * Is this node enabled.
  5645. * If the node has a parent and is enabled, the parent will be inspected as well.
  5646. * @return {boolean} whether this node (and its parent) is enabled.
  5647. * @see setEnabled
  5648. */
  5649. Node.prototype.isEnabled = function () {
  5650. if (!this._isEnabled) {
  5651. return false;
  5652. }
  5653. if (this.parent) {
  5654. return this.parent.isEnabled();
  5655. }
  5656. return true;
  5657. };
  5658. /**
  5659. * Set the enabled state of this node.
  5660. * @param {boolean} value - the new enabled state
  5661. * @see isEnabled
  5662. */
  5663. Node.prototype.setEnabled = function (value) {
  5664. this._isEnabled = value;
  5665. };
  5666. /**
  5667. * Is this node a descendant of the given node.
  5668. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5669. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5670. * @see parent
  5671. */
  5672. Node.prototype.isDescendantOf = function (ancestor) {
  5673. if (this.parent) {
  5674. if (this.parent === ancestor) {
  5675. return true;
  5676. }
  5677. return this.parent.isDescendantOf(ancestor);
  5678. }
  5679. return false;
  5680. };
  5681. Node.prototype._getDescendants = function (list, results) {
  5682. for (var index = 0; index < list.length; index++) {
  5683. var item = list[index];
  5684. if (item.isDescendantOf(this)) {
  5685. results.push(item);
  5686. }
  5687. }
  5688. };
  5689. /**
  5690. * Will return all nodes that have this node as parent.
  5691. * @return {BABYLON.Node[]} all children nodes of all types.
  5692. */
  5693. Node.prototype.getDescendants = function () {
  5694. var results = [];
  5695. this._getDescendants(this._scene.meshes, results);
  5696. this._getDescendants(this._scene.lights, results);
  5697. this._getDescendants(this._scene.cameras, results);
  5698. return results;
  5699. };
  5700. Node.prototype._setReady = function (state) {
  5701. if (state == this._isReady) {
  5702. return;
  5703. }
  5704. if (!state) {
  5705. this._isReady = false;
  5706. return;
  5707. }
  5708. this._isReady = true;
  5709. if (this.onReady) {
  5710. this.onReady(this);
  5711. }
  5712. };
  5713. return Node;
  5714. })();
  5715. BABYLON.Node = Node;
  5716. })(BABYLON || (BABYLON = {}));
  5717. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5718. (function (BABYLON) {
  5719. var BoundingSphere = (function () {
  5720. function BoundingSphere(minimum, maximum) {
  5721. this.minimum = minimum;
  5722. this.maximum = maximum;
  5723. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5724. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5725. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5726. this.radius = distance * 0.5;
  5727. this.centerWorld = BABYLON.Vector3.Zero();
  5728. this._update(BABYLON.Matrix.Identity());
  5729. }
  5730. // Methods
  5731. BoundingSphere.prototype._update = function (world) {
  5732. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5733. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5734. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5735. };
  5736. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5737. for (var i = 0; i < 6; i++) {
  5738. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5739. return false;
  5740. }
  5741. return true;
  5742. };
  5743. BoundingSphere.prototype.intersectsPoint = function (point) {
  5744. var x = this.centerWorld.x - point.x;
  5745. var y = this.centerWorld.y - point.y;
  5746. var z = this.centerWorld.z - point.z;
  5747. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5748. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5749. return false;
  5750. return true;
  5751. };
  5752. // Statics
  5753. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5754. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5755. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5756. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5757. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5758. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5759. return false;
  5760. return true;
  5761. };
  5762. return BoundingSphere;
  5763. })();
  5764. BABYLON.BoundingSphere = BoundingSphere;
  5765. })(BABYLON || (BABYLON = {}));
  5766. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5767. (function (BABYLON) {
  5768. var BoundingBox = (function () {
  5769. function BoundingBox(minimum, maximum) {
  5770. this.minimum = minimum;
  5771. this.maximum = maximum;
  5772. this.vectors = new Array();
  5773. this.vectorsWorld = new Array();
  5774. // Bounding vectors
  5775. this.vectors.push(this.minimum.clone());
  5776. this.vectors.push(this.maximum.clone());
  5777. this.vectors.push(this.minimum.clone());
  5778. this.vectors[2].x = this.maximum.x;
  5779. this.vectors.push(this.minimum.clone());
  5780. this.vectors[3].y = this.maximum.y;
  5781. this.vectors.push(this.minimum.clone());
  5782. this.vectors[4].z = this.maximum.z;
  5783. this.vectors.push(this.maximum.clone());
  5784. this.vectors[5].z = this.minimum.z;
  5785. this.vectors.push(this.maximum.clone());
  5786. this.vectors[6].x = this.minimum.x;
  5787. this.vectors.push(this.maximum.clone());
  5788. this.vectors[7].y = this.minimum.y;
  5789. // OBB
  5790. this.center = this.maximum.add(this.minimum).scale(0.5);
  5791. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5792. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5793. for (var index = 0; index < this.vectors.length; index++) {
  5794. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5795. }
  5796. this.minimumWorld = BABYLON.Vector3.Zero();
  5797. this.maximumWorld = BABYLON.Vector3.Zero();
  5798. this._update(BABYLON.Matrix.Identity());
  5799. }
  5800. // Methods
  5801. BoundingBox.prototype.getWorldMatrix = function () {
  5802. return this._worldMatrix;
  5803. };
  5804. BoundingBox.prototype._update = function (world) {
  5805. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5806. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5807. for (var index = 0; index < this.vectors.length; index++) {
  5808. var v = this.vectorsWorld[index];
  5809. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5810. if (v.x < this.minimumWorld.x)
  5811. this.minimumWorld.x = v.x;
  5812. if (v.y < this.minimumWorld.y)
  5813. this.minimumWorld.y = v.y;
  5814. if (v.z < this.minimumWorld.z)
  5815. this.minimumWorld.z = v.z;
  5816. if (v.x > this.maximumWorld.x)
  5817. this.maximumWorld.x = v.x;
  5818. if (v.y > this.maximumWorld.y)
  5819. this.maximumWorld.y = v.y;
  5820. if (v.z > this.maximumWorld.z)
  5821. this.maximumWorld.z = v.z;
  5822. }
  5823. // OBB
  5824. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5825. this.center.scaleInPlace(0.5);
  5826. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5827. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5828. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5829. this._worldMatrix = world;
  5830. };
  5831. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5832. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5833. };
  5834. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5835. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5836. };
  5837. BoundingBox.prototype.intersectsPoint = function (point) {
  5838. var delta = BABYLON.Engine.Epsilon;
  5839. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5840. return false;
  5841. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5842. return false;
  5843. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5844. return false;
  5845. return true;
  5846. };
  5847. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5848. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5849. };
  5850. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5851. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5852. return false;
  5853. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5854. return false;
  5855. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5856. return false;
  5857. return true;
  5858. };
  5859. // Statics
  5860. BoundingBox.Intersects = function (box0, box1) {
  5861. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5862. return false;
  5863. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5864. return false;
  5865. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5866. return false;
  5867. return true;
  5868. };
  5869. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5870. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5871. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5872. return (num <= (sphereRadius * sphereRadius));
  5873. };
  5874. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5875. for (var p = 0; p < 6; p++) {
  5876. for (var i = 0; i < 8; i++) {
  5877. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5878. return false;
  5879. }
  5880. }
  5881. }
  5882. return true;
  5883. };
  5884. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5885. for (var p = 0; p < 6; p++) {
  5886. var inCount = 8;
  5887. for (var i = 0; i < 8; i++) {
  5888. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5889. --inCount;
  5890. }
  5891. else {
  5892. break;
  5893. }
  5894. }
  5895. if (inCount === 0)
  5896. return false;
  5897. }
  5898. return true;
  5899. };
  5900. return BoundingBox;
  5901. })();
  5902. BABYLON.BoundingBox = BoundingBox;
  5903. })(BABYLON || (BABYLON = {}));
  5904. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5905. (function (BABYLON) {
  5906. var computeBoxExtents = function (axis, box) {
  5907. var p = BABYLON.Vector3.Dot(box.center, axis);
  5908. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5909. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5910. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5911. var r = r0 + r1 + r2;
  5912. return {
  5913. min: p - r,
  5914. max: p + r
  5915. };
  5916. };
  5917. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5918. var axisOverlap = function (axis, box0, box1) {
  5919. var result0 = computeBoxExtents(axis, box0);
  5920. var result1 = computeBoxExtents(axis, box1);
  5921. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5922. };
  5923. var BoundingInfo = (function () {
  5924. function BoundingInfo(minimum, maximum) {
  5925. this.minimum = minimum;
  5926. this.maximum = maximum;
  5927. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5928. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5929. }
  5930. // Methods
  5931. BoundingInfo.prototype._update = function (world) {
  5932. this.boundingBox._update(world);
  5933. this.boundingSphere._update(world);
  5934. };
  5935. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5936. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5937. return false;
  5938. return this.boundingBox.isInFrustum(frustumPlanes);
  5939. };
  5940. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5941. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5942. };
  5943. BoundingInfo.prototype._checkCollision = function (collider) {
  5944. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5945. };
  5946. BoundingInfo.prototype.intersectsPoint = function (point) {
  5947. if (!this.boundingSphere.centerWorld) {
  5948. return false;
  5949. }
  5950. if (!this.boundingSphere.intersectsPoint(point)) {
  5951. return false;
  5952. }
  5953. if (!this.boundingBox.intersectsPoint(point)) {
  5954. return false;
  5955. }
  5956. return true;
  5957. };
  5958. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5959. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5960. return false;
  5961. }
  5962. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5963. return false;
  5964. }
  5965. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5966. return false;
  5967. }
  5968. if (!precise) {
  5969. return true;
  5970. }
  5971. var box0 = this.boundingBox;
  5972. var box1 = boundingInfo.boundingBox;
  5973. if (!axisOverlap(box0.directions[0], box0, box1))
  5974. return false;
  5975. if (!axisOverlap(box0.directions[1], box0, box1))
  5976. return false;
  5977. if (!axisOverlap(box0.directions[2], box0, box1))
  5978. return false;
  5979. if (!axisOverlap(box1.directions[0], box0, box1))
  5980. return false;
  5981. if (!axisOverlap(box1.directions[1], box0, box1))
  5982. return false;
  5983. if (!axisOverlap(box1.directions[2], box0, box1))
  5984. return false;
  5985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5986. return false;
  5987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5988. return false;
  5989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5990. return false;
  5991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5992. return false;
  5993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5994. return false;
  5995. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5996. return false;
  5997. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5998. return false;
  5999. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6000. return false;
  6001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6002. return false;
  6003. return true;
  6004. };
  6005. return BoundingInfo;
  6006. })();
  6007. BABYLON.BoundingInfo = BoundingInfo;
  6008. })(BABYLON || (BABYLON = {}));
  6009. //# sourceMappingURL=babylon.boundingInfo.js.map
  6010. var BABYLON;
  6011. (function (BABYLON) {
  6012. var Light = (function (_super) {
  6013. __extends(Light, _super);
  6014. function Light(name, scene) {
  6015. _super.call(this, name, scene);
  6016. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6017. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6018. this.intensity = 1.0;
  6019. this.range = Number.MAX_VALUE;
  6020. this.includeOnlyWithLayerMask = 0;
  6021. this.includedOnlyMeshes = new Array();
  6022. this.excludedMeshes = new Array();
  6023. this.excludeWithLayerMask = 0;
  6024. this._excludedMeshesIds = new Array();
  6025. this._includedOnlyMeshesIds = new Array();
  6026. scene.addLight(this);
  6027. }
  6028. Light.prototype.getShadowGenerator = function () {
  6029. return this._shadowGenerator;
  6030. };
  6031. Light.prototype.getAbsolutePosition = function () {
  6032. return BABYLON.Vector3.Zero();
  6033. };
  6034. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6035. };
  6036. Light.prototype._getWorldMatrix = function () {
  6037. return BABYLON.Matrix.Identity();
  6038. };
  6039. Light.prototype.canAffectMesh = function (mesh) {
  6040. if (!mesh) {
  6041. return true;
  6042. }
  6043. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6044. return false;
  6045. }
  6046. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6047. return false;
  6048. }
  6049. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6050. return false;
  6051. }
  6052. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6053. return false;
  6054. }
  6055. return true;
  6056. };
  6057. Light.prototype.getWorldMatrix = function () {
  6058. this._currentRenderId = this.getScene().getRenderId();
  6059. var worldMatrix = this._getWorldMatrix();
  6060. if (this.parent && this.parent.getWorldMatrix) {
  6061. if (!this._parentedWorldMatrix) {
  6062. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6063. }
  6064. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6065. return this._parentedWorldMatrix;
  6066. }
  6067. return worldMatrix;
  6068. };
  6069. Light.prototype.dispose = function () {
  6070. if (this._shadowGenerator) {
  6071. this._shadowGenerator.dispose();
  6072. this._shadowGenerator = null;
  6073. }
  6074. // Remove from scene
  6075. this.getScene().removeLight(this);
  6076. };
  6077. return Light;
  6078. })(BABYLON.Node);
  6079. BABYLON.Light = Light;
  6080. })(BABYLON || (BABYLON = {}));
  6081. //# sourceMappingURL=babylon.light.js.map
  6082. var BABYLON;
  6083. (function (BABYLON) {
  6084. var PointLight = (function (_super) {
  6085. __extends(PointLight, _super);
  6086. function PointLight(name, position, scene) {
  6087. _super.call(this, name, scene);
  6088. this.position = position;
  6089. }
  6090. PointLight.prototype.getAbsolutePosition = function () {
  6091. return this._transformedPosition ? this._transformedPosition : this.position;
  6092. };
  6093. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6094. if (this.parent && this.parent.getWorldMatrix) {
  6095. if (!this._transformedPosition) {
  6096. this._transformedPosition = BABYLON.Vector3.Zero();
  6097. }
  6098. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6099. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6100. return;
  6101. }
  6102. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6103. };
  6104. PointLight.prototype.getShadowGenerator = function () {
  6105. return null;
  6106. };
  6107. PointLight.prototype._getWorldMatrix = function () {
  6108. if (!this._worldMatrix) {
  6109. this._worldMatrix = BABYLON.Matrix.Identity();
  6110. }
  6111. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6112. return this._worldMatrix;
  6113. };
  6114. return PointLight;
  6115. })(BABYLON.Light);
  6116. BABYLON.PointLight = PointLight;
  6117. })(BABYLON || (BABYLON = {}));
  6118. //# sourceMappingURL=babylon.pointLight.js.map
  6119. var BABYLON;
  6120. (function (BABYLON) {
  6121. var SpotLight = (function (_super) {
  6122. __extends(SpotLight, _super);
  6123. function SpotLight(name, position, direction, angle, exponent, scene) {
  6124. _super.call(this, name, scene);
  6125. this.position = position;
  6126. this.direction = direction;
  6127. this.angle = angle;
  6128. this.exponent = exponent;
  6129. }
  6130. SpotLight.prototype.getAbsolutePosition = function () {
  6131. return this.transformedPosition ? this.transformedPosition : this.position;
  6132. };
  6133. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6134. var activeCamera = this.getScene().activeCamera;
  6135. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6136. };
  6137. SpotLight.prototype.supportsVSM = function () {
  6138. return true;
  6139. };
  6140. SpotLight.prototype.needRefreshPerFrame = function () {
  6141. return false;
  6142. };
  6143. SpotLight.prototype.setDirectionToTarget = function (target) {
  6144. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6145. return this.direction;
  6146. };
  6147. SpotLight.prototype.computeTransformedPosition = function () {
  6148. if (this.parent && this.parent.getWorldMatrix) {
  6149. if (!this.transformedPosition) {
  6150. this.transformedPosition = BABYLON.Vector3.Zero();
  6151. }
  6152. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6153. return true;
  6154. }
  6155. return false;
  6156. };
  6157. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6158. var normalizeDirection;
  6159. if (this.parent && this.parent.getWorldMatrix) {
  6160. if (!this._transformedDirection) {
  6161. this._transformedDirection = BABYLON.Vector3.Zero();
  6162. }
  6163. this.computeTransformedPosition();
  6164. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6165. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6166. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6167. }
  6168. else {
  6169. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6170. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6171. }
  6172. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6173. };
  6174. SpotLight.prototype._getWorldMatrix = function () {
  6175. if (!this._worldMatrix) {
  6176. this._worldMatrix = BABYLON.Matrix.Identity();
  6177. }
  6178. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6179. return this._worldMatrix;
  6180. };
  6181. return SpotLight;
  6182. })(BABYLON.Light);
  6183. BABYLON.SpotLight = SpotLight;
  6184. })(BABYLON || (BABYLON = {}));
  6185. //# sourceMappingURL=babylon.spotLight.js.map
  6186. var BABYLON;
  6187. (function (BABYLON) {
  6188. var DirectionalLight = (function (_super) {
  6189. __extends(DirectionalLight, _super);
  6190. function DirectionalLight(name, direction, scene) {
  6191. _super.call(this, name, scene);
  6192. this.direction = direction;
  6193. this.shadowOrthoScale = 0.5;
  6194. this.position = direction.scale(-1);
  6195. }
  6196. DirectionalLight.prototype.getAbsolutePosition = function () {
  6197. return this.transformedPosition ? this.transformedPosition : this.position;
  6198. };
  6199. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6200. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6201. return this.direction;
  6202. };
  6203. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6204. var orthoLeft = Number.MAX_VALUE;
  6205. var orthoRight = Number.MIN_VALUE;
  6206. var orthoTop = Number.MIN_VALUE;
  6207. var orthoBottom = Number.MAX_VALUE;
  6208. var tempVector3 = BABYLON.Vector3.Zero();
  6209. var activeCamera = this.getScene().activeCamera;
  6210. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6211. var mesh = renderList[meshIndex];
  6212. if (!mesh) {
  6213. continue;
  6214. }
  6215. var boundingInfo = mesh.getBoundingInfo();
  6216. if (!boundingInfo) {
  6217. continue;
  6218. }
  6219. var boundingBox = boundingInfo.boundingBox;
  6220. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6221. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6222. if (tempVector3.x < orthoLeft)
  6223. orthoLeft = tempVector3.x;
  6224. if (tempVector3.y < orthoBottom)
  6225. orthoBottom = tempVector3.y;
  6226. if (tempVector3.x > orthoRight)
  6227. orthoRight = tempVector3.x;
  6228. if (tempVector3.y > orthoTop)
  6229. orthoTop = tempVector3.y;
  6230. }
  6231. }
  6232. var xOffset = orthoRight - orthoLeft;
  6233. var yOffset = orthoTop - orthoBottom;
  6234. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6235. };
  6236. DirectionalLight.prototype.supportsVSM = function () {
  6237. return true;
  6238. };
  6239. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6240. return true;
  6241. };
  6242. DirectionalLight.prototype.computeTransformedPosition = function () {
  6243. if (this.parent && this.parent.getWorldMatrix) {
  6244. if (!this.transformedPosition) {
  6245. this.transformedPosition = BABYLON.Vector3.Zero();
  6246. }
  6247. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6248. return true;
  6249. }
  6250. return false;
  6251. };
  6252. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6253. if (this.parent && this.parent.getWorldMatrix) {
  6254. if (!this._transformedDirection) {
  6255. this._transformedDirection = BABYLON.Vector3.Zero();
  6256. }
  6257. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6258. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6259. return;
  6260. }
  6261. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6262. };
  6263. DirectionalLight.prototype._getWorldMatrix = function () {
  6264. if (!this._worldMatrix) {
  6265. this._worldMatrix = BABYLON.Matrix.Identity();
  6266. }
  6267. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6268. return this._worldMatrix;
  6269. };
  6270. return DirectionalLight;
  6271. })(BABYLON.Light);
  6272. BABYLON.DirectionalLight = DirectionalLight;
  6273. })(BABYLON || (BABYLON = {}));
  6274. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6275. (function (BABYLON) {
  6276. var ShadowGenerator = (function () {
  6277. function ShadowGenerator(mapSize, light) {
  6278. var _this = this;
  6279. // Members
  6280. this._filter = ShadowGenerator.FILTER_NONE;
  6281. this.blurScale = 2;
  6282. this._blurBoxOffset = 0;
  6283. this._bias = 0.00005;
  6284. this._darkness = 0;
  6285. this._transparencyShadow = false;
  6286. this._viewMatrix = BABYLON.Matrix.Zero();
  6287. this._projectionMatrix = BABYLON.Matrix.Zero();
  6288. this._transformMatrix = BABYLON.Matrix.Zero();
  6289. this._worldViewProjection = BABYLON.Matrix.Zero();
  6290. this._light = light;
  6291. this._scene = light.getScene();
  6292. this._mapSize = mapSize;
  6293. light._shadowGenerator = this;
  6294. // Render target
  6295. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6296. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6297. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6298. this._shadowMap.anisotropicFilteringLevel = 1;
  6299. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6300. this._shadowMap.renderParticles = false;
  6301. this._shadowMap.onAfterUnbind = function () {
  6302. if (!_this.useBlurVarianceShadowMap) {
  6303. return;
  6304. }
  6305. if (!_this._shadowMap2) {
  6306. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6307. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6308. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6309. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6310. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6311. _this._downSamplePostprocess.onApply = function (effect) {
  6312. effect.setTexture("textureSampler", _this._shadowMap);
  6313. };
  6314. _this.blurBoxOffset = 1;
  6315. }
  6316. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6317. };
  6318. // Custom render function
  6319. var renderSubMesh = function (subMesh) {
  6320. var mesh = subMesh.getRenderingMesh();
  6321. var scene = _this._scene;
  6322. var engine = scene.getEngine();
  6323. // Culling
  6324. engine.setState(subMesh.getMaterial().backFaceCulling);
  6325. // Managing instances
  6326. var batch = mesh._getInstancesRenderList(subMesh._id);
  6327. if (batch.mustReturn) {
  6328. return;
  6329. }
  6330. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6331. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6332. engine.enableEffect(_this._effect);
  6333. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6334. var material = subMesh.getMaterial();
  6335. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6336. // Alpha test
  6337. if (material && material.needAlphaTesting()) {
  6338. var alphaTexture = material.getAlphaTestTexture();
  6339. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6340. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6341. }
  6342. // Bones
  6343. if (mesh.useBones) {
  6344. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6345. }
  6346. // Draw
  6347. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6348. }
  6349. else {
  6350. // Need to reset refresh rate of the shadowMap
  6351. _this._shadowMap.resetRefreshCounter();
  6352. }
  6353. };
  6354. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6355. var index;
  6356. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6357. renderSubMesh(opaqueSubMeshes.data[index]);
  6358. }
  6359. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6360. renderSubMesh(alphaTestSubMeshes.data[index]);
  6361. }
  6362. if (_this._transparencyShadow) {
  6363. for (index = 0; index < transparentSubMeshes.length; index++) {
  6364. renderSubMesh(transparentSubMeshes.data[index]);
  6365. }
  6366. }
  6367. };
  6368. this._shadowMap.onClear = function (engine) {
  6369. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6370. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6371. }
  6372. else {
  6373. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6374. }
  6375. };
  6376. }
  6377. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6378. // Static
  6379. get: function () {
  6380. return ShadowGenerator._FILTER_NONE;
  6381. },
  6382. enumerable: true,
  6383. configurable: true
  6384. });
  6385. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6386. get: function () {
  6387. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6388. },
  6389. enumerable: true,
  6390. configurable: true
  6391. });
  6392. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6393. get: function () {
  6394. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6395. },
  6396. enumerable: true,
  6397. configurable: true
  6398. });
  6399. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6400. get: function () {
  6401. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6402. },
  6403. enumerable: true,
  6404. configurable: true
  6405. });
  6406. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6407. get: function () {
  6408. return this._bias;
  6409. },
  6410. set: function (bias) {
  6411. this._bias = bias;
  6412. },
  6413. enumerable: true,
  6414. configurable: true
  6415. });
  6416. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6417. get: function () {
  6418. return this._blurBoxOffset;
  6419. },
  6420. set: function (value) {
  6421. var _this = this;
  6422. if (this._blurBoxOffset === value) {
  6423. return;
  6424. }
  6425. this._blurBoxOffset = value;
  6426. if (this._boxBlurPostprocess) {
  6427. this._boxBlurPostprocess.dispose();
  6428. }
  6429. 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);
  6430. this._boxBlurPostprocess.onApply = function (effect) {
  6431. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6432. };
  6433. },
  6434. enumerable: true,
  6435. configurable: true
  6436. });
  6437. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6438. get: function () {
  6439. return this._filter;
  6440. },
  6441. set: function (value) {
  6442. if (this._filter === value) {
  6443. return;
  6444. }
  6445. this._filter = value;
  6446. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6447. this._shadowMap.anisotropicFilteringLevel = 16;
  6448. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6449. }
  6450. else {
  6451. this._shadowMap.anisotropicFilteringLevel = 1;
  6452. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6453. }
  6454. },
  6455. enumerable: true,
  6456. configurable: true
  6457. });
  6458. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6459. get: function () {
  6460. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6461. },
  6462. set: function (value) {
  6463. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6464. },
  6465. enumerable: true,
  6466. configurable: true
  6467. });
  6468. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6469. get: function () {
  6470. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6471. },
  6472. set: function (value) {
  6473. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6474. },
  6475. enumerable: true,
  6476. configurable: true
  6477. });
  6478. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6479. get: function () {
  6480. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6481. },
  6482. set: function (value) {
  6483. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6484. },
  6485. enumerable: true,
  6486. configurable: true
  6487. });
  6488. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6489. var defines = [];
  6490. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6491. defines.push("#define VSM");
  6492. }
  6493. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6494. var mesh = subMesh.getMesh();
  6495. var material = subMesh.getMaterial();
  6496. // Alpha test
  6497. if (material && material.needAlphaTesting()) {
  6498. defines.push("#define ALPHATEST");
  6499. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6500. attribs.push(BABYLON.VertexBuffer.UVKind);
  6501. defines.push("#define UV1");
  6502. }
  6503. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6504. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6505. defines.push("#define UV2");
  6506. }
  6507. }
  6508. // Bones
  6509. if (mesh.useBones) {
  6510. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6511. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6512. defines.push("#define BONES");
  6513. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6514. }
  6515. // Instances
  6516. if (useInstances) {
  6517. defines.push("#define INSTANCES");
  6518. attribs.push("world0");
  6519. attribs.push("world1");
  6520. attribs.push("world2");
  6521. attribs.push("world3");
  6522. }
  6523. // Get correct effect
  6524. var join = defines.join("\n");
  6525. if (this._cachedDefines !== join) {
  6526. this._cachedDefines = join;
  6527. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6528. }
  6529. return this._effect.isReady();
  6530. };
  6531. ShadowGenerator.prototype.getShadowMap = function () {
  6532. return this._shadowMap;
  6533. };
  6534. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6535. if (this._shadowMap2) {
  6536. return this._shadowMap2;
  6537. }
  6538. return this._shadowMap;
  6539. };
  6540. ShadowGenerator.prototype.getLight = function () {
  6541. return this._light;
  6542. };
  6543. // Methods
  6544. ShadowGenerator.prototype.getTransformMatrix = function () {
  6545. var scene = this._scene;
  6546. if (this._currentRenderID === scene.getRenderId()) {
  6547. return this._transformMatrix;
  6548. }
  6549. this._currentRenderID = scene.getRenderId();
  6550. var lightPosition = this._light.position;
  6551. var lightDirection = this._light.direction;
  6552. if (this._light.computeTransformedPosition()) {
  6553. lightPosition = this._light.transformedPosition;
  6554. }
  6555. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6556. this._cachedPosition = lightPosition.clone();
  6557. this._cachedDirection = lightDirection.clone();
  6558. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6559. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6560. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6561. }
  6562. return this._transformMatrix;
  6563. };
  6564. ShadowGenerator.prototype.getDarkness = function () {
  6565. return this._darkness;
  6566. };
  6567. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6568. if (darkness >= 1.0)
  6569. this._darkness = 1.0;
  6570. else if (darkness <= 0.0)
  6571. this._darkness = 0.0;
  6572. else
  6573. this._darkness = darkness;
  6574. };
  6575. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6576. this._transparencyShadow = hasShadow;
  6577. };
  6578. ShadowGenerator.prototype._packHalf = function (depth) {
  6579. var scale = depth * 255.0;
  6580. var fract = scale - Math.floor(scale);
  6581. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6582. };
  6583. ShadowGenerator.prototype.dispose = function () {
  6584. this._shadowMap.dispose();
  6585. if (this._shadowMap2) {
  6586. this._shadowMap2.dispose();
  6587. }
  6588. if (this._downSamplePostprocess) {
  6589. this._downSamplePostprocess.dispose();
  6590. }
  6591. if (this._boxBlurPostprocess) {
  6592. this._boxBlurPostprocess.dispose();
  6593. }
  6594. };
  6595. ShadowGenerator._FILTER_NONE = 0;
  6596. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6597. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6598. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6599. return ShadowGenerator;
  6600. })();
  6601. BABYLON.ShadowGenerator = ShadowGenerator;
  6602. })(BABYLON || (BABYLON = {}));
  6603. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6604. var BABYLON;
  6605. (function (BABYLON) {
  6606. var HemisphericLight = (function (_super) {
  6607. __extends(HemisphericLight, _super);
  6608. function HemisphericLight(name, direction, scene) {
  6609. _super.call(this, name, scene);
  6610. this.direction = direction;
  6611. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6612. }
  6613. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6614. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6615. return this.direction;
  6616. };
  6617. HemisphericLight.prototype.getShadowGenerator = function () {
  6618. return null;
  6619. };
  6620. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6621. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6622. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6623. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6624. };
  6625. HemisphericLight.prototype._getWorldMatrix = function () {
  6626. if (!this._worldMatrix) {
  6627. this._worldMatrix = BABYLON.Matrix.Identity();
  6628. }
  6629. return this._worldMatrix;
  6630. };
  6631. return HemisphericLight;
  6632. })(BABYLON.Light);
  6633. BABYLON.HemisphericLight = HemisphericLight;
  6634. })(BABYLON || (BABYLON = {}));
  6635. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6636. (function (BABYLON) {
  6637. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6638. if (boxMin.x > sphereCenter.x + sphereRadius)
  6639. return false;
  6640. if (sphereCenter.x - sphereRadius > boxMax.x)
  6641. return false;
  6642. if (boxMin.y > sphereCenter.y + sphereRadius)
  6643. return false;
  6644. if (sphereCenter.y - sphereRadius > boxMax.y)
  6645. return false;
  6646. if (boxMin.z > sphereCenter.z + sphereRadius)
  6647. return false;
  6648. if (sphereCenter.z - sphereRadius > boxMax.z)
  6649. return false;
  6650. return true;
  6651. };
  6652. var getLowestRoot = function (a, b, c, maxR) {
  6653. var determinant = b * b - 4.0 * a * c;
  6654. var result = { root: 0, found: false };
  6655. if (determinant < 0)
  6656. return result;
  6657. var sqrtD = Math.sqrt(determinant);
  6658. var r1 = (-b - sqrtD) / (2.0 * a);
  6659. var r2 = (-b + sqrtD) / (2.0 * a);
  6660. if (r1 > r2) {
  6661. var temp = r2;
  6662. r2 = r1;
  6663. r1 = temp;
  6664. }
  6665. if (r1 > 0 && r1 < maxR) {
  6666. result.root = r1;
  6667. result.found = true;
  6668. return result;
  6669. }
  6670. if (r2 > 0 && r2 < maxR) {
  6671. result.root = r2;
  6672. result.found = true;
  6673. return result;
  6674. }
  6675. return result;
  6676. };
  6677. var Collider = (function () {
  6678. function Collider() {
  6679. this.radius = new BABYLON.Vector3(1, 1, 1);
  6680. this.retry = 0;
  6681. this.basePointWorld = BABYLON.Vector3.Zero();
  6682. this.velocityWorld = BABYLON.Vector3.Zero();
  6683. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6684. this._collisionPoint = BABYLON.Vector3.Zero();
  6685. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6686. this._tempVector = BABYLON.Vector3.Zero();
  6687. this._tempVector2 = BABYLON.Vector3.Zero();
  6688. this._tempVector3 = BABYLON.Vector3.Zero();
  6689. this._tempVector4 = BABYLON.Vector3.Zero();
  6690. this._edge = BABYLON.Vector3.Zero();
  6691. this._baseToVertex = BABYLON.Vector3.Zero();
  6692. this._destinationPoint = BABYLON.Vector3.Zero();
  6693. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6694. this._displacementVector = BABYLON.Vector3.Zero();
  6695. }
  6696. // Methods
  6697. Collider.prototype._initialize = function (source, dir, e) {
  6698. this.velocity = dir;
  6699. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6700. this.basePoint = source;
  6701. source.multiplyToRef(this.radius, this.basePointWorld);
  6702. dir.multiplyToRef(this.radius, this.velocityWorld);
  6703. this.velocityWorldLength = this.velocityWorld.length();
  6704. this.epsilon = e;
  6705. this.collisionFound = false;
  6706. };
  6707. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6708. pa.subtractToRef(point, this._tempVector);
  6709. pb.subtractToRef(point, this._tempVector2);
  6710. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6711. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6712. if (d < 0)
  6713. return false;
  6714. pc.subtractToRef(point, this._tempVector3);
  6715. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6716. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6717. if (d < 0)
  6718. return false;
  6719. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6720. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6721. return d >= 0;
  6722. };
  6723. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6724. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6725. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6726. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6727. return false;
  6728. }
  6729. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6730. return false;
  6731. return true;
  6732. };
  6733. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6734. var t0;
  6735. var embeddedInPlane = false;
  6736. if (!subMesh._trianglePlanes) {
  6737. subMesh._trianglePlanes = [];
  6738. }
  6739. if (!subMesh._trianglePlanes[faceIndex]) {
  6740. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6741. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6742. }
  6743. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6744. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6745. return;
  6746. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6747. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6748. if (normalDotVelocity == 0) {
  6749. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6750. return;
  6751. embeddedInPlane = true;
  6752. t0 = 0;
  6753. }
  6754. else {
  6755. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6756. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6757. if (t0 > t1) {
  6758. var temp = t1;
  6759. t1 = t0;
  6760. t0 = temp;
  6761. }
  6762. if (t0 > 1.0 || t1 < 0.0)
  6763. return;
  6764. if (t0 < 0)
  6765. t0 = 0;
  6766. if (t0 > 1.0)
  6767. t0 = 1.0;
  6768. }
  6769. this._collisionPoint.copyFromFloats(0, 0, 0);
  6770. var found = false;
  6771. var t = 1.0;
  6772. if (!embeddedInPlane) {
  6773. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6774. this.velocity.scaleToRef(t0, this._tempVector);
  6775. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6776. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6777. found = true;
  6778. t = t0;
  6779. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6780. }
  6781. }
  6782. if (!found) {
  6783. var velocitySquaredLength = this.velocity.lengthSquared();
  6784. var a = velocitySquaredLength;
  6785. this.basePoint.subtractToRef(p1, this._tempVector);
  6786. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6787. var c = this._tempVector.lengthSquared() - 1.0;
  6788. var lowestRoot = getLowestRoot(a, b, c, t);
  6789. if (lowestRoot.found) {
  6790. t = lowestRoot.root;
  6791. found = true;
  6792. this._collisionPoint.copyFrom(p1);
  6793. }
  6794. this.basePoint.subtractToRef(p2, this._tempVector);
  6795. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6796. c = this._tempVector.lengthSquared() - 1.0;
  6797. lowestRoot = getLowestRoot(a, b, c, t);
  6798. if (lowestRoot.found) {
  6799. t = lowestRoot.root;
  6800. found = true;
  6801. this._collisionPoint.copyFrom(p2);
  6802. }
  6803. this.basePoint.subtractToRef(p3, this._tempVector);
  6804. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6805. c = this._tempVector.lengthSquared() - 1.0;
  6806. lowestRoot = getLowestRoot(a, b, c, t);
  6807. if (lowestRoot.found) {
  6808. t = lowestRoot.root;
  6809. found = true;
  6810. this._collisionPoint.copyFrom(p3);
  6811. }
  6812. p2.subtractToRef(p1, this._edge);
  6813. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6814. var edgeSquaredLength = this._edge.lengthSquared();
  6815. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6816. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6817. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6818. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6819. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6820. lowestRoot = getLowestRoot(a, b, c, t);
  6821. if (lowestRoot.found) {
  6822. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6823. if (f >= 0.0 && f <= 1.0) {
  6824. t = lowestRoot.root;
  6825. found = true;
  6826. this._edge.scaleInPlace(f);
  6827. p1.addToRef(this._edge, this._collisionPoint);
  6828. }
  6829. }
  6830. p3.subtractToRef(p2, this._edge);
  6831. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6832. edgeSquaredLength = this._edge.lengthSquared();
  6833. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6834. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6835. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6836. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6837. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6838. lowestRoot = getLowestRoot(a, b, c, t);
  6839. if (lowestRoot.found) {
  6840. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6841. if (f >= 0.0 && f <= 1.0) {
  6842. t = lowestRoot.root;
  6843. found = true;
  6844. this._edge.scaleInPlace(f);
  6845. p2.addToRef(this._edge, this._collisionPoint);
  6846. }
  6847. }
  6848. p1.subtractToRef(p3, this._edge);
  6849. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6850. edgeSquaredLength = this._edge.lengthSquared();
  6851. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6852. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6853. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6854. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6855. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6856. lowestRoot = getLowestRoot(a, b, c, t);
  6857. if (lowestRoot.found) {
  6858. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6859. if (f >= 0.0 && f <= 1.0) {
  6860. t = lowestRoot.root;
  6861. found = true;
  6862. this._edge.scaleInPlace(f);
  6863. p3.addToRef(this._edge, this._collisionPoint);
  6864. }
  6865. }
  6866. }
  6867. if (found) {
  6868. var distToCollision = t * this.velocity.length();
  6869. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6870. if (!this.intersectionPoint) {
  6871. this.intersectionPoint = this._collisionPoint.clone();
  6872. }
  6873. else {
  6874. this.intersectionPoint.copyFrom(this._collisionPoint);
  6875. }
  6876. this.nearestDistance = distToCollision;
  6877. this.collisionFound = true;
  6878. this.collidedMesh = subMesh.getMesh();
  6879. }
  6880. }
  6881. };
  6882. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6883. for (var i = indexStart; i < indexEnd; i += 3) {
  6884. var p1 = pts[indices[i] - decal];
  6885. var p2 = pts[indices[i + 1] - decal];
  6886. var p3 = pts[indices[i + 2] - decal];
  6887. this._testTriangle(i, subMesh, p3, p2, p1);
  6888. }
  6889. };
  6890. Collider.prototype._getResponse = function (pos, vel) {
  6891. pos.addToRef(vel, this._destinationPoint);
  6892. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6893. this.basePoint.addToRef(vel, pos);
  6894. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6895. this._slidePlaneNormal.normalize();
  6896. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6897. pos.addInPlace(this._displacementVector);
  6898. this.intersectionPoint.addInPlace(this._displacementVector);
  6899. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6900. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6901. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6902. };
  6903. return Collider;
  6904. })();
  6905. BABYLON.Collider = Collider;
  6906. })(BABYLON || (BABYLON = {}));
  6907. //# sourceMappingURL=babylon.collider.js.map
  6908. var BABYLON;
  6909. (function (BABYLON) {
  6910. var Camera = (function (_super) {
  6911. __extends(Camera, _super);
  6912. function Camera(name, position, scene) {
  6913. _super.call(this, name, scene);
  6914. this.position = position;
  6915. // Members
  6916. this.upVector = BABYLON.Vector3.Up();
  6917. this.orthoLeft = null;
  6918. this.orthoRight = null;
  6919. this.orthoBottom = null;
  6920. this.orthoTop = null;
  6921. this.fov = 0.8;
  6922. this.minZ = 1.0;
  6923. this.maxZ = 10000.0;
  6924. this.inertia = 0.9;
  6925. this.mode = Camera.PERSPECTIVE_CAMERA;
  6926. this.isIntermediate = false;
  6927. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6928. this.subCameras = [];
  6929. this.layerMask = 0xFFFFFFFF;
  6930. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6931. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6932. this._projectionMatrix = new BABYLON.Matrix();
  6933. this._postProcesses = new Array();
  6934. this._postProcessesTakenIndices = [];
  6935. this._activeMeshes = new BABYLON.SmartArray(256);
  6936. this._globalPosition = BABYLON.Vector3.Zero();
  6937. scene.addCamera(this);
  6938. if (!scene.activeCamera) {
  6939. scene.activeCamera = this;
  6940. }
  6941. }
  6942. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6943. get: function () {
  6944. return Camera._PERSPECTIVE_CAMERA;
  6945. },
  6946. enumerable: true,
  6947. configurable: true
  6948. });
  6949. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6950. get: function () {
  6951. return Camera._ORTHOGRAPHIC_CAMERA;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6957. get: function () {
  6958. return Camera._FOVMODE_VERTICAL_FIXED;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6964. get: function () {
  6965. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Camera.prototype, "globalPosition", {
  6971. get: function () {
  6972. return this._globalPosition;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Camera.prototype.getActiveMeshes = function () {
  6978. return this._activeMeshes;
  6979. };
  6980. Camera.prototype.isActiveMesh = function (mesh) {
  6981. return (this._activeMeshes.indexOf(mesh) !== -1);
  6982. };
  6983. //Cache
  6984. Camera.prototype._initCache = function () {
  6985. _super.prototype._initCache.call(this);
  6986. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6987. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6988. this._cache.mode = undefined;
  6989. this._cache.minZ = undefined;
  6990. this._cache.maxZ = undefined;
  6991. this._cache.fov = undefined;
  6992. this._cache.aspectRatio = undefined;
  6993. this._cache.orthoLeft = undefined;
  6994. this._cache.orthoRight = undefined;
  6995. this._cache.orthoBottom = undefined;
  6996. this._cache.orthoTop = undefined;
  6997. this._cache.renderWidth = undefined;
  6998. this._cache.renderHeight = undefined;
  6999. };
  7000. Camera.prototype._updateCache = function (ignoreParentClass) {
  7001. if (!ignoreParentClass) {
  7002. _super.prototype._updateCache.call(this);
  7003. }
  7004. var engine = this.getEngine();
  7005. this._cache.position.copyFrom(this.position);
  7006. this._cache.upVector.copyFrom(this.upVector);
  7007. this._cache.mode = this.mode;
  7008. this._cache.minZ = this.minZ;
  7009. this._cache.maxZ = this.maxZ;
  7010. this._cache.fov = this.fov;
  7011. this._cache.aspectRatio = engine.getAspectRatio(this);
  7012. this._cache.orthoLeft = this.orthoLeft;
  7013. this._cache.orthoRight = this.orthoRight;
  7014. this._cache.orthoBottom = this.orthoBottom;
  7015. this._cache.orthoTop = this.orthoTop;
  7016. this._cache.renderWidth = engine.getRenderWidth();
  7017. this._cache.renderHeight = engine.getRenderHeight();
  7018. };
  7019. Camera.prototype._updateFromScene = function () {
  7020. this.updateCache();
  7021. this._update();
  7022. };
  7023. // Synchronized
  7024. Camera.prototype.isSynchronizedWithParent = function () {
  7025. return false;
  7026. };
  7027. Camera.prototype._isSynchronized = function () {
  7028. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7029. };
  7030. Camera.prototype._isSynchronizedViewMatrix = function () {
  7031. if (!_super.prototype._isSynchronized.call(this))
  7032. return false;
  7033. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7034. };
  7035. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7036. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7037. if (!check) {
  7038. return false;
  7039. }
  7040. var engine = this.getEngine();
  7041. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7042. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7043. }
  7044. else {
  7045. 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();
  7046. }
  7047. return check;
  7048. };
  7049. // Controls
  7050. Camera.prototype.attachControl = function (element) {
  7051. };
  7052. Camera.prototype.detachControl = function (element) {
  7053. };
  7054. Camera.prototype._update = function () {
  7055. };
  7056. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7057. if (insertAt === void 0) { insertAt = null; }
  7058. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7059. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7060. return 0;
  7061. }
  7062. if (insertAt == null || insertAt < 0) {
  7063. this._postProcesses.push(postProcess);
  7064. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7065. return this._postProcesses.length - 1;
  7066. }
  7067. var add = 0;
  7068. if (this._postProcesses[insertAt]) {
  7069. var start = this._postProcesses.length - 1;
  7070. for (var i = start; i >= insertAt + 1; --i) {
  7071. this._postProcesses[i + 1] = this._postProcesses[i];
  7072. }
  7073. add = 1;
  7074. }
  7075. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7076. if (this._postProcessesTakenIndices[i] < insertAt) {
  7077. continue;
  7078. }
  7079. start = this._postProcessesTakenIndices.length - 1;
  7080. for (var j = start; j >= i; --j) {
  7081. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7082. }
  7083. this._postProcessesTakenIndices[i] = insertAt;
  7084. break;
  7085. }
  7086. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7087. this._postProcessesTakenIndices.push(insertAt);
  7088. }
  7089. var result = insertAt + add;
  7090. this._postProcesses[result] = postProcess;
  7091. return result;
  7092. };
  7093. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7094. if (atIndices === void 0) { atIndices = null; }
  7095. var result = [];
  7096. if (!atIndices) {
  7097. var length = this._postProcesses.length;
  7098. for (var i = 0; i < length; i++) {
  7099. if (this._postProcesses[i] !== postProcess) {
  7100. continue;
  7101. }
  7102. delete this._postProcesses[i];
  7103. var index = this._postProcessesTakenIndices.indexOf(i);
  7104. this._postProcessesTakenIndices.splice(index, 1);
  7105. }
  7106. }
  7107. else {
  7108. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7109. for (i = 0; i < atIndices.length; i++) {
  7110. var foundPostProcess = this._postProcesses[atIndices[i]];
  7111. if (foundPostProcess !== postProcess) {
  7112. result.push(i);
  7113. continue;
  7114. }
  7115. delete this._postProcesses[atIndices[i]];
  7116. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7117. this._postProcessesTakenIndices.splice(index, 1);
  7118. }
  7119. }
  7120. return result;
  7121. };
  7122. Camera.prototype.getWorldMatrix = function () {
  7123. if (!this._worldMatrix) {
  7124. this._worldMatrix = BABYLON.Matrix.Identity();
  7125. }
  7126. var viewMatrix = this.getViewMatrix();
  7127. viewMatrix.invertToRef(this._worldMatrix);
  7128. return this._worldMatrix;
  7129. };
  7130. Camera.prototype._getViewMatrix = function () {
  7131. return BABYLON.Matrix.Identity();
  7132. };
  7133. Camera.prototype.getViewMatrix = function () {
  7134. this._computedViewMatrix = this._computeViewMatrix();
  7135. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7136. this._globalPosition.copyFrom(this.position);
  7137. return this._computedViewMatrix;
  7138. }
  7139. if (!this._worldMatrix) {
  7140. this._worldMatrix = BABYLON.Matrix.Identity();
  7141. }
  7142. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7143. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7144. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7145. this._computedViewMatrix.invert();
  7146. this._currentRenderId = this.getScene().getRenderId();
  7147. return this._computedViewMatrix;
  7148. };
  7149. Camera.prototype._computeViewMatrix = function (force) {
  7150. if (!force && this._isSynchronizedViewMatrix()) {
  7151. return this._computedViewMatrix;
  7152. }
  7153. this._computedViewMatrix = this._getViewMatrix();
  7154. // if (!this.parent || !this.parent.getWorldMatrix) {
  7155. this._currentRenderId = this.getScene().getRenderId();
  7156. //}
  7157. return this._computedViewMatrix;
  7158. };
  7159. Camera.prototype.getProjectionMatrix = function (force) {
  7160. if (!force && this._isSynchronizedProjectionMatrix()) {
  7161. return this._projectionMatrix;
  7162. }
  7163. var engine = this.getEngine();
  7164. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7165. if (this.minZ <= 0) {
  7166. this.minZ = 0.1;
  7167. }
  7168. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7169. return this._projectionMatrix;
  7170. }
  7171. var halfWidth = engine.getRenderWidth() / 2.0;
  7172. var halfHeight = engine.getRenderHeight() / 2.0;
  7173. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7174. return this._projectionMatrix;
  7175. };
  7176. Camera.prototype.dispose = function () {
  7177. // Remove from scene
  7178. this.getScene().removeCamera(this);
  7179. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7180. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7181. }
  7182. };
  7183. // Statics
  7184. Camera._PERSPECTIVE_CAMERA = 0;
  7185. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7186. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7187. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7188. return Camera;
  7189. })(BABYLON.Node);
  7190. BABYLON.Camera = Camera;
  7191. })(BABYLON || (BABYLON = {}));
  7192. //# sourceMappingURL=babylon.camera.js.map
  7193. var BABYLON;
  7194. (function (BABYLON) {
  7195. var TargetCamera = (function (_super) {
  7196. __extends(TargetCamera, _super);
  7197. function TargetCamera(name, position, scene) {
  7198. _super.call(this, name, position, scene);
  7199. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7200. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7201. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7202. this.speed = 2.0;
  7203. this.noRotationConstraint = false;
  7204. this.lockedTarget = null;
  7205. this._currentTarget = BABYLON.Vector3.Zero();
  7206. this._viewMatrix = BABYLON.Matrix.Zero();
  7207. this._camMatrix = BABYLON.Matrix.Zero();
  7208. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7209. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7210. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7211. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7212. this._lookAtTemp = BABYLON.Matrix.Zero();
  7213. this._tempMatrix = BABYLON.Matrix.Zero();
  7214. }
  7215. TargetCamera.prototype._getLockedTargetPosition = function () {
  7216. if (!this.lockedTarget) {
  7217. return null;
  7218. }
  7219. return this.lockedTarget.position || this.lockedTarget;
  7220. };
  7221. // Cache
  7222. TargetCamera.prototype._initCache = function () {
  7223. _super.prototype._initCache.call(this);
  7224. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7225. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7226. };
  7227. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7228. if (!ignoreParentClass) {
  7229. _super.prototype._updateCache.call(this);
  7230. }
  7231. var lockedTargetPosition = this._getLockedTargetPosition();
  7232. if (!lockedTargetPosition) {
  7233. this._cache.lockedTarget = null;
  7234. }
  7235. else {
  7236. if (!this._cache.lockedTarget) {
  7237. this._cache.lockedTarget = lockedTargetPosition.clone();
  7238. }
  7239. else {
  7240. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7241. }
  7242. }
  7243. this._cache.rotation.copyFrom(this.rotation);
  7244. };
  7245. // Synchronized
  7246. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7247. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7248. return false;
  7249. }
  7250. var lockedTargetPosition = this._getLockedTargetPosition();
  7251. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7252. };
  7253. // Methods
  7254. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7255. var engine = this.getEngine();
  7256. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7257. };
  7258. // Target
  7259. TargetCamera.prototype.setTarget = function (target) {
  7260. this.upVector.normalize();
  7261. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7262. this._camMatrix.invert();
  7263. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7264. var vDir = target.subtract(this.position);
  7265. if (vDir.x >= 0.0) {
  7266. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7267. }
  7268. else {
  7269. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7270. }
  7271. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7272. if (isNaN(this.rotation.x)) {
  7273. this.rotation.x = 0;
  7274. }
  7275. if (isNaN(this.rotation.y)) {
  7276. this.rotation.y = 0;
  7277. }
  7278. if (isNaN(this.rotation.z)) {
  7279. this.rotation.z = 0;
  7280. }
  7281. };
  7282. TargetCamera.prototype.getTarget = function () {
  7283. return this._currentTarget;
  7284. };
  7285. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7286. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7287. };
  7288. TargetCamera.prototype._updatePosition = function () {
  7289. this.position.addInPlace(this.cameraDirection);
  7290. };
  7291. TargetCamera.prototype._update = function () {
  7292. var needToMove = this._decideIfNeedsToMove();
  7293. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7294. // Move
  7295. if (needToMove) {
  7296. this._updatePosition();
  7297. }
  7298. // Rotate
  7299. if (needToRotate) {
  7300. this.rotation.x += this.cameraRotation.x;
  7301. this.rotation.y += this.cameraRotation.y;
  7302. if (!this.noRotationConstraint) {
  7303. var limit = (Math.PI / 2) * 0.95;
  7304. if (this.rotation.x > limit)
  7305. this.rotation.x = limit;
  7306. if (this.rotation.x < -limit)
  7307. this.rotation.x = -limit;
  7308. }
  7309. }
  7310. // Inertia
  7311. if (needToMove) {
  7312. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7313. this.cameraDirection.x = 0;
  7314. }
  7315. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7316. this.cameraDirection.y = 0;
  7317. }
  7318. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7319. this.cameraDirection.z = 0;
  7320. }
  7321. this.cameraDirection.scaleInPlace(this.inertia);
  7322. }
  7323. if (needToRotate) {
  7324. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7325. this.cameraRotation.x = 0;
  7326. }
  7327. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7328. this.cameraRotation.y = 0;
  7329. }
  7330. this.cameraRotation.scaleInPlace(this.inertia);
  7331. }
  7332. };
  7333. TargetCamera.prototype._getViewMatrix = function () {
  7334. if (!this.lockedTarget) {
  7335. // Compute
  7336. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7337. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7338. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7339. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7340. this._lookAtTemp.invert();
  7341. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7342. }
  7343. else {
  7344. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7345. }
  7346. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7347. // Computing target and final matrix
  7348. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7349. }
  7350. else {
  7351. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7352. }
  7353. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7354. return this._viewMatrix;
  7355. };
  7356. return TargetCamera;
  7357. })(BABYLON.Camera);
  7358. BABYLON.TargetCamera = TargetCamera;
  7359. })(BABYLON || (BABYLON = {}));
  7360. //# sourceMappingURL=babylon.targetCamera.js.map
  7361. var BABYLON;
  7362. (function (BABYLON) {
  7363. var FollowCamera = (function (_super) {
  7364. __extends(FollowCamera, _super);
  7365. function FollowCamera(name, position, scene) {
  7366. _super.call(this, name, position, scene);
  7367. this.radius = 12;
  7368. this.rotationOffset = 0;
  7369. this.heightOffset = 4;
  7370. this.cameraAcceleration = 0.05;
  7371. this.maxCameraSpeed = 20;
  7372. }
  7373. FollowCamera.prototype.getRadians = function (degrees) {
  7374. return degrees * Math.PI / 180;
  7375. };
  7376. FollowCamera.prototype.follow = function (cameraTarget) {
  7377. if (!cameraTarget)
  7378. return;
  7379. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7380. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7381. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7382. var dx = targetX - this.position.x;
  7383. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7384. var dz = (targetZ) - this.position.z;
  7385. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7386. var vy = dy * this.cameraAcceleration;
  7387. var vz = dz * this.cameraAcceleration * 2;
  7388. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7389. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7390. }
  7391. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7392. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7393. }
  7394. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7395. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7396. }
  7397. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7398. this.setTarget(cameraTarget.position);
  7399. };
  7400. FollowCamera.prototype._update = function () {
  7401. _super.prototype._update.call(this);
  7402. this.follow(this.target);
  7403. };
  7404. return FollowCamera;
  7405. })(BABYLON.TargetCamera);
  7406. BABYLON.FollowCamera = FollowCamera;
  7407. })(BABYLON || (BABYLON = {}));
  7408. //# sourceMappingURL=babylon.followCamera.js.map
  7409. var BABYLON;
  7410. (function (BABYLON) {
  7411. var FreeCamera = (function (_super) {
  7412. __extends(FreeCamera, _super);
  7413. function FreeCamera(name, position, scene) {
  7414. _super.call(this, name, position, scene);
  7415. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7416. this.keysUp = [38];
  7417. this.keysDown = [40];
  7418. this.keysLeft = [37];
  7419. this.keysRight = [39];
  7420. this.checkCollisions = false;
  7421. this.applyGravity = false;
  7422. this.angularSensibility = 2000.0;
  7423. this._keys = [];
  7424. this._collider = new BABYLON.Collider();
  7425. this._needMoveForGravity = true;
  7426. this._oldPosition = BABYLON.Vector3.Zero();
  7427. this._diffPosition = BABYLON.Vector3.Zero();
  7428. this._newPosition = BABYLON.Vector3.Zero();
  7429. }
  7430. // Controls
  7431. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7432. var _this = this;
  7433. var previousPosition;
  7434. var engine = this.getEngine();
  7435. if (this._attachedElement) {
  7436. return;
  7437. }
  7438. this._attachedElement = element;
  7439. if (this._onMouseDown === undefined) {
  7440. this._onMouseDown = function (evt) {
  7441. previousPosition = {
  7442. x: evt.clientX,
  7443. y: evt.clientY
  7444. };
  7445. if (!noPreventDefault) {
  7446. evt.preventDefault();
  7447. }
  7448. };
  7449. this._onMouseUp = function (evt) {
  7450. previousPosition = null;
  7451. if (!noPreventDefault) {
  7452. evt.preventDefault();
  7453. }
  7454. };
  7455. this._onMouseOut = function (evt) {
  7456. previousPosition = null;
  7457. _this._keys = [];
  7458. if (!noPreventDefault) {
  7459. evt.preventDefault();
  7460. }
  7461. };
  7462. this._onMouseMove = function (evt) {
  7463. if (!previousPosition && !engine.isPointerLock) {
  7464. return;
  7465. }
  7466. var offsetX;
  7467. var offsetY;
  7468. if (!engine.isPointerLock) {
  7469. offsetX = evt.clientX - previousPosition.x;
  7470. offsetY = evt.clientY - previousPosition.y;
  7471. }
  7472. else {
  7473. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7474. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7475. }
  7476. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7477. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7478. previousPosition = {
  7479. x: evt.clientX,
  7480. y: evt.clientY
  7481. };
  7482. if (!noPreventDefault) {
  7483. evt.preventDefault();
  7484. }
  7485. };
  7486. this._onKeyDown = function (evt) {
  7487. 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) {
  7488. var index = _this._keys.indexOf(evt.keyCode);
  7489. if (index === -1) {
  7490. _this._keys.push(evt.keyCode);
  7491. }
  7492. if (!noPreventDefault) {
  7493. evt.preventDefault();
  7494. }
  7495. }
  7496. };
  7497. this._onKeyUp = function (evt) {
  7498. 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) {
  7499. var index = _this._keys.indexOf(evt.keyCode);
  7500. if (index >= 0) {
  7501. _this._keys.splice(index, 1);
  7502. }
  7503. if (!noPreventDefault) {
  7504. evt.preventDefault();
  7505. }
  7506. }
  7507. };
  7508. this._onLostFocus = function () {
  7509. _this._keys = [];
  7510. };
  7511. this._reset = function () {
  7512. _this._keys = [];
  7513. previousPosition = null;
  7514. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7515. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7516. };
  7517. }
  7518. element.addEventListener("mousedown", this._onMouseDown, false);
  7519. element.addEventListener("mouseup", this._onMouseUp, false);
  7520. element.addEventListener("mouseout", this._onMouseOut, false);
  7521. element.addEventListener("mousemove", this._onMouseMove, false);
  7522. BABYLON.Tools.RegisterTopRootEvents([
  7523. { name: "keydown", handler: this._onKeyDown },
  7524. { name: "keyup", handler: this._onKeyUp },
  7525. { name: "blur", handler: this._onLostFocus }
  7526. ]);
  7527. };
  7528. FreeCamera.prototype.detachControl = function (element) {
  7529. if (this._attachedElement != element) {
  7530. return;
  7531. }
  7532. element.removeEventListener("mousedown", this._onMouseDown);
  7533. element.removeEventListener("mouseup", this._onMouseUp);
  7534. element.removeEventListener("mouseout", this._onMouseOut);
  7535. element.removeEventListener("mousemove", this._onMouseMove);
  7536. BABYLON.Tools.UnregisterTopRootEvents([
  7537. { name: "keydown", handler: this._onKeyDown },
  7538. { name: "keyup", handler: this._onKeyUp },
  7539. { name: "blur", handler: this._onLostFocus }
  7540. ]);
  7541. this._attachedElement = null;
  7542. if (this._reset) {
  7543. this._reset();
  7544. }
  7545. };
  7546. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7547. var globalPosition;
  7548. if (this.parent) {
  7549. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7550. }
  7551. else {
  7552. globalPosition = this.position;
  7553. }
  7554. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7555. this._collider.radius = this.ellipsoid;
  7556. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7557. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7558. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7559. this.position.addInPlace(this._diffPosition);
  7560. if (this.onCollide) {
  7561. this.onCollide(this._collider.collidedMesh);
  7562. }
  7563. }
  7564. };
  7565. FreeCamera.prototype._checkInputs = function () {
  7566. if (!this._localDirection) {
  7567. this._localDirection = BABYLON.Vector3.Zero();
  7568. this._transformedDirection = BABYLON.Vector3.Zero();
  7569. }
  7570. for (var index = 0; index < this._keys.length; index++) {
  7571. var keyCode = this._keys[index];
  7572. var speed = this._computeLocalCameraSpeed();
  7573. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7574. this._localDirection.copyFromFloats(-speed, 0, 0);
  7575. }
  7576. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7577. this._localDirection.copyFromFloats(0, 0, speed);
  7578. }
  7579. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7580. this._localDirection.copyFromFloats(speed, 0, 0);
  7581. }
  7582. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7583. this._localDirection.copyFromFloats(0, 0, -speed);
  7584. }
  7585. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7586. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7587. this.cameraDirection.addInPlace(this._transformedDirection);
  7588. }
  7589. };
  7590. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7591. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7592. };
  7593. FreeCamera.prototype._updatePosition = function () {
  7594. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7595. this._collideWithWorld(this.cameraDirection);
  7596. if (this.applyGravity) {
  7597. var oldPosition = this.position;
  7598. this._collideWithWorld(this.getScene().gravity);
  7599. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7600. }
  7601. }
  7602. else {
  7603. this.position.addInPlace(this.cameraDirection);
  7604. }
  7605. };
  7606. FreeCamera.prototype._update = function () {
  7607. this._checkInputs();
  7608. _super.prototype._update.call(this);
  7609. };
  7610. return FreeCamera;
  7611. })(BABYLON.TargetCamera);
  7612. BABYLON.FreeCamera = FreeCamera;
  7613. })(BABYLON || (BABYLON = {}));
  7614. //# sourceMappingURL=babylon.freeCamera.js.map
  7615. var BABYLON;
  7616. (function (BABYLON) {
  7617. // We're mainly based on the logic defined into the FreeCamera code
  7618. var TouchCamera = (function (_super) {
  7619. __extends(TouchCamera, _super);
  7620. function TouchCamera(name, position, scene) {
  7621. _super.call(this, name, position, scene);
  7622. this._offsetX = null;
  7623. this._offsetY = null;
  7624. this._pointerCount = 0;
  7625. this._pointerPressed = [];
  7626. this.angularSensibility = 200000.0;
  7627. this.moveSensibility = 500.0;
  7628. }
  7629. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7630. var _this = this;
  7631. var previousPosition;
  7632. if (this._attachedCanvas) {
  7633. return;
  7634. }
  7635. this._attachedCanvas = canvas;
  7636. if (this._onPointerDown === undefined) {
  7637. this._onPointerDown = function (evt) {
  7638. if (!noPreventDefault) {
  7639. evt.preventDefault();
  7640. }
  7641. _this._pointerPressed.push(evt.pointerId);
  7642. if (_this._pointerPressed.length !== 1) {
  7643. return;
  7644. }
  7645. previousPosition = {
  7646. x: evt.clientX,
  7647. y: evt.clientY
  7648. };
  7649. };
  7650. this._onPointerUp = function (evt) {
  7651. if (!noPreventDefault) {
  7652. evt.preventDefault();
  7653. }
  7654. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7655. if (index === -1) {
  7656. return;
  7657. }
  7658. _this._pointerPressed.splice(index, 1);
  7659. if (index != 0) {
  7660. return;
  7661. }
  7662. previousPosition = null;
  7663. _this._offsetX = null;
  7664. _this._offsetY = null;
  7665. };
  7666. this._onPointerMove = function (evt) {
  7667. if (!noPreventDefault) {
  7668. evt.preventDefault();
  7669. }
  7670. if (!previousPosition) {
  7671. return;
  7672. }
  7673. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7674. if (index != 0) {
  7675. return;
  7676. }
  7677. _this._offsetX = evt.clientX - previousPosition.x;
  7678. _this._offsetY = -(evt.clientY - previousPosition.y);
  7679. };
  7680. this._onLostFocus = function () {
  7681. _this._offsetX = null;
  7682. _this._offsetY = null;
  7683. };
  7684. }
  7685. canvas.addEventListener("pointerdown", this._onPointerDown);
  7686. canvas.addEventListener("pointerup", this._onPointerUp);
  7687. canvas.addEventListener("pointerout", this._onPointerUp);
  7688. canvas.addEventListener("pointermove", this._onPointerMove);
  7689. BABYLON.Tools.RegisterTopRootEvents([
  7690. { name: "blur", handler: this._onLostFocus }
  7691. ]);
  7692. };
  7693. TouchCamera.prototype.detachControl = function (canvas) {
  7694. if (this._attachedCanvas != canvas) {
  7695. return;
  7696. }
  7697. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7698. canvas.removeEventListener("pointerup", this._onPointerUp);
  7699. canvas.removeEventListener("pointerout", this._onPointerUp);
  7700. canvas.removeEventListener("pointermove", this._onPointerMove);
  7701. BABYLON.Tools.UnregisterTopRootEvents([
  7702. { name: "blur", handler: this._onLostFocus }
  7703. ]);
  7704. this._attachedCanvas = null;
  7705. };
  7706. TouchCamera.prototype._checkInputs = function () {
  7707. if (!this._offsetX) {
  7708. return;
  7709. }
  7710. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7711. if (this._pointerPressed.length > 1) {
  7712. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7713. }
  7714. else {
  7715. var speed = this._computeLocalCameraSpeed();
  7716. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7717. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7718. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7719. }
  7720. };
  7721. return TouchCamera;
  7722. })(BABYLON.FreeCamera);
  7723. BABYLON.TouchCamera = TouchCamera;
  7724. })(BABYLON || (BABYLON = {}));
  7725. //# sourceMappingURL=babylon.touchCamera.js.map
  7726. var BABYLON;
  7727. (function (BABYLON) {
  7728. // We're mainly based on the logic defined into the FreeCamera code
  7729. var DeviceOrientationCamera = (function (_super) {
  7730. __extends(DeviceOrientationCamera, _super);
  7731. function DeviceOrientationCamera(name, position, scene) {
  7732. var _this = this;
  7733. _super.call(this, name, position, scene);
  7734. this._offsetX = null;
  7735. this._offsetY = null;
  7736. this._orientationGamma = 0;
  7737. this._orientationBeta = 0;
  7738. this._initialOrientationGamma = 0;
  7739. this._initialOrientationBeta = 0;
  7740. this.angularSensibility = 10000.0;
  7741. this.moveSensibility = 50.0;
  7742. window.addEventListener("resize", function () {
  7743. _this._initialOrientationGamma = null;
  7744. }, false);
  7745. }
  7746. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7747. var _this = this;
  7748. if (this._attachedCanvas) {
  7749. return;
  7750. }
  7751. this._attachedCanvas = canvas;
  7752. if (!this._orientationChanged) {
  7753. this._orientationChanged = function (evt) {
  7754. if (!_this._initialOrientationGamma) {
  7755. _this._initialOrientationGamma = evt.gamma;
  7756. _this._initialOrientationBeta = evt.beta;
  7757. }
  7758. _this._orientationGamma = evt.gamma;
  7759. _this._orientationBeta = evt.beta;
  7760. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7761. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7762. };
  7763. }
  7764. window.addEventListener("deviceorientation", this._orientationChanged);
  7765. };
  7766. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7767. if (this._attachedCanvas != canvas) {
  7768. return;
  7769. }
  7770. window.removeEventListener("deviceorientation", this._orientationChanged);
  7771. this._attachedCanvas = null;
  7772. this._orientationGamma = 0;
  7773. this._orientationBeta = 0;
  7774. this._initialOrientationGamma = 0;
  7775. this._initialOrientationBeta = 0;
  7776. };
  7777. DeviceOrientationCamera.prototype._checkInputs = function () {
  7778. if (!this._offsetX) {
  7779. return;
  7780. }
  7781. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7782. var speed = this._computeLocalCameraSpeed();
  7783. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7784. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7785. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7786. };
  7787. return DeviceOrientationCamera;
  7788. })(BABYLON.FreeCamera);
  7789. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7790. })(BABYLON || (BABYLON = {}));
  7791. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7792. var BABYLON;
  7793. (function (BABYLON) {
  7794. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7795. var ArcRotateCamera = (function (_super) {
  7796. __extends(ArcRotateCamera, _super);
  7797. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7798. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7799. this.alpha = alpha;
  7800. this.beta = beta;
  7801. this.radius = radius;
  7802. this.target = target;
  7803. this.inertialAlphaOffset = 0;
  7804. this.inertialBetaOffset = 0;
  7805. this.inertialRadiusOffset = 0;
  7806. this.lowerAlphaLimit = null;
  7807. this.upperAlphaLimit = null;
  7808. this.lowerBetaLimit = 0.01;
  7809. this.upperBetaLimit = Math.PI;
  7810. this.lowerRadiusLimit = null;
  7811. this.upperRadiusLimit = null;
  7812. this.angularSensibility = 1000.0;
  7813. this.wheelPrecision = 3.0;
  7814. this.pinchPrecision = 2.0;
  7815. this.keysUp = [38];
  7816. this.keysDown = [40];
  7817. this.keysLeft = [37];
  7818. this.keysRight = [39];
  7819. this.zoomOnFactor = 1;
  7820. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7821. this._keys = [];
  7822. this._viewMatrix = new BABYLON.Matrix();
  7823. this.checkCollisions = false;
  7824. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7825. this._collider = new BABYLON.Collider();
  7826. this._previousPosition = BABYLON.Vector3.Zero();
  7827. this._collisionVelocity = BABYLON.Vector3.Zero();
  7828. this._newPosition = BABYLON.Vector3.Zero();
  7829. if (!this.target) {
  7830. this.target = BABYLON.Vector3.Zero();
  7831. }
  7832. this.getViewMatrix();
  7833. }
  7834. ArcRotateCamera.prototype._getTargetPosition = function () {
  7835. return this.target.position || this.target;
  7836. };
  7837. // Cache
  7838. ArcRotateCamera.prototype._initCache = function () {
  7839. _super.prototype._initCache.call(this);
  7840. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7841. this._cache.alpha = undefined;
  7842. this._cache.beta = undefined;
  7843. this._cache.radius = undefined;
  7844. this._cache.targetScreenOffset = undefined;
  7845. };
  7846. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7847. if (!ignoreParentClass) {
  7848. _super.prototype._updateCache.call(this);
  7849. }
  7850. this._cache.target.copyFrom(this._getTargetPosition());
  7851. this._cache.alpha = this.alpha;
  7852. this._cache.beta = this.beta;
  7853. this._cache.radius = this.radius;
  7854. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7855. };
  7856. // Synchronized
  7857. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7858. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7859. return false;
  7860. 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);
  7861. };
  7862. // Methods
  7863. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7864. var _this = this;
  7865. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7866. var previousPinchDistance = 0;
  7867. var pointers = new BABYLON.SmartCollection();
  7868. if (this._attachedElement) {
  7869. return;
  7870. }
  7871. this._attachedElement = element;
  7872. var engine = this.getEngine();
  7873. if (this._onPointerDown === undefined) {
  7874. this._onPointerDown = function (evt) {
  7875. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7876. cacheSoloPointer = pointers.item(evt.pointerId);
  7877. if (!noPreventDefault) {
  7878. evt.preventDefault();
  7879. }
  7880. };
  7881. this._onPointerUp = function (evt) {
  7882. cacheSoloPointer = null;
  7883. previousPinchDistance = 0;
  7884. pointers.remove(evt.pointerId);
  7885. if (!noPreventDefault) {
  7886. evt.preventDefault();
  7887. }
  7888. };
  7889. this._onPointerMove = function (evt) {
  7890. if (!noPreventDefault) {
  7891. evt.preventDefault();
  7892. }
  7893. switch (pointers.count) {
  7894. case 1:
  7895. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7896. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7897. var offsetX = evt.clientX - cacheSoloPointer.x;
  7898. var offsetY = evt.clientY - cacheSoloPointer.y;
  7899. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7900. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7901. //pointers.item(evt.pointerId).x = evt.clientX;
  7902. //pointers.item(evt.pointerId).y = evt.clientY;
  7903. cacheSoloPointer.x = evt.clientX;
  7904. cacheSoloPointer.y = evt.clientY;
  7905. break;
  7906. case 2:
  7907. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7908. pointers.item(evt.pointerId).x = evt.clientX;
  7909. pointers.item(evt.pointerId).y = evt.clientY;
  7910. var direction = 1;
  7911. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7912. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7913. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7914. if (previousPinchDistance === 0) {
  7915. previousPinchDistance = pinchSquaredDistance;
  7916. return;
  7917. }
  7918. if (pinchSquaredDistance !== previousPinchDistance) {
  7919. if (pinchSquaredDistance > previousPinchDistance) {
  7920. direction = -1;
  7921. }
  7922. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7923. previousPinchDistance = pinchSquaredDistance;
  7924. }
  7925. break;
  7926. default:
  7927. if (pointers.item(evt.pointerId)) {
  7928. pointers.item(evt.pointerId).x = evt.clientX;
  7929. pointers.item(evt.pointerId).y = evt.clientY;
  7930. }
  7931. }
  7932. };
  7933. this._onMouseMove = function (evt) {
  7934. if (!engine.isPointerLock) {
  7935. return;
  7936. }
  7937. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7938. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7939. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7940. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7941. if (!noPreventDefault) {
  7942. evt.preventDefault();
  7943. }
  7944. };
  7945. this._wheel = function (event) {
  7946. var delta = 0;
  7947. if (event.wheelDelta) {
  7948. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7949. }
  7950. else if (event.detail) {
  7951. delta = -event.detail / _this.wheelPrecision;
  7952. }
  7953. if (delta)
  7954. _this.inertialRadiusOffset += delta;
  7955. if (event.preventDefault) {
  7956. if (!noPreventDefault) {
  7957. event.preventDefault();
  7958. }
  7959. }
  7960. };
  7961. this._onKeyDown = function (evt) {
  7962. 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) {
  7963. var index = _this._keys.indexOf(evt.keyCode);
  7964. if (index === -1) {
  7965. _this._keys.push(evt.keyCode);
  7966. }
  7967. if (evt.preventDefault) {
  7968. if (!noPreventDefault) {
  7969. evt.preventDefault();
  7970. }
  7971. }
  7972. }
  7973. };
  7974. this._onKeyUp = function (evt) {
  7975. 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) {
  7976. var index = _this._keys.indexOf(evt.keyCode);
  7977. if (index >= 0) {
  7978. _this._keys.splice(index, 1);
  7979. }
  7980. if (evt.preventDefault) {
  7981. if (!noPreventDefault) {
  7982. evt.preventDefault();
  7983. }
  7984. }
  7985. }
  7986. };
  7987. this._onLostFocus = function () {
  7988. _this._keys = [];
  7989. pointers.empty();
  7990. previousPinchDistance = 0;
  7991. cacheSoloPointer = null;
  7992. };
  7993. this._onGestureStart = function (e) {
  7994. if (window.MSGesture === undefined) {
  7995. return;
  7996. }
  7997. if (!_this._MSGestureHandler) {
  7998. _this._MSGestureHandler = new MSGesture();
  7999. _this._MSGestureHandler.target = element;
  8000. }
  8001. _this._MSGestureHandler.addPointer(e.pointerId);
  8002. };
  8003. this._onGesture = function (e) {
  8004. _this.radius *= e.scale;
  8005. if (e.preventDefault) {
  8006. if (!noPreventDefault) {
  8007. e.stopPropagation();
  8008. e.preventDefault();
  8009. }
  8010. }
  8011. };
  8012. this._reset = function () {
  8013. _this._keys = [];
  8014. _this.inertialAlphaOffset = 0;
  8015. _this.inertialBetaOffset = 0;
  8016. _this.inertialRadiusOffset = 0;
  8017. pointers.empty();
  8018. previousPinchDistance = 0;
  8019. cacheSoloPointer = null;
  8020. };
  8021. }
  8022. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8023. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8024. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8025. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8026. element.addEventListener("mousemove", this._onMouseMove, false);
  8027. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8028. element.addEventListener("MSGestureChange", this._onGesture, false);
  8029. element.addEventListener('mousewheel', this._wheel, false);
  8030. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8031. BABYLON.Tools.RegisterTopRootEvents([
  8032. { name: "keydown", handler: this._onKeyDown },
  8033. { name: "keyup", handler: this._onKeyUp },
  8034. { name: "blur", handler: this._onLostFocus }
  8035. ]);
  8036. };
  8037. ArcRotateCamera.prototype.detachControl = function (element) {
  8038. if (this._attachedElement !== element) {
  8039. return;
  8040. }
  8041. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8042. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8043. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8044. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8045. element.removeEventListener("mousemove", this._onMouseMove);
  8046. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8047. element.removeEventListener("MSGestureChange", this._onGesture);
  8048. element.removeEventListener('mousewheel', this._wheel);
  8049. element.removeEventListener('DOMMouseScroll', this._wheel);
  8050. BABYLON.Tools.UnregisterTopRootEvents([
  8051. { name: "keydown", handler: this._onKeyDown },
  8052. { name: "keyup", handler: this._onKeyUp },
  8053. { name: "blur", handler: this._onLostFocus }
  8054. ]);
  8055. this._MSGestureHandler = null;
  8056. this._attachedElement = null;
  8057. if (this._reset) {
  8058. this._reset();
  8059. }
  8060. };
  8061. ArcRotateCamera.prototype._update = function () {
  8062. for (var index = 0; index < this._keys.length; index++) {
  8063. var keyCode = this._keys[index];
  8064. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8065. this.inertialAlphaOffset -= 0.01;
  8066. }
  8067. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8068. this.inertialBetaOffset -= 0.01;
  8069. }
  8070. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8071. this.inertialAlphaOffset += 0.01;
  8072. }
  8073. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8074. this.inertialBetaOffset += 0.01;
  8075. }
  8076. }
  8077. // Inertia
  8078. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8079. this.alpha += this.inertialAlphaOffset;
  8080. this.beta += this.inertialBetaOffset;
  8081. this.radius -= this.inertialRadiusOffset;
  8082. this.inertialAlphaOffset *= this.inertia;
  8083. this.inertialBetaOffset *= this.inertia;
  8084. this.inertialRadiusOffset *= this.inertia;
  8085. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8086. this.inertialAlphaOffset = 0;
  8087. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8088. this.inertialBetaOffset = 0;
  8089. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8090. this.inertialRadiusOffset = 0;
  8091. }
  8092. // Limits
  8093. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8094. this.alpha = this.lowerAlphaLimit;
  8095. }
  8096. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8097. this.alpha = this.upperAlphaLimit;
  8098. }
  8099. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8100. this.beta = this.lowerBetaLimit;
  8101. }
  8102. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8103. this.beta = this.upperBetaLimit;
  8104. }
  8105. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8106. this.radius = this.lowerRadiusLimit;
  8107. }
  8108. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8109. this.radius = this.upperRadiusLimit;
  8110. }
  8111. };
  8112. ArcRotateCamera.prototype.setPosition = function (position) {
  8113. var radiusv3 = position.subtract(this._getTargetPosition());
  8114. this.radius = radiusv3.length();
  8115. // Alpha
  8116. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8117. if (radiusv3.z < 0) {
  8118. this.alpha = 2 * Math.PI - this.alpha;
  8119. }
  8120. // Beta
  8121. this.beta = Math.acos(radiusv3.y / this.radius);
  8122. };
  8123. ArcRotateCamera.prototype._getViewMatrix = function () {
  8124. // Compute
  8125. var cosa = Math.cos(this.alpha);
  8126. var sina = Math.sin(this.alpha);
  8127. var cosb = Math.cos(this.beta);
  8128. var sinb = Math.sin(this.beta);
  8129. var target = this._getTargetPosition();
  8130. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8131. if (this.checkCollisions) {
  8132. this._collider.radius = this.collisionRadius;
  8133. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8134. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8135. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8136. this.position.copyFrom(this._previousPosition);
  8137. this.alpha = this._previousAlpha;
  8138. this.beta = this._previousBeta;
  8139. this.radius = this._previousRadius;
  8140. if (this.onCollide) {
  8141. this.onCollide(this._collider.collidedMesh);
  8142. }
  8143. }
  8144. }
  8145. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8146. this._previousAlpha = this.alpha;
  8147. this._previousBeta = this.beta;
  8148. this._previousRadius = this.radius;
  8149. this._previousPosition.copyFrom(this.position);
  8150. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8151. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8152. return this._viewMatrix;
  8153. };
  8154. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8155. meshes = meshes || this.getScene().meshes;
  8156. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8157. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8158. this.radius = distance * this.zoomOnFactor;
  8159. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8160. };
  8161. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8162. var meshesOrMinMaxVector;
  8163. var distance;
  8164. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8165. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8166. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8167. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8168. }
  8169. else {
  8170. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8171. distance = meshesOrMinMaxVectorAndDistance.distance;
  8172. }
  8173. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8174. this.maxZ = distance * 2;
  8175. };
  8176. return ArcRotateCamera;
  8177. })(BABYLON.Camera);
  8178. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8179. })(BABYLON || (BABYLON = {}));
  8180. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8181. (function (BABYLON) {
  8182. /**
  8183. * Represents a scene to be rendered by the engine.
  8184. * @see http://doc.babylonjs.com/page.php?p=21911
  8185. */
  8186. var Scene = (function () {
  8187. /**
  8188. * @constructor
  8189. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8190. */
  8191. function Scene(engine) {
  8192. // Members
  8193. this.autoClear = true;
  8194. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8195. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8196. this.forceWireframe = false;
  8197. this.forcePointsCloud = false;
  8198. this.forceShowBoundingBoxes = false;
  8199. this.animationsEnabled = true;
  8200. 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
  8201. // Fog
  8202. /**
  8203. * is fog enabled on this scene.
  8204. * @type {boolean}
  8205. */
  8206. this.fogEnabled = true;
  8207. this.fogMode = Scene.FOGMODE_NONE;
  8208. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8209. this.fogDensity = 0.1;
  8210. this.fogStart = 0;
  8211. this.fogEnd = 1000.0;
  8212. // Lights
  8213. /**
  8214. * is shadow enabled on this scene.
  8215. * @type {boolean}
  8216. */
  8217. this.shadowsEnabled = true;
  8218. /**
  8219. * is light enabled on this scene.
  8220. * @type {boolean}
  8221. */
  8222. this.lightsEnabled = true;
  8223. /**
  8224. * All of the lights added to this scene.
  8225. * @see BABYLON.Light
  8226. * @type {BABYLON.Light[]}
  8227. */
  8228. this.lights = new Array();
  8229. // Cameras
  8230. /**
  8231. * All of the cameras added to this scene.
  8232. * @see BABYLON.Camera
  8233. * @type {BABYLON.Camera[]}
  8234. */
  8235. this.cameras = new Array();
  8236. this.activeCameras = new Array();
  8237. // Meshes
  8238. /**
  8239. * All of the (abstract) meshes added to this scene.
  8240. * @see BABYLON.AbstractMesh
  8241. * @type {BABYLON.AbstractMesh[]}
  8242. */
  8243. this.meshes = new Array();
  8244. // Geometries
  8245. this._geometries = new Array();
  8246. this.materials = new Array();
  8247. this.multiMaterials = new Array();
  8248. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8249. // Textures
  8250. this.texturesEnabled = true;
  8251. this.textures = new Array();
  8252. // Particles
  8253. this.particlesEnabled = true;
  8254. this.particleSystems = new Array();
  8255. // Sprites
  8256. this.spritesEnabled = true;
  8257. this.spriteManagers = new Array();
  8258. // Layers
  8259. this.layers = new Array();
  8260. // Skeletons
  8261. this.skeletonsEnabled = true;
  8262. this.skeletons = new Array();
  8263. // Lens flares
  8264. this.lensFlaresEnabled = true;
  8265. this.lensFlareSystems = new Array();
  8266. // Collisions
  8267. this.collisionsEnabled = true;
  8268. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8269. // Postprocesses
  8270. this.postProcessesEnabled = true;
  8271. // Customs render targets
  8272. this.renderTargetsEnabled = true;
  8273. this.dumpNextRenderTargets = false;
  8274. this.customRenderTargets = new Array();
  8275. // Imported meshes
  8276. this.importedMeshesFiles = new Array();
  8277. this._actionManagers = new Array();
  8278. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8279. // Procedural textures
  8280. this.proceduralTexturesEnabled = true;
  8281. this._proceduralTextures = new Array();
  8282. this.soundTracks = new Array();
  8283. this._audioEnabled = true;
  8284. this._headphone = false;
  8285. this._totalVertices = 0;
  8286. this._activeVertices = 0;
  8287. this._activeParticles = 0;
  8288. this._lastFrameDuration = 0;
  8289. this._evaluateActiveMeshesDuration = 0;
  8290. this._renderTargetsDuration = 0;
  8291. this._particlesDuration = 0;
  8292. this._renderDuration = 0;
  8293. this._spritesDuration = 0;
  8294. this._animationRatio = 0;
  8295. this._renderId = 0;
  8296. this._executeWhenReadyTimeoutId = -1;
  8297. this._toBeDisposed = new BABYLON.SmartArray(256);
  8298. this._onReadyCallbacks = new Array();
  8299. this._pendingData = []; //ANY
  8300. this._onBeforeRenderCallbacks = new Array();
  8301. this._onAfterRenderCallbacks = new Array();
  8302. this._activeMeshes = new BABYLON.SmartArray(256);
  8303. this._processedMaterials = new BABYLON.SmartArray(256);
  8304. this._renderTargets = new BABYLON.SmartArray(256);
  8305. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8306. this._activeSkeletons = new BABYLON.SmartArray(32);
  8307. this._activeBones = 0;
  8308. this._activeAnimatables = new Array();
  8309. this._transformMatrix = BABYLON.Matrix.Zero();
  8310. this._scaledPosition = BABYLON.Vector3.Zero();
  8311. this._scaledVelocity = BABYLON.Vector3.Zero();
  8312. this._uniqueIdCounter = 0;
  8313. this._engine = engine;
  8314. engine.scenes.push(this);
  8315. this._renderingManager = new BABYLON.RenderingManager(this);
  8316. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8317. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8318. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8319. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8320. this.attachControl();
  8321. this._debugLayer = new BABYLON.DebugLayer(this);
  8322. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8323. //simplification queue
  8324. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8325. }
  8326. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8327. get: function () {
  8328. return Scene._FOGMODE_NONE;
  8329. },
  8330. enumerable: true,
  8331. configurable: true
  8332. });
  8333. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8334. get: function () {
  8335. return Scene._FOGMODE_EXP;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8341. get: function () {
  8342. return Scene._FOGMODE_EXP2;
  8343. },
  8344. enumerable: true,
  8345. configurable: true
  8346. });
  8347. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8348. get: function () {
  8349. return Scene._FOGMODE_LINEAR;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(Scene.prototype, "debugLayer", {
  8355. // Properties
  8356. get: function () {
  8357. return this._debugLayer;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8363. /**
  8364. * The mesh that is currently under the pointer.
  8365. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8366. */
  8367. get: function () {
  8368. return this._meshUnderPointer;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Scene.prototype, "pointerX", {
  8374. /**
  8375. * Current on-screen X position of the pointer
  8376. * @return {number} X position of the pointer
  8377. */
  8378. get: function () {
  8379. return this._pointerX;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Scene.prototype, "pointerY", {
  8385. /**
  8386. * Current on-screen Y position of the pointer
  8387. * @return {number} Y position of the pointer
  8388. */
  8389. get: function () {
  8390. return this._pointerY;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Scene.prototype.getCachedMaterial = function () {
  8396. return this._cachedMaterial;
  8397. };
  8398. Scene.prototype.getBoundingBoxRenderer = function () {
  8399. return this._boundingBoxRenderer;
  8400. };
  8401. Scene.prototype.getOutlineRenderer = function () {
  8402. return this._outlineRenderer;
  8403. };
  8404. Scene.prototype.getEngine = function () {
  8405. return this._engine;
  8406. };
  8407. Scene.prototype.getTotalVertices = function () {
  8408. return this._totalVertices;
  8409. };
  8410. Scene.prototype.getActiveVertices = function () {
  8411. return this._activeVertices;
  8412. };
  8413. Scene.prototype.getActiveParticles = function () {
  8414. return this._activeParticles;
  8415. };
  8416. Scene.prototype.getActiveBones = function () {
  8417. return this._activeBones;
  8418. };
  8419. // Stats
  8420. Scene.prototype.getLastFrameDuration = function () {
  8421. return this._lastFrameDuration;
  8422. };
  8423. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8424. return this._evaluateActiveMeshesDuration;
  8425. };
  8426. Scene.prototype.getActiveMeshes = function () {
  8427. return this._activeMeshes;
  8428. };
  8429. Scene.prototype.getRenderTargetsDuration = function () {
  8430. return this._renderTargetsDuration;
  8431. };
  8432. Scene.prototype.getRenderDuration = function () {
  8433. return this._renderDuration;
  8434. };
  8435. Scene.prototype.getParticlesDuration = function () {
  8436. return this._particlesDuration;
  8437. };
  8438. Scene.prototype.getSpritesDuration = function () {
  8439. return this._spritesDuration;
  8440. };
  8441. Scene.prototype.getAnimationRatio = function () {
  8442. return this._animationRatio;
  8443. };
  8444. Scene.prototype.getRenderId = function () {
  8445. return this._renderId;
  8446. };
  8447. Scene.prototype.incrementRenderId = function () {
  8448. this._renderId++;
  8449. };
  8450. Scene.prototype._updatePointerPosition = function (evt) {
  8451. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8452. this._pointerX = evt.clientX - canvasRect.left;
  8453. this._pointerY = evt.clientY - canvasRect.top;
  8454. if (this.cameraToUseForPointers) {
  8455. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8456. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8457. }
  8458. };
  8459. // Pointers handling
  8460. Scene.prototype.attachControl = function () {
  8461. var _this = this;
  8462. this._onPointerMove = function (evt) {
  8463. var canvas = _this._engine.getRenderingCanvas();
  8464. _this._updatePointerPosition(evt);
  8465. 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);
  8466. if (pickResult.hit) {
  8467. _this._meshUnderPointer = pickResult.pickedMesh;
  8468. _this.setPointerOverMesh(pickResult.pickedMesh);
  8469. canvas.style.cursor = "pointer";
  8470. }
  8471. else {
  8472. _this.setPointerOverMesh(null);
  8473. canvas.style.cursor = "";
  8474. _this._meshUnderPointer = null;
  8475. }
  8476. };
  8477. this._onPointerDown = function (evt) {
  8478. var predicate = null;
  8479. if (!_this.onPointerDown) {
  8480. predicate = function (mesh) {
  8481. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8482. };
  8483. }
  8484. _this._updatePointerPosition(evt);
  8485. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8486. if (pickResult.hit) {
  8487. if (pickResult.pickedMesh.actionManager) {
  8488. switch (evt.button) {
  8489. case 0:
  8490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8491. break;
  8492. case 1:
  8493. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8494. break;
  8495. case 2:
  8496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8497. break;
  8498. }
  8499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8500. }
  8501. }
  8502. if (_this.onPointerDown) {
  8503. _this.onPointerDown(evt, pickResult);
  8504. }
  8505. };
  8506. this._onKeyDown = function (evt) {
  8507. if (_this.actionManager) {
  8508. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8509. }
  8510. };
  8511. this._onKeyUp = function (evt) {
  8512. if (_this.actionManager) {
  8513. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8514. }
  8515. };
  8516. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8517. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8518. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8519. BABYLON.Tools.RegisterTopRootEvents([
  8520. { name: "keydown", handler: this._onKeyDown },
  8521. { name: "keyup", handler: this._onKeyUp }
  8522. ]);
  8523. };
  8524. Scene.prototype.detachControl = function () {
  8525. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8526. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8527. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8528. BABYLON.Tools.UnregisterTopRootEvents([
  8529. { name: "keydown", handler: this._onKeyDown },
  8530. { name: "keyup", handler: this._onKeyUp }
  8531. ]);
  8532. };
  8533. // Ready
  8534. Scene.prototype.isReady = function () {
  8535. if (this._pendingData.length > 0) {
  8536. return false;
  8537. }
  8538. for (var index = 0; index < this._geometries.length; index++) {
  8539. var geometry = this._geometries[index];
  8540. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8541. return false;
  8542. }
  8543. }
  8544. for (index = 0; index < this.meshes.length; index++) {
  8545. var mesh = this.meshes[index];
  8546. if (!mesh.isReady()) {
  8547. return false;
  8548. }
  8549. var mat = mesh.material;
  8550. if (mat) {
  8551. if (!mat.isReady(mesh)) {
  8552. return false;
  8553. }
  8554. }
  8555. }
  8556. return true;
  8557. };
  8558. Scene.prototype.resetCachedMaterial = function () {
  8559. this._cachedMaterial = null;
  8560. };
  8561. Scene.prototype.registerBeforeRender = function (func) {
  8562. this._onBeforeRenderCallbacks.push(func);
  8563. };
  8564. Scene.prototype.unregisterBeforeRender = function (func) {
  8565. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8566. if (index > -1) {
  8567. this._onBeforeRenderCallbacks.splice(index, 1);
  8568. }
  8569. };
  8570. Scene.prototype.registerAfterRender = function (func) {
  8571. this._onAfterRenderCallbacks.push(func);
  8572. };
  8573. Scene.prototype.unregisterAfterRender = function (func) {
  8574. var index = this._onAfterRenderCallbacks.indexOf(func);
  8575. if (index > -1) {
  8576. this._onAfterRenderCallbacks.splice(index, 1);
  8577. }
  8578. };
  8579. Scene.prototype._addPendingData = function (data) {
  8580. this._pendingData.push(data);
  8581. };
  8582. Scene.prototype._removePendingData = function (data) {
  8583. var index = this._pendingData.indexOf(data);
  8584. if (index !== -1) {
  8585. this._pendingData.splice(index, 1);
  8586. }
  8587. };
  8588. Scene.prototype.getWaitingItemsCount = function () {
  8589. return this._pendingData.length;
  8590. };
  8591. /**
  8592. * Registers a function to be executed when the scene is ready.
  8593. * @param {Function} func - the function to be executed.
  8594. */
  8595. Scene.prototype.executeWhenReady = function (func) {
  8596. var _this = this;
  8597. this._onReadyCallbacks.push(func);
  8598. if (this._executeWhenReadyTimeoutId !== -1) {
  8599. return;
  8600. }
  8601. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8602. _this._checkIsReady();
  8603. }, 150);
  8604. };
  8605. Scene.prototype._checkIsReady = function () {
  8606. var _this = this;
  8607. if (this.isReady()) {
  8608. this._onReadyCallbacks.forEach(function (func) {
  8609. func();
  8610. });
  8611. this._onReadyCallbacks = [];
  8612. this._executeWhenReadyTimeoutId = -1;
  8613. return;
  8614. }
  8615. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8616. _this._checkIsReady();
  8617. }, 150);
  8618. };
  8619. // Animations
  8620. /**
  8621. * Will start the animation sequence of a given target
  8622. * @param target - the target
  8623. * @param {number} from - from which frame should animation start
  8624. * @param {number} to - till which frame should animation run.
  8625. * @param {boolean} [loop] - should the animation loop
  8626. * @param {number} [speedRatio] - the speed in which to run the animation
  8627. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8628. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8629. * @return {BABYLON.Animatable} the animatable object created for this animation
  8630. * @see BABYLON.Animatable
  8631. * @see http://doc.babylonjs.com/page.php?p=22081
  8632. */
  8633. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8634. if (speedRatio === undefined) {
  8635. speedRatio = 1.0;
  8636. }
  8637. this.stopAnimation(target);
  8638. if (!animatable) {
  8639. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8640. }
  8641. // Local animations
  8642. if (target.animations) {
  8643. animatable.appendAnimations(target, target.animations);
  8644. }
  8645. // Children animations
  8646. if (target.getAnimatables) {
  8647. var animatables = target.getAnimatables();
  8648. for (var index = 0; index < animatables.length; index++) {
  8649. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8650. }
  8651. }
  8652. return animatable;
  8653. };
  8654. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8655. if (speedRatio === undefined) {
  8656. speedRatio = 1.0;
  8657. }
  8658. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8659. return animatable;
  8660. };
  8661. Scene.prototype.getAnimatableByTarget = function (target) {
  8662. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8663. if (this._activeAnimatables[index].target === target) {
  8664. return this._activeAnimatables[index];
  8665. }
  8666. }
  8667. return null;
  8668. };
  8669. /**
  8670. * Will stop the animation of the given target
  8671. * @param target - the target
  8672. * @see beginAnimation
  8673. */
  8674. Scene.prototype.stopAnimation = function (target) {
  8675. var animatable = this.getAnimatableByTarget(target);
  8676. if (animatable) {
  8677. animatable.stop();
  8678. }
  8679. };
  8680. Scene.prototype._animate = function () {
  8681. if (!this.animationsEnabled) {
  8682. return;
  8683. }
  8684. if (!this._animationStartDate) {
  8685. this._animationStartDate = BABYLON.Tools.Now;
  8686. }
  8687. // Getting time
  8688. var now = BABYLON.Tools.Now;
  8689. var delay = now - this._animationStartDate;
  8690. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8691. this._activeAnimatables[index]._animate(delay);
  8692. }
  8693. };
  8694. // Matrix
  8695. Scene.prototype.getViewMatrix = function () {
  8696. return this._viewMatrix;
  8697. };
  8698. Scene.prototype.getProjectionMatrix = function () {
  8699. return this._projectionMatrix;
  8700. };
  8701. Scene.prototype.getTransformMatrix = function () {
  8702. return this._transformMatrix;
  8703. };
  8704. Scene.prototype.setTransformMatrix = function (view, projection) {
  8705. this._viewMatrix = view;
  8706. this._projectionMatrix = projection;
  8707. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8708. };
  8709. // Methods
  8710. Scene.prototype.addMesh = function (newMesh) {
  8711. newMesh.uniqueId = this._uniqueIdCounter++;
  8712. var position = this.meshes.push(newMesh);
  8713. if (this.onNewMeshAdded) {
  8714. this.onNewMeshAdded(newMesh, position, this);
  8715. }
  8716. };
  8717. Scene.prototype.removeMesh = function (toRemove) {
  8718. var index = this.meshes.indexOf(toRemove);
  8719. if (index !== -1) {
  8720. // Remove from the scene if mesh found
  8721. this.meshes.splice(index, 1);
  8722. }
  8723. if (this.onMeshRemoved) {
  8724. this.onMeshRemoved(toRemove);
  8725. }
  8726. return index;
  8727. };
  8728. Scene.prototype.removeLight = function (toRemove) {
  8729. var index = this.lights.indexOf(toRemove);
  8730. if (index !== -1) {
  8731. // Remove from the scene if mesh found
  8732. this.lights.splice(index, 1);
  8733. }
  8734. if (this.onLightRemoved) {
  8735. this.onLightRemoved(toRemove);
  8736. }
  8737. return index;
  8738. };
  8739. Scene.prototype.removeCamera = function (toRemove) {
  8740. var index = this.cameras.indexOf(toRemove);
  8741. if (index !== -1) {
  8742. // Remove from the scene if mesh found
  8743. this.cameras.splice(index, 1);
  8744. }
  8745. // Remove from activeCameras
  8746. var index2 = this.activeCameras.indexOf(toRemove);
  8747. if (index2 !== -1) {
  8748. // Remove from the scene if mesh found
  8749. this.activeCameras.splice(index2, 1);
  8750. }
  8751. // Reset the activeCamera
  8752. if (this.activeCamera === toRemove) {
  8753. if (this.cameras.length > 0) {
  8754. this.activeCamera = this.cameras[0];
  8755. }
  8756. else {
  8757. this.activeCamera = null;
  8758. }
  8759. }
  8760. if (this.onCameraRemoved) {
  8761. this.onCameraRemoved(toRemove);
  8762. }
  8763. return index;
  8764. };
  8765. Scene.prototype.addLight = function (newLight) {
  8766. newLight.uniqueId = this._uniqueIdCounter++;
  8767. var position = this.lights.push(newLight);
  8768. if (this.onNewLightAdded) {
  8769. this.onNewLightAdded(newLight, position, this);
  8770. }
  8771. };
  8772. Scene.prototype.addCamera = function (newCamera) {
  8773. newCamera.uniqueId = this._uniqueIdCounter++;
  8774. var position = this.cameras.push(newCamera);
  8775. if (this.onNewCameraAdded) {
  8776. this.onNewCameraAdded(newCamera, position, this);
  8777. }
  8778. };
  8779. /**
  8780. * sets the active camera of the scene using its ID
  8781. * @param {string} id - the camera's ID
  8782. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8783. * @see activeCamera
  8784. */
  8785. Scene.prototype.setActiveCameraByID = function (id) {
  8786. var camera = this.getCameraByID(id);
  8787. if (camera) {
  8788. this.activeCamera = camera;
  8789. return camera;
  8790. }
  8791. return null;
  8792. };
  8793. /**
  8794. * sets the active camera of the scene using its name
  8795. * @param {string} name - the camera's name
  8796. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8797. * @see activeCamera
  8798. */
  8799. Scene.prototype.setActiveCameraByName = function (name) {
  8800. var camera = this.getCameraByName(name);
  8801. if (camera) {
  8802. this.activeCamera = camera;
  8803. return camera;
  8804. }
  8805. return null;
  8806. };
  8807. /**
  8808. * get a material using its id
  8809. * @param {string} the material's ID
  8810. * @return {BABYLON.Material|null} the material or null if none found.
  8811. */
  8812. Scene.prototype.getMaterialByID = function (id) {
  8813. for (var index = 0; index < this.materials.length; index++) {
  8814. if (this.materials[index].id === id) {
  8815. return this.materials[index];
  8816. }
  8817. }
  8818. return null;
  8819. };
  8820. /**
  8821. * get a material using its name
  8822. * @param {string} the material's name
  8823. * @return {BABYLON.Material|null} the material or null if none found.
  8824. */
  8825. Scene.prototype.getMaterialByName = function (name) {
  8826. for (var index = 0; index < this.materials.length; index++) {
  8827. if (this.materials[index].name === name) {
  8828. return this.materials[index];
  8829. }
  8830. }
  8831. return null;
  8832. };
  8833. Scene.prototype.getCameraByID = function (id) {
  8834. for (var index = 0; index < this.cameras.length; index++) {
  8835. if (this.cameras[index].id === id) {
  8836. return this.cameras[index];
  8837. }
  8838. }
  8839. return null;
  8840. };
  8841. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8842. for (var index = 0; index < this.cameras.length; index++) {
  8843. if (this.cameras[index].uniqueId === uniqueId) {
  8844. return this.cameras[index];
  8845. }
  8846. }
  8847. return null;
  8848. };
  8849. /**
  8850. * get a camera using its name
  8851. * @param {string} the camera's name
  8852. * @return {BABYLON.Camera|null} the camera or null if none found.
  8853. */
  8854. Scene.prototype.getCameraByName = function (name) {
  8855. for (var index = 0; index < this.cameras.length; index++) {
  8856. if (this.cameras[index].name === name) {
  8857. return this.cameras[index];
  8858. }
  8859. }
  8860. return null;
  8861. };
  8862. /**
  8863. * get a light node using its name
  8864. * @param {string} the light's name
  8865. * @return {BABYLON.Light|null} the light or null if none found.
  8866. */
  8867. Scene.prototype.getLightByName = function (name) {
  8868. for (var index = 0; index < this.lights.length; index++) {
  8869. if (this.lights[index].name === name) {
  8870. return this.lights[index];
  8871. }
  8872. }
  8873. return null;
  8874. };
  8875. /**
  8876. * get a light node using its ID
  8877. * @param {string} the light's id
  8878. * @return {BABYLON.Light|null} the light or null if none found.
  8879. */
  8880. Scene.prototype.getLightByID = function (id) {
  8881. for (var index = 0; index < this.lights.length; index++) {
  8882. if (this.lights[index].id === id) {
  8883. return this.lights[index];
  8884. }
  8885. }
  8886. return null;
  8887. };
  8888. /**
  8889. * get a light node using its scene-generated unique ID
  8890. * @param {number} the light's unique id
  8891. * @return {BABYLON.Light|null} the light or null if none found.
  8892. */
  8893. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8894. for (var index = 0; index < this.lights.length; index++) {
  8895. if (this.lights[index].uniqueId === uniqueId) {
  8896. return this.lights[index];
  8897. }
  8898. }
  8899. return null;
  8900. };
  8901. /**
  8902. * get a geometry using its ID
  8903. * @param {string} the geometry's id
  8904. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8905. */
  8906. Scene.prototype.getGeometryByID = function (id) {
  8907. for (var index = 0; index < this._geometries.length; index++) {
  8908. if (this._geometries[index].id === id) {
  8909. return this._geometries[index];
  8910. }
  8911. }
  8912. return null;
  8913. };
  8914. /**
  8915. * add a new geometry to this scene.
  8916. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8917. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8918. * @return {boolean} was the geometry added or not
  8919. */
  8920. Scene.prototype.pushGeometry = function (geometry, force) {
  8921. if (!force && this.getGeometryByID(geometry.id)) {
  8922. return false;
  8923. }
  8924. this._geometries.push(geometry);
  8925. if (this.onGeometryAdded) {
  8926. this.onGeometryAdded(geometry);
  8927. }
  8928. return true;
  8929. };
  8930. /**
  8931. * Removes an existing geometry
  8932. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8933. * @return {boolean} was the geometry removed or not
  8934. */
  8935. Scene.prototype.removeGeometry = function (geometry) {
  8936. var index = this._geometries.indexOf(geometry);
  8937. if (index > -1) {
  8938. this._geometries.splice(index, 1);
  8939. if (this.onGeometryRemoved) {
  8940. this.onGeometryRemoved(geometry);
  8941. }
  8942. return true;
  8943. }
  8944. return false;
  8945. };
  8946. Scene.prototype.getGeometries = function () {
  8947. return this._geometries;
  8948. };
  8949. /**
  8950. * Get the first added mesh found of a given ID
  8951. * @param {string} id - the id to search for
  8952. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8953. */
  8954. Scene.prototype.getMeshByID = function (id) {
  8955. for (var index = 0; index < this.meshes.length; index++) {
  8956. if (this.meshes[index].id === id) {
  8957. return this.meshes[index];
  8958. }
  8959. }
  8960. return null;
  8961. };
  8962. /**
  8963. * Get a mesh with its auto-generated unique id
  8964. * @param {number} uniqueId - the unique id to search for
  8965. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8966. */
  8967. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8968. for (var index = 0; index < this.meshes.length; index++) {
  8969. if (this.meshes[index].uniqueId === uniqueId) {
  8970. return this.meshes[index];
  8971. }
  8972. }
  8973. return null;
  8974. };
  8975. /**
  8976. * Get a the last added mesh found of a given ID
  8977. * @param {string} id - the id to search for
  8978. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8979. */
  8980. Scene.prototype.getLastMeshByID = function (id) {
  8981. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8982. if (this.meshes[index].id === id) {
  8983. return this.meshes[index];
  8984. }
  8985. }
  8986. return null;
  8987. };
  8988. /**
  8989. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8990. * @param {string} id - the id to search for
  8991. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8992. */
  8993. Scene.prototype.getLastEntryByID = function (id) {
  8994. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8995. if (this.meshes[index].id === id) {
  8996. return this.meshes[index];
  8997. }
  8998. }
  8999. for (index = this.cameras.length - 1; index >= 0; index--) {
  9000. if (this.cameras[index].id === id) {
  9001. return this.cameras[index];
  9002. }
  9003. }
  9004. for (index = this.lights.length - 1; index >= 0; index--) {
  9005. if (this.lights[index].id === id) {
  9006. return this.lights[index];
  9007. }
  9008. }
  9009. return null;
  9010. };
  9011. Scene.prototype.getNodeByName = function (name) {
  9012. var mesh = this.getMeshByName(name);
  9013. if (mesh) {
  9014. return mesh;
  9015. }
  9016. var light = this.getLightByName(name);
  9017. if (light) {
  9018. return light;
  9019. }
  9020. return this.getCameraByName(name);
  9021. };
  9022. Scene.prototype.getMeshByName = function (name) {
  9023. for (var index = 0; index < this.meshes.length; index++) {
  9024. if (this.meshes[index].name === name) {
  9025. return this.meshes[index];
  9026. }
  9027. }
  9028. return null;
  9029. };
  9030. Scene.prototype.getSoundByName = function (name) {
  9031. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9032. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9033. return this.mainSoundTrack.soundCollection[index];
  9034. }
  9035. }
  9036. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9037. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9038. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9039. return this.soundTracks[sdIndex].soundCollection[index];
  9040. }
  9041. }
  9042. }
  9043. return null;
  9044. };
  9045. Scene.prototype.getLastSkeletonByID = function (id) {
  9046. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9047. if (this.skeletons[index].id === id) {
  9048. return this.skeletons[index];
  9049. }
  9050. }
  9051. return null;
  9052. };
  9053. Scene.prototype.getSkeletonById = function (id) {
  9054. for (var index = 0; index < this.skeletons.length; index++) {
  9055. if (this.skeletons[index].id === id) {
  9056. return this.skeletons[index];
  9057. }
  9058. }
  9059. return null;
  9060. };
  9061. Scene.prototype.getSkeletonByName = function (name) {
  9062. for (var index = 0; index < this.skeletons.length; index++) {
  9063. if (this.skeletons[index].name === name) {
  9064. return this.skeletons[index];
  9065. }
  9066. }
  9067. return null;
  9068. };
  9069. Scene.prototype.isActiveMesh = function (mesh) {
  9070. return (this._activeMeshes.indexOf(mesh) !== -1);
  9071. };
  9072. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9073. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9074. var material = subMesh.getMaterial();
  9075. if (mesh.showSubMeshesBoundingBox) {
  9076. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9077. }
  9078. if (material) {
  9079. // Render targets
  9080. if (material.getRenderTargetTextures) {
  9081. if (this._processedMaterials.indexOf(material) === -1) {
  9082. this._processedMaterials.push(material);
  9083. this._renderTargets.concat(material.getRenderTargetTextures());
  9084. }
  9085. }
  9086. // Dispatch
  9087. this._activeVertices += subMesh.indexCount;
  9088. this._renderingManager.dispatch(subMesh);
  9089. }
  9090. }
  9091. };
  9092. Scene.prototype._evaluateActiveMeshes = function () {
  9093. this.activeCamera._activeMeshes.reset();
  9094. this._activeMeshes.reset();
  9095. this._renderingManager.reset();
  9096. this._processedMaterials.reset();
  9097. this._activeParticleSystems.reset();
  9098. this._activeSkeletons.reset();
  9099. this._boundingBoxRenderer.reset();
  9100. if (!this._frustumPlanes) {
  9101. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9102. }
  9103. else {
  9104. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9105. }
  9106. // Meshes
  9107. var meshes;
  9108. var len;
  9109. if (this._selectionOctree) {
  9110. var selection = this._selectionOctree.select(this._frustumPlanes);
  9111. meshes = selection.data;
  9112. len = selection.length;
  9113. }
  9114. else {
  9115. len = this.meshes.length;
  9116. meshes = this.meshes;
  9117. }
  9118. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9119. var mesh = meshes[meshIndex];
  9120. if (mesh.isBlocked) {
  9121. continue;
  9122. }
  9123. this._totalVertices += mesh.getTotalVertices();
  9124. if (!mesh.isReady()) {
  9125. continue;
  9126. }
  9127. mesh.computeWorldMatrix();
  9128. // Intersections
  9129. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9130. this._meshesForIntersections.pushNoDuplicate(mesh);
  9131. }
  9132. // Switch to current LOD
  9133. var meshLOD = mesh.getLOD(this.activeCamera);
  9134. if (!meshLOD) {
  9135. continue;
  9136. }
  9137. mesh._preActivate();
  9138. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9139. this._activeMeshes.push(mesh);
  9140. this.activeCamera._activeMeshes.push(mesh);
  9141. mesh._activate(this._renderId);
  9142. this._activeMesh(meshLOD);
  9143. }
  9144. }
  9145. // Particle systems
  9146. var beforeParticlesDate = BABYLON.Tools.Now;
  9147. if (this.particlesEnabled) {
  9148. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9149. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9150. var particleSystem = this.particleSystems[particleIndex];
  9151. if (!particleSystem.isStarted()) {
  9152. continue;
  9153. }
  9154. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9155. this._activeParticleSystems.push(particleSystem);
  9156. particleSystem.animate();
  9157. }
  9158. }
  9159. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9160. }
  9161. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9162. };
  9163. Scene.prototype._activeMesh = function (mesh) {
  9164. if (mesh.skeleton && this.skeletonsEnabled) {
  9165. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9166. }
  9167. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9168. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9169. }
  9170. if (mesh && mesh.subMeshes) {
  9171. // Submeshes Octrees
  9172. var len;
  9173. var subMeshes;
  9174. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9175. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9176. len = intersections.length;
  9177. subMeshes = intersections.data;
  9178. }
  9179. else {
  9180. subMeshes = mesh.subMeshes;
  9181. len = subMeshes.length;
  9182. }
  9183. for (var subIndex = 0; subIndex < len; subIndex++) {
  9184. var subMesh = subMeshes[subIndex];
  9185. this._evaluateSubMesh(subMesh, mesh);
  9186. }
  9187. }
  9188. };
  9189. Scene.prototype.updateTransformMatrix = function (force) {
  9190. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9191. };
  9192. Scene.prototype._renderForCamera = function (camera) {
  9193. var engine = this._engine;
  9194. this.activeCamera = camera;
  9195. if (!this.activeCamera)
  9196. throw new Error("Active camera not set");
  9197. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9198. // Viewport
  9199. engine.setViewport(this.activeCamera.viewport);
  9200. // Camera
  9201. this._renderId++;
  9202. this.updateTransformMatrix();
  9203. if (this.beforeCameraRender) {
  9204. this.beforeCameraRender(this.activeCamera);
  9205. }
  9206. // Meshes
  9207. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9208. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9209. this._evaluateActiveMeshes();
  9210. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9211. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9212. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9213. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9214. skeleton.prepare();
  9215. }
  9216. // Render targets
  9217. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9218. if (this.renderTargetsEnabled) {
  9219. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9220. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9221. var renderTarget = this._renderTargets.data[renderIndex];
  9222. if (renderTarget._shouldRender()) {
  9223. this._renderId++;
  9224. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9225. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9226. }
  9227. }
  9228. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9229. this._renderId++;
  9230. }
  9231. if (this._renderTargets.length > 0) {
  9232. engine.restoreDefaultFramebuffer();
  9233. }
  9234. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9235. // Prepare Frame
  9236. this.postProcessManager._prepareFrame();
  9237. var beforeRenderDate = BABYLON.Tools.Now;
  9238. // Backgrounds
  9239. if (this.layers.length) {
  9240. engine.setDepthBuffer(false);
  9241. var layerIndex;
  9242. var layer;
  9243. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9244. layer = this.layers[layerIndex];
  9245. if (layer.isBackground) {
  9246. layer.render();
  9247. }
  9248. }
  9249. engine.setDepthBuffer(true);
  9250. }
  9251. // Render
  9252. BABYLON.Tools.StartPerformanceCounter("Main render");
  9253. this._renderingManager.render(null, null, true, true);
  9254. BABYLON.Tools.EndPerformanceCounter("Main render");
  9255. // Bounding boxes
  9256. this._boundingBoxRenderer.render();
  9257. // Lens flares
  9258. if (this.lensFlaresEnabled) {
  9259. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9260. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9261. this.lensFlareSystems[lensFlareSystemIndex].render();
  9262. }
  9263. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9264. }
  9265. // Foregrounds
  9266. if (this.layers.length) {
  9267. engine.setDepthBuffer(false);
  9268. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9269. layer = this.layers[layerIndex];
  9270. if (!layer.isBackground) {
  9271. layer.render();
  9272. }
  9273. }
  9274. engine.setDepthBuffer(true);
  9275. }
  9276. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9277. // Finalize frame
  9278. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9279. // Update camera
  9280. this.activeCamera._updateFromScene();
  9281. // Reset some special arrays
  9282. this._renderTargets.reset();
  9283. if (this.afterCameraRender) {
  9284. this.afterCameraRender(this.activeCamera);
  9285. }
  9286. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9287. };
  9288. Scene.prototype._processSubCameras = function (camera) {
  9289. if (camera.subCameras.length === 0) {
  9290. this._renderForCamera(camera);
  9291. return;
  9292. }
  9293. for (var index = 0; index < camera.subCameras.length; index++) {
  9294. this._renderForCamera(camera.subCameras[index]);
  9295. }
  9296. this.activeCamera = camera;
  9297. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9298. // Update camera
  9299. this.activeCamera._updateFromScene();
  9300. };
  9301. Scene.prototype._checkIntersections = function () {
  9302. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9303. var sourceMesh = this._meshesForIntersections.data[index];
  9304. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9305. var action = sourceMesh.actionManager.actions[actionIndex];
  9306. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9307. var parameters = action.getTriggerParameter();
  9308. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9309. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9310. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9311. if (areIntersecting && currentIntersectionInProgress === -1) {
  9312. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9313. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9314. sourceMesh._intersectionsInProgress.push(otherMesh);
  9315. }
  9316. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9317. sourceMesh._intersectionsInProgress.push(otherMesh);
  9318. }
  9319. }
  9320. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9321. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9322. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9323. if (indexOfOther > -1) {
  9324. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9325. }
  9326. }
  9327. }
  9328. }
  9329. }
  9330. };
  9331. Scene.prototype.render = function () {
  9332. var startDate = BABYLON.Tools.Now;
  9333. this._particlesDuration = 0;
  9334. this._spritesDuration = 0;
  9335. this._activeParticles = 0;
  9336. this._renderDuration = 0;
  9337. this._renderTargetsDuration = 0;
  9338. this._evaluateActiveMeshesDuration = 0;
  9339. this._totalVertices = 0;
  9340. this._activeVertices = 0;
  9341. this._activeBones = 0;
  9342. this.getEngine().resetDrawCalls();
  9343. this._meshesForIntersections.reset();
  9344. this.resetCachedMaterial();
  9345. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9346. // Actions
  9347. if (this.actionManager) {
  9348. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9349. }
  9350. //Simplification Queue
  9351. if (!this.simplificationQueue.running) {
  9352. this.simplificationQueue.executeNext();
  9353. }
  9354. // Before render
  9355. if (this.beforeRender) {
  9356. this.beforeRender();
  9357. }
  9358. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9359. this._onBeforeRenderCallbacks[callbackIndex]();
  9360. }
  9361. // Animations
  9362. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9363. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9364. this._animate();
  9365. // Physics
  9366. if (this._physicsEngine) {
  9367. BABYLON.Tools.StartPerformanceCounter("Physics");
  9368. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9369. BABYLON.Tools.EndPerformanceCounter("Physics");
  9370. }
  9371. // Customs render targets
  9372. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9373. var engine = this.getEngine();
  9374. var currentActiveCamera = this.activeCamera;
  9375. if (this.renderTargetsEnabled) {
  9376. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9377. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9378. var renderTarget = this.customRenderTargets[customIndex];
  9379. if (renderTarget._shouldRender()) {
  9380. this._renderId++;
  9381. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9382. if (!this.activeCamera)
  9383. throw new Error("Active camera not set");
  9384. // Viewport
  9385. engine.setViewport(this.activeCamera.viewport);
  9386. // Camera
  9387. this.updateTransformMatrix();
  9388. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9389. }
  9390. }
  9391. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9392. this._renderId++;
  9393. }
  9394. if (this.customRenderTargets.length > 0) {
  9395. engine.restoreDefaultFramebuffer();
  9396. }
  9397. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9398. this.activeCamera = currentActiveCamera;
  9399. // Procedural textures
  9400. if (this.proceduralTexturesEnabled) {
  9401. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9402. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9403. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9404. if (proceduralTexture._shouldRender()) {
  9405. proceduralTexture.render();
  9406. }
  9407. }
  9408. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9409. }
  9410. // Clear
  9411. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9412. // Shadows
  9413. if (this.shadowsEnabled) {
  9414. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9415. var light = this.lights[lightIndex];
  9416. var shadowGenerator = light.getShadowGenerator();
  9417. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9418. this._renderTargets.push(shadowGenerator.getShadowMap());
  9419. }
  9420. }
  9421. }
  9422. // Depth renderer
  9423. if (this._depthRenderer) {
  9424. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9425. }
  9426. // RenderPipeline
  9427. this.postProcessRenderPipelineManager.update();
  9428. // Multi-cameras?
  9429. if (this.activeCameras.length > 0) {
  9430. var currentRenderId = this._renderId;
  9431. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9432. this._renderId = currentRenderId;
  9433. this._processSubCameras(this.activeCameras[cameraIndex]);
  9434. }
  9435. }
  9436. else {
  9437. if (!this.activeCamera) {
  9438. throw new Error("No camera defined");
  9439. }
  9440. this._processSubCameras(this.activeCamera);
  9441. }
  9442. // Intersection checks
  9443. this._checkIntersections();
  9444. // Update the audio listener attached to the camera
  9445. this._updateAudioParameters();
  9446. // After render
  9447. if (this.afterRender) {
  9448. this.afterRender();
  9449. }
  9450. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9451. this._onAfterRenderCallbacks[callbackIndex]();
  9452. }
  9453. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9454. this._toBeDisposed.data[index].dispose();
  9455. this._toBeDisposed[index] = null;
  9456. }
  9457. this._toBeDisposed.reset();
  9458. if (this.dumpNextRenderTargets) {
  9459. this.dumpNextRenderTargets = false;
  9460. }
  9461. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9462. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9463. };
  9464. Scene.prototype._updateAudioParameters = function () {
  9465. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9466. return;
  9467. }
  9468. var listeningCamera;
  9469. var audioEngine = BABYLON.Engine.audioEngine;
  9470. if (this.activeCameras.length > 0) {
  9471. listeningCamera = this.activeCameras[0];
  9472. }
  9473. else {
  9474. listeningCamera = this.activeCamera;
  9475. }
  9476. if (listeningCamera && audioEngine.canUseWebAudio) {
  9477. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9478. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9479. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9480. cameraDirection.normalize();
  9481. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9482. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9483. var sound = this.mainSoundTrack.soundCollection[i];
  9484. if (sound.useCustomAttenuation) {
  9485. sound.updateDistanceFromListener();
  9486. }
  9487. }
  9488. for (i = 0; i < this.soundTracks.length; i++) {
  9489. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9490. sound = this.soundTracks[i].soundCollection[j];
  9491. if (sound.useCustomAttenuation) {
  9492. sound.updateDistanceFromListener();
  9493. }
  9494. }
  9495. }
  9496. }
  9497. };
  9498. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9499. // Audio
  9500. get: function () {
  9501. return this._audioEnabled;
  9502. },
  9503. set: function (value) {
  9504. this._audioEnabled = value;
  9505. if (this._audioEnabled) {
  9506. this._enableAudio();
  9507. }
  9508. else {
  9509. this._disableAudio();
  9510. }
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Scene.prototype._disableAudio = function () {
  9516. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9517. this.mainSoundTrack.soundCollection[i].pause();
  9518. }
  9519. for (i = 0; i < this.soundTracks.length; i++) {
  9520. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9521. this.soundTracks[i].soundCollection[j].pause();
  9522. }
  9523. }
  9524. };
  9525. Scene.prototype._enableAudio = function () {
  9526. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9527. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9528. this.mainSoundTrack.soundCollection[i].play();
  9529. }
  9530. }
  9531. for (i = 0; i < this.soundTracks.length; i++) {
  9532. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9533. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9534. this.soundTracks[i].soundCollection[j].play();
  9535. }
  9536. }
  9537. }
  9538. };
  9539. Object.defineProperty(Scene.prototype, "headphone", {
  9540. get: function () {
  9541. return this._headphone;
  9542. },
  9543. set: function (value) {
  9544. this._headphone = value;
  9545. if (this._headphone) {
  9546. this._switchAudioModeForHeadphones();
  9547. }
  9548. else {
  9549. this._switchAudioModeForNormalSpeakers();
  9550. }
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Scene.prototype._switchAudioModeForHeadphones = function () {
  9556. this.mainSoundTrack.switchPanningModelToHRTF();
  9557. for (var i = 0; i < this.soundTracks.length; i++) {
  9558. this.soundTracks[i].switchPanningModelToHRTF();
  9559. }
  9560. };
  9561. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9562. this.mainSoundTrack.switchPanningModelToEqualPower();
  9563. for (var i = 0; i < this.soundTracks.length; i++) {
  9564. this.soundTracks[i].switchPanningModelToEqualPower();
  9565. }
  9566. };
  9567. Scene.prototype.enableDepthRenderer = function () {
  9568. if (this._depthRenderer) {
  9569. return this._depthRenderer;
  9570. }
  9571. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9572. return this._depthRenderer;
  9573. };
  9574. Scene.prototype.disableDepthRenderer = function () {
  9575. if (!this._depthRenderer) {
  9576. return;
  9577. }
  9578. this._depthRenderer.dispose();
  9579. this._depthRenderer = null;
  9580. };
  9581. Scene.prototype.dispose = function () {
  9582. this.beforeRender = null;
  9583. this.afterRender = null;
  9584. this.skeletons = [];
  9585. this._boundingBoxRenderer.dispose();
  9586. if (this._depthRenderer) {
  9587. this._depthRenderer.dispose();
  9588. }
  9589. // Debug layer
  9590. this.debugLayer.hide();
  9591. // Events
  9592. if (this.onDispose) {
  9593. this.onDispose();
  9594. }
  9595. this._onBeforeRenderCallbacks = [];
  9596. this._onAfterRenderCallbacks = [];
  9597. this.detachControl();
  9598. // Release sounds & sounds tracks
  9599. this.disposeSounds();
  9600. // Detach cameras
  9601. var canvas = this._engine.getRenderingCanvas();
  9602. var index;
  9603. for (index = 0; index < this.cameras.length; index++) {
  9604. this.cameras[index].detachControl(canvas);
  9605. }
  9606. while (this.lights.length) {
  9607. this.lights[0].dispose();
  9608. }
  9609. while (this.meshes.length) {
  9610. this.meshes[0].dispose(true);
  9611. }
  9612. while (this.cameras.length) {
  9613. this.cameras[0].dispose();
  9614. }
  9615. while (this.materials.length) {
  9616. this.materials[0].dispose();
  9617. }
  9618. while (this.particleSystems.length) {
  9619. this.particleSystems[0].dispose();
  9620. }
  9621. while (this.spriteManagers.length) {
  9622. this.spriteManagers[0].dispose();
  9623. }
  9624. while (this.layers.length) {
  9625. this.layers[0].dispose();
  9626. }
  9627. while (this.textures.length) {
  9628. this.textures[0].dispose();
  9629. }
  9630. // Post-processes
  9631. this.postProcessManager.dispose();
  9632. // Physics
  9633. if (this._physicsEngine) {
  9634. this.disablePhysicsEngine();
  9635. }
  9636. // Remove from engine
  9637. index = this._engine.scenes.indexOf(this);
  9638. if (index > -1) {
  9639. this._engine.scenes.splice(index, 1);
  9640. }
  9641. this._engine.wipeCaches();
  9642. };
  9643. // Release sounds & sounds tracks
  9644. Scene.prototype.disposeSounds = function () {
  9645. this.mainSoundTrack.dispose();
  9646. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9647. this.soundTracks[scIndex].dispose();
  9648. }
  9649. };
  9650. // Collisions
  9651. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9652. if (excludedMesh === void 0) { excludedMesh = null; }
  9653. position.divideToRef(collider.radius, this._scaledPosition);
  9654. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9655. collider.retry = 0;
  9656. collider.initialVelocity = this._scaledVelocity;
  9657. collider.initialPosition = this._scaledPosition;
  9658. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9659. finalPosition.multiplyInPlace(collider.radius);
  9660. };
  9661. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9662. if (excludedMesh === void 0) { excludedMesh = null; }
  9663. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9664. if (collider.retry >= maximumRetry) {
  9665. finalPosition.copyFrom(position);
  9666. return;
  9667. }
  9668. collider._initialize(position, velocity, closeDistance);
  9669. for (var index = 0; index < this.meshes.length; index++) {
  9670. var mesh = this.meshes[index];
  9671. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9672. mesh._checkCollision(collider);
  9673. }
  9674. }
  9675. if (!collider.collisionFound) {
  9676. position.addToRef(velocity, finalPosition);
  9677. return;
  9678. }
  9679. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9680. collider._getResponse(position, velocity);
  9681. }
  9682. if (velocity.length() <= closeDistance) {
  9683. finalPosition.copyFrom(position);
  9684. return;
  9685. }
  9686. collider.retry++;
  9687. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9688. };
  9689. // Octrees
  9690. Scene.prototype.getWorldExtends = function () {
  9691. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9692. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9693. for (var index = 0; index < this.meshes.length; index++) {
  9694. var mesh = this.meshes[index];
  9695. mesh.computeWorldMatrix(true);
  9696. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9697. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9698. BABYLON.Tools.CheckExtends(minBox, min, max);
  9699. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9700. }
  9701. return {
  9702. min: min,
  9703. max: max
  9704. };
  9705. };
  9706. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9707. if (maxCapacity === void 0) { maxCapacity = 64; }
  9708. if (maxDepth === void 0) { maxDepth = 2; }
  9709. if (!this._selectionOctree) {
  9710. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9711. }
  9712. var worldExtends = this.getWorldExtends();
  9713. // Update octree
  9714. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9715. return this._selectionOctree;
  9716. };
  9717. // Picking
  9718. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9719. var engine = this._engine;
  9720. if (!camera) {
  9721. if (!this.activeCamera)
  9722. throw new Error("Active camera not set");
  9723. camera = this.activeCamera;
  9724. }
  9725. var cameraViewport = camera.viewport;
  9726. var viewport = cameraViewport.toGlobal(engine);
  9727. // Moving coordinates to local viewport world
  9728. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9729. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9730. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9731. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9732. };
  9733. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9734. var pickingInfo = null;
  9735. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9736. var mesh = this.meshes[meshIndex];
  9737. if (predicate) {
  9738. if (!predicate(mesh)) {
  9739. continue;
  9740. }
  9741. }
  9742. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9743. continue;
  9744. }
  9745. var world = mesh.getWorldMatrix();
  9746. var ray = rayFunction(world);
  9747. var result = mesh.intersects(ray, fastCheck);
  9748. if (!result || !result.hit)
  9749. continue;
  9750. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9751. continue;
  9752. pickingInfo = result;
  9753. if (fastCheck) {
  9754. break;
  9755. }
  9756. }
  9757. return pickingInfo || new BABYLON.PickingInfo();
  9758. };
  9759. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9760. var _this = this;
  9761. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9762. /// <param name="x">X position on screen</param>
  9763. /// <param name="y">Y position on screen</param>
  9764. /// <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>
  9765. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9766. /// <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>
  9767. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9768. };
  9769. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9770. var _this = this;
  9771. return this._internalPick(function (world) {
  9772. if (!_this._pickWithRayInverseMatrix) {
  9773. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9774. }
  9775. world.invertToRef(_this._pickWithRayInverseMatrix);
  9776. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9777. }, predicate, fastCheck);
  9778. };
  9779. Scene.prototype.setPointerOverMesh = function (mesh) {
  9780. if (this._pointerOverMesh === mesh) {
  9781. return;
  9782. }
  9783. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9784. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9785. }
  9786. this._pointerOverMesh = mesh;
  9787. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9788. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9789. }
  9790. };
  9791. Scene.prototype.getPointerOverMesh = function () {
  9792. return this._pointerOverMesh;
  9793. };
  9794. // Physics
  9795. Scene.prototype.getPhysicsEngine = function () {
  9796. return this._physicsEngine;
  9797. };
  9798. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9799. if (this._physicsEngine) {
  9800. return true;
  9801. }
  9802. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9803. if (!this._physicsEngine.isSupported()) {
  9804. this._physicsEngine = null;
  9805. return false;
  9806. }
  9807. this._physicsEngine._initialize(gravity);
  9808. return true;
  9809. };
  9810. Scene.prototype.disablePhysicsEngine = function () {
  9811. if (!this._physicsEngine) {
  9812. return;
  9813. }
  9814. this._physicsEngine.dispose();
  9815. this._physicsEngine = undefined;
  9816. };
  9817. Scene.prototype.isPhysicsEnabled = function () {
  9818. return this._physicsEngine !== undefined;
  9819. };
  9820. Scene.prototype.setGravity = function (gravity) {
  9821. if (!this._physicsEngine) {
  9822. return;
  9823. }
  9824. this._physicsEngine._setGravity(gravity);
  9825. };
  9826. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9827. if (parts.parts) {
  9828. options = parts;
  9829. parts = parts.parts;
  9830. }
  9831. if (!this._physicsEngine) {
  9832. return null;
  9833. }
  9834. for (var index = 0; index < parts.length; index++) {
  9835. var mesh = parts[index].mesh;
  9836. mesh._physicImpostor = parts[index].impostor;
  9837. mesh._physicsMass = options.mass / parts.length;
  9838. mesh._physicsFriction = options.friction;
  9839. mesh._physicRestitution = options.restitution;
  9840. }
  9841. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9842. };
  9843. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9844. for (var index = 0; index < compound.parts.length; index++) {
  9845. var mesh = compound.parts[index].mesh;
  9846. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9847. this._physicsEngine._unregisterMesh(mesh);
  9848. }
  9849. };
  9850. // Misc.
  9851. Scene.prototype.createDefaultCameraOrLight = function () {
  9852. // Light
  9853. if (this.lights.length === 0) {
  9854. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9855. }
  9856. // Camera
  9857. if (!this.activeCamera) {
  9858. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9859. // Compute position
  9860. var worldExtends = this.getWorldExtends();
  9861. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9862. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9863. camera.setTarget(worldCenter);
  9864. this.activeCamera = camera;
  9865. }
  9866. };
  9867. // Tags
  9868. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9869. if (tagsQuery === undefined) {
  9870. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9871. return list;
  9872. }
  9873. var listByTags = [];
  9874. forEach = forEach || (function (item) {
  9875. return;
  9876. });
  9877. for (var i in list) {
  9878. var item = list[i];
  9879. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9880. listByTags.push(item);
  9881. forEach(item);
  9882. }
  9883. }
  9884. return listByTags;
  9885. };
  9886. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9887. return this._getByTags(this.meshes, tagsQuery, forEach);
  9888. };
  9889. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9890. return this._getByTags(this.cameras, tagsQuery, forEach);
  9891. };
  9892. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9893. return this._getByTags(this.lights, tagsQuery, forEach);
  9894. };
  9895. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9896. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9897. };
  9898. // Statics
  9899. Scene._FOGMODE_NONE = 0;
  9900. Scene._FOGMODE_EXP = 1;
  9901. Scene._FOGMODE_EXP2 = 2;
  9902. Scene._FOGMODE_LINEAR = 3;
  9903. Scene.MinDeltaTime = 1.0;
  9904. Scene.MaxDeltaTime = 1000.0;
  9905. return Scene;
  9906. })();
  9907. BABYLON.Scene = Scene;
  9908. })(BABYLON || (BABYLON = {}));
  9909. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9910. (function (BABYLON) {
  9911. var VertexBuffer = (function () {
  9912. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9913. if (engine instanceof BABYLON.Mesh) {
  9914. this._engine = engine.getScene().getEngine();
  9915. }
  9916. else {
  9917. this._engine = engine;
  9918. }
  9919. this._updatable = updatable;
  9920. this._data = data;
  9921. if (!postponeInternalCreation) {
  9922. this.create();
  9923. }
  9924. this._kind = kind;
  9925. if (stride) {
  9926. this._strideSize = stride;
  9927. return;
  9928. }
  9929. switch (kind) {
  9930. case VertexBuffer.PositionKind:
  9931. this._strideSize = 3;
  9932. break;
  9933. case VertexBuffer.NormalKind:
  9934. this._strideSize = 3;
  9935. break;
  9936. case VertexBuffer.UVKind:
  9937. this._strideSize = 2;
  9938. break;
  9939. case VertexBuffer.UV2Kind:
  9940. this._strideSize = 2;
  9941. break;
  9942. case VertexBuffer.ColorKind:
  9943. this._strideSize = 4;
  9944. break;
  9945. case VertexBuffer.MatricesIndicesKind:
  9946. this._strideSize = 4;
  9947. break;
  9948. case VertexBuffer.MatricesWeightsKind:
  9949. this._strideSize = 4;
  9950. break;
  9951. }
  9952. }
  9953. // Properties
  9954. VertexBuffer.prototype.isUpdatable = function () {
  9955. return this._updatable;
  9956. };
  9957. VertexBuffer.prototype.getData = function () {
  9958. return this._data;
  9959. };
  9960. VertexBuffer.prototype.getBuffer = function () {
  9961. return this._buffer;
  9962. };
  9963. VertexBuffer.prototype.getStrideSize = function () {
  9964. return this._strideSize;
  9965. };
  9966. // Methods
  9967. VertexBuffer.prototype.create = function (data) {
  9968. if (!data && this._buffer) {
  9969. return; // nothing to do
  9970. }
  9971. data = data || this._data;
  9972. if (!this._buffer) {
  9973. if (this._updatable) {
  9974. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9975. }
  9976. else {
  9977. this._buffer = this._engine.createVertexBuffer(data);
  9978. }
  9979. }
  9980. if (this._updatable) {
  9981. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9982. this._data = data;
  9983. }
  9984. };
  9985. VertexBuffer.prototype.update = function (data) {
  9986. this.create(data);
  9987. };
  9988. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9989. if (!this._buffer) {
  9990. return;
  9991. }
  9992. if (this._updatable) {
  9993. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9994. this._data = null;
  9995. }
  9996. };
  9997. VertexBuffer.prototype.dispose = function () {
  9998. if (!this._buffer) {
  9999. return;
  10000. }
  10001. if (this._engine._releaseBuffer(this._buffer)) {
  10002. this._buffer = null;
  10003. }
  10004. };
  10005. Object.defineProperty(VertexBuffer, "PositionKind", {
  10006. get: function () {
  10007. return VertexBuffer._PositionKind;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Object.defineProperty(VertexBuffer, "NormalKind", {
  10013. get: function () {
  10014. return VertexBuffer._NormalKind;
  10015. },
  10016. enumerable: true,
  10017. configurable: true
  10018. });
  10019. Object.defineProperty(VertexBuffer, "UVKind", {
  10020. get: function () {
  10021. return VertexBuffer._UVKind;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10027. get: function () {
  10028. return VertexBuffer._UV2Kind;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Object.defineProperty(VertexBuffer, "ColorKind", {
  10034. get: function () {
  10035. return VertexBuffer._ColorKind;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10041. get: function () {
  10042. return VertexBuffer._MatricesIndicesKind;
  10043. },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10048. get: function () {
  10049. return VertexBuffer._MatricesWeightsKind;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. // Enums
  10055. VertexBuffer._PositionKind = "position";
  10056. VertexBuffer._NormalKind = "normal";
  10057. VertexBuffer._UVKind = "uv";
  10058. VertexBuffer._UV2Kind = "uv2";
  10059. VertexBuffer._ColorKind = "color";
  10060. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10061. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10062. return VertexBuffer;
  10063. })();
  10064. BABYLON.VertexBuffer = VertexBuffer;
  10065. })(BABYLON || (BABYLON = {}));
  10066. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10067. var BABYLON;
  10068. (function (BABYLON) {
  10069. var AbstractMesh = (function (_super) {
  10070. __extends(AbstractMesh, _super);
  10071. function AbstractMesh(name, scene) {
  10072. _super.call(this, name, scene);
  10073. // Properties
  10074. this.definedFacingForward = true; // orientation for POV movement & rotation
  10075. this.position = new BABYLON.Vector3(0, 0, 0);
  10076. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10077. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10078. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10079. this.visibility = 1.0;
  10080. this.alphaIndex = Number.MAX_VALUE;
  10081. this.infiniteDistance = false;
  10082. this.isVisible = true;
  10083. this.isPickable = true;
  10084. this.showBoundingBox = false;
  10085. this.showSubMeshesBoundingBox = false;
  10086. this.onDispose = null;
  10087. this.checkCollisions = false;
  10088. this.isBlocker = false;
  10089. this.renderingGroupId = 0;
  10090. this.receiveShadows = false;
  10091. this.renderOutline = false;
  10092. this.outlineColor = BABYLON.Color3.Red();
  10093. this.outlineWidth = 0.02;
  10094. this.renderOverlay = false;
  10095. this.overlayColor = BABYLON.Color3.Red();
  10096. this.overlayAlpha = 0.5;
  10097. this.hasVertexAlpha = false;
  10098. this.useVertexColors = true;
  10099. this.applyFog = true;
  10100. this.useOctreeForRenderingSelection = true;
  10101. this.useOctreeForPicking = true;
  10102. this.useOctreeForCollisions = true;
  10103. this.layerMask = 0x0FFFFFFF;
  10104. // Physics
  10105. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10106. // Collisions
  10107. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10108. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10109. this._collider = new BABYLON.Collider();
  10110. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10111. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10112. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10113. // Cache
  10114. this._localScaling = BABYLON.Matrix.Zero();
  10115. this._localRotation = BABYLON.Matrix.Zero();
  10116. this._localTranslation = BABYLON.Matrix.Zero();
  10117. this._localBillboard = BABYLON.Matrix.Zero();
  10118. this._localPivotScaling = BABYLON.Matrix.Zero();
  10119. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10120. this._localWorld = BABYLON.Matrix.Zero();
  10121. this._worldMatrix = BABYLON.Matrix.Zero();
  10122. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10123. this._absolutePosition = BABYLON.Vector3.Zero();
  10124. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10125. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10126. this._isDirty = false;
  10127. this._pivotMatrix = BABYLON.Matrix.Identity();
  10128. this._isDisposed = false;
  10129. this._renderId = 0;
  10130. this._intersectionsInProgress = new Array();
  10131. this._onAfterWorldMatrixUpdate = new Array();
  10132. scene.addMesh(this);
  10133. }
  10134. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10135. get: function () {
  10136. return AbstractMesh._BILLBOARDMODE_NONE;
  10137. },
  10138. enumerable: true,
  10139. configurable: true
  10140. });
  10141. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10142. get: function () {
  10143. return AbstractMesh._BILLBOARDMODE_X;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10149. get: function () {
  10150. return AbstractMesh._BILLBOARDMODE_Y;
  10151. },
  10152. enumerable: true,
  10153. configurable: true
  10154. });
  10155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10156. get: function () {
  10157. return AbstractMesh._BILLBOARDMODE_Z;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10163. get: function () {
  10164. return AbstractMesh._BILLBOARDMODE_ALL;
  10165. },
  10166. enumerable: true,
  10167. configurable: true
  10168. });
  10169. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10170. // Methods
  10171. get: function () {
  10172. return false;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. AbstractMesh.prototype.getLOD = function (camera) {
  10178. return this;
  10179. };
  10180. AbstractMesh.prototype.getTotalVertices = function () {
  10181. return 0;
  10182. };
  10183. AbstractMesh.prototype.getIndices = function () {
  10184. return null;
  10185. };
  10186. AbstractMesh.prototype.getVerticesData = function (kind) {
  10187. return null;
  10188. };
  10189. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10190. return false;
  10191. };
  10192. AbstractMesh.prototype.getBoundingInfo = function () {
  10193. if (this._masterMesh) {
  10194. return this._masterMesh.getBoundingInfo();
  10195. }
  10196. if (!this._boundingInfo) {
  10197. this._updateBoundingInfo();
  10198. }
  10199. return this._boundingInfo;
  10200. };
  10201. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10202. get: function () {
  10203. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. AbstractMesh.prototype._preActivate = function () {
  10209. };
  10210. AbstractMesh.prototype._activate = function (renderId) {
  10211. this._renderId = renderId;
  10212. };
  10213. AbstractMesh.prototype.getWorldMatrix = function () {
  10214. if (this._masterMesh) {
  10215. return this._masterMesh.getWorldMatrix();
  10216. }
  10217. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10218. this.computeWorldMatrix();
  10219. }
  10220. return this._worldMatrix;
  10221. };
  10222. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10223. get: function () {
  10224. return this._worldMatrix;
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10230. get: function () {
  10231. return this._absolutePosition;
  10232. },
  10233. enumerable: true,
  10234. configurable: true
  10235. });
  10236. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10237. if (!this.rotationQuaternion) {
  10238. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10239. this.rotation = BABYLON.Vector3.Zero();
  10240. }
  10241. if (!space || space === 0 /* LOCAL */) {
  10242. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10243. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10244. }
  10245. else {
  10246. if (this.parent) {
  10247. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10248. invertParentWorldMatrix.invert();
  10249. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10250. }
  10251. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10252. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10253. }
  10254. };
  10255. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10256. var displacementVector = axis.scale(distance);
  10257. if (!space || space === 0 /* LOCAL */) {
  10258. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10259. this.setPositionWithLocalVector(tempV3);
  10260. }
  10261. else {
  10262. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10263. }
  10264. };
  10265. AbstractMesh.prototype.getAbsolutePosition = function () {
  10266. this.computeWorldMatrix();
  10267. return this._absolutePosition;
  10268. };
  10269. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10270. if (!absolutePosition) {
  10271. return;
  10272. }
  10273. var absolutePositionX;
  10274. var absolutePositionY;
  10275. var absolutePositionZ;
  10276. if (absolutePosition.x === undefined) {
  10277. if (arguments.length < 3) {
  10278. return;
  10279. }
  10280. absolutePositionX = arguments[0];
  10281. absolutePositionY = arguments[1];
  10282. absolutePositionZ = arguments[2];
  10283. }
  10284. else {
  10285. absolutePositionX = absolutePosition.x;
  10286. absolutePositionY = absolutePosition.y;
  10287. absolutePositionZ = absolutePosition.z;
  10288. }
  10289. if (this.parent) {
  10290. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10291. invertParentWorldMatrix.invert();
  10292. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10293. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10294. }
  10295. else {
  10296. this.position.x = absolutePositionX;
  10297. this.position.y = absolutePositionY;
  10298. this.position.z = absolutePositionZ;
  10299. }
  10300. };
  10301. // ================================== Point of View Movement =================================
  10302. /**
  10303. * Perform relative position change from the point of view of behind the front of the mesh.
  10304. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10305. * Supports definition of mesh facing forward or backward.
  10306. * @param {number} amountRight
  10307. * @param {number} amountUp
  10308. * @param {number} amountForward
  10309. */
  10310. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10311. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10312. };
  10313. /**
  10314. * Calculate relative position change from the point of view of behind the front of the mesh.
  10315. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10316. * Supports definition of mesh facing forward or backward.
  10317. * @param {number} amountRight
  10318. * @param {number} amountUp
  10319. * @param {number} amountForward
  10320. */
  10321. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10322. var rotMatrix = new BABYLON.Matrix();
  10323. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10324. rotQuaternion.toRotationMatrix(rotMatrix);
  10325. var translationDelta = BABYLON.Vector3.Zero();
  10326. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10327. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10328. return translationDelta;
  10329. };
  10330. // ================================== Point of View Rotation =================================
  10331. /**
  10332. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10333. * Supports definition of mesh facing forward or backward.
  10334. * @param {number} flipBack
  10335. * @param {number} twirlClockwise
  10336. * @param {number} tiltRight
  10337. */
  10338. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10339. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10340. };
  10341. /**
  10342. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10343. * Supports definition of mesh facing forward or backward.
  10344. * @param {number} flipBack
  10345. * @param {number} twirlClockwise
  10346. * @param {number} tiltRight
  10347. */
  10348. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10349. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10350. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10351. };
  10352. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10353. this._pivotMatrix = matrix;
  10354. this._cache.pivotMatrixUpdated = true;
  10355. };
  10356. AbstractMesh.prototype.getPivotMatrix = function () {
  10357. return this._pivotMatrix;
  10358. };
  10359. AbstractMesh.prototype._isSynchronized = function () {
  10360. if (this._isDirty) {
  10361. return false;
  10362. }
  10363. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10364. return false;
  10365. if (this._cache.pivotMatrixUpdated) {
  10366. return false;
  10367. }
  10368. if (this.infiniteDistance) {
  10369. return false;
  10370. }
  10371. if (!this._cache.position.equals(this.position))
  10372. return false;
  10373. if (this.rotationQuaternion) {
  10374. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10375. return false;
  10376. }
  10377. else {
  10378. if (!this._cache.rotation.equals(this.rotation))
  10379. return false;
  10380. }
  10381. if (!this._cache.scaling.equals(this.scaling))
  10382. return false;
  10383. return true;
  10384. };
  10385. AbstractMesh.prototype._initCache = function () {
  10386. _super.prototype._initCache.call(this);
  10387. this._cache.localMatrixUpdated = false;
  10388. this._cache.position = BABYLON.Vector3.Zero();
  10389. this._cache.scaling = BABYLON.Vector3.Zero();
  10390. this._cache.rotation = BABYLON.Vector3.Zero();
  10391. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10392. };
  10393. AbstractMesh.prototype.markAsDirty = function (property) {
  10394. if (property === "rotation") {
  10395. this.rotationQuaternion = null;
  10396. }
  10397. this._currentRenderId = Number.MAX_VALUE;
  10398. this._isDirty = true;
  10399. };
  10400. AbstractMesh.prototype._updateBoundingInfo = function () {
  10401. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10402. this._boundingInfo._update(this.worldMatrixFromCache);
  10403. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10404. };
  10405. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10406. if (!this.subMeshes) {
  10407. return;
  10408. }
  10409. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10410. var subMesh = this.subMeshes[subIndex];
  10411. subMesh.updateBoundingInfo(matrix);
  10412. }
  10413. };
  10414. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10415. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10416. return this._worldMatrix;
  10417. }
  10418. this._cache.position.copyFrom(this.position);
  10419. this._cache.scaling.copyFrom(this.scaling);
  10420. this._cache.pivotMatrixUpdated = false;
  10421. this._currentRenderId = this.getScene().getRenderId();
  10422. this._isDirty = false;
  10423. // Scaling
  10424. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10425. // Rotation
  10426. if (this.rotationQuaternion) {
  10427. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10428. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10429. }
  10430. else {
  10431. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10432. this._cache.rotation.copyFrom(this.rotation);
  10433. }
  10434. // Translation
  10435. if (this.infiniteDistance && !this.parent) {
  10436. var camera = this.getScene().activeCamera;
  10437. var cameraWorldMatrix = camera.getWorldMatrix();
  10438. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10439. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10440. }
  10441. else {
  10442. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10443. }
  10444. // Composing transformations
  10445. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10446. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10447. // Billboarding
  10448. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10449. var localPosition = this.position.clone();
  10450. var zero = this.getScene().activeCamera.globalPosition.clone();
  10451. if (this.parent && this.parent.position) {
  10452. localPosition.addInPlace(this.parent.position);
  10453. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10454. }
  10455. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  10456. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10457. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10458. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10459. zero.y = localPosition.y + 0.001;
  10460. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10461. zero.z = localPosition.z + 0.001;
  10462. }
  10463. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10464. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10465. this._localBillboard.invert();
  10466. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10467. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10468. }
  10469. // Local world
  10470. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10471. // Parent
  10472. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10473. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10474. }
  10475. else {
  10476. this._worldMatrix.copyFrom(this._localWorld);
  10477. }
  10478. // Bounding info
  10479. this._updateBoundingInfo();
  10480. // Absolute position
  10481. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10482. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10483. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10484. }
  10485. return this._worldMatrix;
  10486. };
  10487. /**
  10488. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10489. * @param func: callback function to add
  10490. */
  10491. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10492. this._onAfterWorldMatrixUpdate.push(func);
  10493. };
  10494. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10495. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10496. if (index > -1) {
  10497. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10498. }
  10499. };
  10500. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10501. this.computeWorldMatrix();
  10502. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10503. };
  10504. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10505. this.computeWorldMatrix();
  10506. var invLocalWorldMatrix = this._localWorld.clone();
  10507. invLocalWorldMatrix.invert();
  10508. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10509. };
  10510. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10511. this.computeWorldMatrix();
  10512. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10513. };
  10514. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10515. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10516. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10517. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10518. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10519. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10520. /// <returns>Mesh oriented towards targetMesh</returns>
  10521. yawCor = yawCor || 0; // default to zero if undefined
  10522. pitchCor = pitchCor || 0;
  10523. rollCor = rollCor || 0;
  10524. var dv = targetPoint.subtract(this.position);
  10525. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10526. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10527. var pitch = Math.atan2(dv.y, len);
  10528. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10529. };
  10530. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10531. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10532. return false;
  10533. }
  10534. return true;
  10535. };
  10536. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10537. if (!camera) {
  10538. camera = this.getScene().activeCamera;
  10539. }
  10540. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10541. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10542. return false;
  10543. }
  10544. return true;
  10545. };
  10546. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10547. if (!this._boundingInfo || !mesh._boundingInfo) {
  10548. return false;
  10549. }
  10550. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10551. };
  10552. AbstractMesh.prototype.intersectsPoint = function (point) {
  10553. if (!this._boundingInfo) {
  10554. return false;
  10555. }
  10556. return this._boundingInfo.intersectsPoint(point);
  10557. };
  10558. // Physics
  10559. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10560. var physicsEngine = this.getScene().getPhysicsEngine();
  10561. if (!physicsEngine) {
  10562. return;
  10563. }
  10564. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10565. if (impostor.impostor) {
  10566. // Old API
  10567. options = impostor;
  10568. impostor = impostor.impostor;
  10569. }
  10570. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10571. physicsEngine._unregisterMesh(this);
  10572. return;
  10573. }
  10574. if (!options) {
  10575. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10576. }
  10577. else {
  10578. if (!options.mass && options.mass !== 0)
  10579. options.mass = 0;
  10580. if (!options.friction && options.friction !== 0)
  10581. options.friction = 0.2;
  10582. if (!options.restitution && options.restitution !== 0)
  10583. options.restitution = 0.2;
  10584. }
  10585. this._physicImpostor = impostor;
  10586. this._physicsMass = options.mass;
  10587. this._physicsFriction = options.friction;
  10588. this._physicRestitution = options.restitution;
  10589. return physicsEngine._registerMesh(this, impostor, options);
  10590. };
  10591. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10592. if (!this._physicImpostor) {
  10593. return BABYLON.PhysicsEngine.NoImpostor;
  10594. }
  10595. return this._physicImpostor;
  10596. };
  10597. AbstractMesh.prototype.getPhysicsMass = function () {
  10598. if (!this._physicsMass) {
  10599. return 0;
  10600. }
  10601. return this._physicsMass;
  10602. };
  10603. AbstractMesh.prototype.getPhysicsFriction = function () {
  10604. if (!this._physicsFriction) {
  10605. return 0;
  10606. }
  10607. return this._physicsFriction;
  10608. };
  10609. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10610. if (!this._physicRestitution) {
  10611. return 0;
  10612. }
  10613. return this._physicRestitution;
  10614. };
  10615. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10616. if (!camera) {
  10617. camera = this.getScene().activeCamera;
  10618. }
  10619. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10620. };
  10621. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10622. if (!camera) {
  10623. camera = this.getScene().activeCamera;
  10624. }
  10625. return this.absolutePosition.subtract(camera.position).length();
  10626. };
  10627. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10628. if (!this._physicImpostor) {
  10629. return;
  10630. }
  10631. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10632. };
  10633. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10634. if (!this._physicImpostor) {
  10635. return;
  10636. }
  10637. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10638. };
  10639. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10640. if (!this._physicImpostor) {
  10641. return;
  10642. }
  10643. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10644. };
  10645. // Collisions
  10646. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10647. var globalPosition = this.getAbsolutePosition();
  10648. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10649. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10650. this._collider.radius = this.ellipsoid;
  10651. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10652. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10653. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10654. this.position.addInPlace(this._diffPositionForCollisions);
  10655. }
  10656. };
  10657. // Submeshes octree
  10658. /**
  10659. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10660. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10661. */
  10662. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10663. if (maxCapacity === void 0) { maxCapacity = 64; }
  10664. if (maxDepth === void 0) { maxDepth = 2; }
  10665. if (!this._submeshesOctree) {
  10666. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10667. }
  10668. this.computeWorldMatrix(true);
  10669. // Update octree
  10670. var bbox = this.getBoundingInfo().boundingBox;
  10671. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10672. return this._submeshesOctree;
  10673. };
  10674. // Collisions
  10675. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10676. this._generatePointsArray();
  10677. // Transformation
  10678. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10679. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10680. subMesh._lastColliderWorldVertices = [];
  10681. subMesh._trianglePlanes = [];
  10682. var start = subMesh.verticesStart;
  10683. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10684. for (var i = start; i < end; i++) {
  10685. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10686. }
  10687. }
  10688. // Collide
  10689. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10690. };
  10691. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10692. var subMeshes;
  10693. var len;
  10694. // Octrees
  10695. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10696. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10697. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10698. len = intersections.length;
  10699. subMeshes = intersections.data;
  10700. }
  10701. else {
  10702. subMeshes = this.subMeshes;
  10703. len = subMeshes.length;
  10704. }
  10705. for (var index = 0; index < len; index++) {
  10706. var subMesh = subMeshes[index];
  10707. // Bounding test
  10708. if (len > 1 && !subMesh._checkCollision(collider))
  10709. continue;
  10710. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10711. }
  10712. };
  10713. AbstractMesh.prototype._checkCollision = function (collider) {
  10714. // Bounding box test
  10715. if (!this._boundingInfo._checkCollision(collider))
  10716. return;
  10717. // Transformation matrix
  10718. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10719. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10720. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10721. };
  10722. // Picking
  10723. AbstractMesh.prototype._generatePointsArray = function () {
  10724. return false;
  10725. };
  10726. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10727. var pickingInfo = new BABYLON.PickingInfo();
  10728. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10729. return pickingInfo;
  10730. }
  10731. if (!this._generatePointsArray()) {
  10732. return pickingInfo;
  10733. }
  10734. var intersectInfo = null;
  10735. // Octrees
  10736. var subMeshes;
  10737. var len;
  10738. if (this._submeshesOctree && this.useOctreeForPicking) {
  10739. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10740. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10741. len = intersections.length;
  10742. subMeshes = intersections.data;
  10743. }
  10744. else {
  10745. subMeshes = this.subMeshes;
  10746. len = subMeshes.length;
  10747. }
  10748. for (var index = 0; index < len; index++) {
  10749. var subMesh = subMeshes[index];
  10750. // Bounding test
  10751. if (len > 1 && !subMesh.canIntersects(ray))
  10752. continue;
  10753. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10754. if (currentIntersectInfo) {
  10755. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10756. intersectInfo = currentIntersectInfo;
  10757. intersectInfo.subMeshId = index;
  10758. if (fastCheck) {
  10759. break;
  10760. }
  10761. }
  10762. }
  10763. }
  10764. if (intersectInfo) {
  10765. // Get picked point
  10766. var world = this.getWorldMatrix();
  10767. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10768. var direction = ray.direction.clone();
  10769. direction = direction.scale(intersectInfo.distance);
  10770. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10771. var pickedPoint = worldOrigin.add(worldDirection);
  10772. // Return result
  10773. pickingInfo.hit = true;
  10774. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10775. pickingInfo.pickedPoint = pickedPoint;
  10776. pickingInfo.pickedMesh = this;
  10777. pickingInfo.bu = intersectInfo.bu;
  10778. pickingInfo.bv = intersectInfo.bv;
  10779. pickingInfo.faceId = intersectInfo.faceId;
  10780. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10781. return pickingInfo;
  10782. }
  10783. return pickingInfo;
  10784. };
  10785. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10786. return null;
  10787. };
  10788. AbstractMesh.prototype.releaseSubMeshes = function () {
  10789. if (this.subMeshes) {
  10790. while (this.subMeshes.length) {
  10791. this.subMeshes[0].dispose();
  10792. }
  10793. }
  10794. else {
  10795. this.subMeshes = new Array();
  10796. }
  10797. };
  10798. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10799. var index;
  10800. // Physics
  10801. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10802. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10803. }
  10804. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10805. var other = this._intersectionsInProgress[index];
  10806. var pos = other._intersectionsInProgress.indexOf(this);
  10807. other._intersectionsInProgress.splice(pos, 1);
  10808. }
  10809. this._intersectionsInProgress = [];
  10810. // SubMeshes
  10811. this.releaseSubMeshes();
  10812. // Remove from scene
  10813. this.getScene().removeMesh(this);
  10814. if (!doNotRecurse) {
  10815. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10816. if (this.getScene().particleSystems[index].emitter === this) {
  10817. this.getScene().particleSystems[index].dispose();
  10818. index--;
  10819. }
  10820. }
  10821. // Children
  10822. var objects = this.getScene().meshes.slice(0);
  10823. for (index = 0; index < objects.length; index++) {
  10824. if (objects[index].parent === this) {
  10825. objects[index].dispose();
  10826. }
  10827. }
  10828. }
  10829. else {
  10830. for (index = 0; index < this.getScene().meshes.length; index++) {
  10831. var obj = this.getScene().meshes[index];
  10832. if (obj.parent === this) {
  10833. obj.parent = null;
  10834. obj.computeWorldMatrix(true);
  10835. }
  10836. }
  10837. }
  10838. this._onAfterWorldMatrixUpdate = [];
  10839. this._isDisposed = true;
  10840. // Callback
  10841. if (this.onDispose) {
  10842. this.onDispose();
  10843. }
  10844. };
  10845. // Statics
  10846. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10847. AbstractMesh._BILLBOARDMODE_X = 1;
  10848. AbstractMesh._BILLBOARDMODE_Y = 2;
  10849. AbstractMesh._BILLBOARDMODE_Z = 4;
  10850. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10851. return AbstractMesh;
  10852. })(BABYLON.Node);
  10853. BABYLON.AbstractMesh = AbstractMesh;
  10854. })(BABYLON || (BABYLON = {}));
  10855. //# sourceMappingURL=babylon.abstractMesh.js.map
  10856. var BABYLON;
  10857. (function (BABYLON) {
  10858. var _InstancesBatch = (function () {
  10859. function _InstancesBatch() {
  10860. this.mustReturn = false;
  10861. this.visibleInstances = new Array();
  10862. this.renderSelf = new Array();
  10863. }
  10864. return _InstancesBatch;
  10865. })();
  10866. BABYLON._InstancesBatch = _InstancesBatch;
  10867. var Mesh = (function (_super) {
  10868. __extends(Mesh, _super);
  10869. /**
  10870. * @constructor
  10871. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10872. * @param {Scene} scene - The scene to add this mesh to.
  10873. * @param {Node} parent - The parent of this mesh, if it has one
  10874. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10875. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10876. * When false, achieved by calling a clone(), also passing False.
  10877. * This will make creation of children, recursive.
  10878. */
  10879. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10880. if (parent === void 0) { parent = null; }
  10881. _super.call(this, name, scene);
  10882. // Members
  10883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10884. this.instances = new Array();
  10885. this._LODLevels = new Array();
  10886. this._onBeforeRenderCallbacks = new Array();
  10887. this._onAfterRenderCallbacks = new Array();
  10888. this._visibleInstances = {};
  10889. this._renderIdForInstances = new Array();
  10890. this._batchCache = new _InstancesBatch();
  10891. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10892. this._sideOrientation = Mesh._DEFAULTSIDE;
  10893. if (source) {
  10894. // Geometry
  10895. if (source._geometry) {
  10896. source._geometry.applyToMesh(this);
  10897. }
  10898. // Deep copy
  10899. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10900. // Material
  10901. this.material = source.material;
  10902. if (!doNotCloneChildren) {
  10903. for (var index = 0; index < scene.meshes.length; index++) {
  10904. var mesh = scene.meshes[index];
  10905. if (mesh.parent === source) {
  10906. // doNotCloneChildren is always going to be False
  10907. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10908. }
  10909. }
  10910. }
  10911. for (index = 0; index < scene.particleSystems.length; index++) {
  10912. var system = scene.particleSystems[index];
  10913. if (system.emitter === source) {
  10914. system.clone(system.name, this);
  10915. }
  10916. }
  10917. this.computeWorldMatrix(true);
  10918. }
  10919. // Parent
  10920. if (parent !== null) {
  10921. this.parent = parent;
  10922. }
  10923. }
  10924. Object.defineProperty(Mesh, "FRONTSIDE", {
  10925. get: function () {
  10926. return Mesh._FRONTSIDE;
  10927. },
  10928. enumerable: true,
  10929. configurable: true
  10930. });
  10931. Object.defineProperty(Mesh, "BACKSIDE", {
  10932. get: function () {
  10933. return Mesh._BACKSIDE;
  10934. },
  10935. enumerable: true,
  10936. configurable: true
  10937. });
  10938. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10939. get: function () {
  10940. return Mesh._DOUBLESIDE;
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10946. get: function () {
  10947. return Mesh._DEFAULTSIDE;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10953. // Methods
  10954. get: function () {
  10955. return this._LODLevels.length > 0;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Mesh.prototype._sortLODLevels = function () {
  10961. this._LODLevels.sort(function (a, b) {
  10962. if (a.distance < b.distance) {
  10963. return 1;
  10964. }
  10965. if (a.distance > b.distance) {
  10966. return -1;
  10967. }
  10968. return 0;
  10969. });
  10970. };
  10971. /**
  10972. * Add a mesh as LOD level triggered at the given distance.
  10973. * @param {number} distance - the distance from the center of the object to show this level
  10974. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10975. * @return {BABYLON.Mesh} this mesh (for chaining)
  10976. */
  10977. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10978. if (mesh && mesh._masterMesh) {
  10979. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10980. return this;
  10981. }
  10982. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10983. this._LODLevels.push(level);
  10984. if (mesh) {
  10985. mesh._masterMesh = this;
  10986. }
  10987. this._sortLODLevels();
  10988. return this;
  10989. };
  10990. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10991. for (var index = 0; index < this._LODLevels.length; index++) {
  10992. var level = this._LODLevels[index];
  10993. if (level.distance === distance) {
  10994. return level.mesh;
  10995. }
  10996. }
  10997. return null;
  10998. };
  10999. /**
  11000. * Remove a mesh from the LOD array
  11001. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  11002. * @return {BABYLON.Mesh} this mesh (for chaining)
  11003. */
  11004. Mesh.prototype.removeLODLevel = function (mesh) {
  11005. for (var index = 0; index < this._LODLevels.length; index++) {
  11006. if (this._LODLevels[index].mesh === mesh) {
  11007. this._LODLevels.splice(index, 1);
  11008. if (mesh) {
  11009. mesh._masterMesh = null;
  11010. }
  11011. }
  11012. }
  11013. this._sortLODLevels();
  11014. return this;
  11015. };
  11016. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11017. if (!this._LODLevels || this._LODLevels.length === 0) {
  11018. return this;
  11019. }
  11020. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11021. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11022. if (this.onLODLevelSelection) {
  11023. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11024. }
  11025. return this;
  11026. }
  11027. for (var index = 0; index < this._LODLevels.length; index++) {
  11028. var level = this._LODLevels[index];
  11029. if (level.distance < distanceToCamera) {
  11030. if (level.mesh) {
  11031. level.mesh._preActivate();
  11032. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11033. }
  11034. if (this.onLODLevelSelection) {
  11035. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11036. }
  11037. return level.mesh;
  11038. }
  11039. }
  11040. if (this.onLODLevelSelection) {
  11041. this.onLODLevelSelection(distanceToCamera, this, this);
  11042. }
  11043. return this;
  11044. };
  11045. Object.defineProperty(Mesh.prototype, "geometry", {
  11046. get: function () {
  11047. return this._geometry;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Mesh.prototype.getTotalVertices = function () {
  11053. if (!this._geometry) {
  11054. return 0;
  11055. }
  11056. return this._geometry.getTotalVertices();
  11057. };
  11058. Mesh.prototype.getVerticesData = function (kind) {
  11059. if (!this._geometry) {
  11060. return null;
  11061. }
  11062. return this._geometry.getVerticesData(kind);
  11063. };
  11064. Mesh.prototype.getVertexBuffer = function (kind) {
  11065. if (!this._geometry) {
  11066. return undefined;
  11067. }
  11068. return this._geometry.getVertexBuffer(kind);
  11069. };
  11070. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11071. if (!this._geometry) {
  11072. if (this._delayInfo) {
  11073. return this._delayInfo.indexOf(kind) !== -1;
  11074. }
  11075. return false;
  11076. }
  11077. return this._geometry.isVerticesDataPresent(kind);
  11078. };
  11079. Mesh.prototype.getVerticesDataKinds = function () {
  11080. if (!this._geometry) {
  11081. var result = [];
  11082. if (this._delayInfo) {
  11083. for (var kind in this._delayInfo) {
  11084. result.push(kind);
  11085. }
  11086. }
  11087. return result;
  11088. }
  11089. return this._geometry.getVerticesDataKinds();
  11090. };
  11091. Mesh.prototype.getTotalIndices = function () {
  11092. if (!this._geometry) {
  11093. return 0;
  11094. }
  11095. return this._geometry.getTotalIndices();
  11096. };
  11097. Mesh.prototype.getIndices = function () {
  11098. if (!this._geometry) {
  11099. return [];
  11100. }
  11101. return this._geometry.getIndices();
  11102. };
  11103. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11104. get: function () {
  11105. return this._masterMesh !== null && this._masterMesh !== undefined;
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Mesh.prototype.isReady = function () {
  11111. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11112. return false;
  11113. }
  11114. return _super.prototype.isReady.call(this);
  11115. };
  11116. Mesh.prototype.isDisposed = function () {
  11117. return this._isDisposed;
  11118. };
  11119. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11120. get: function () {
  11121. return this._sideOrientation;
  11122. },
  11123. set: function (sideO) {
  11124. this._sideOrientation = sideO;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. // Methods
  11130. Mesh.prototype._preActivate = function () {
  11131. var sceneRenderId = this.getScene().getRenderId();
  11132. if (this._preActivateId === sceneRenderId) {
  11133. return;
  11134. }
  11135. this._preActivateId = sceneRenderId;
  11136. this._visibleInstances = null;
  11137. };
  11138. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11139. if (!this._visibleInstances) {
  11140. this._visibleInstances = {};
  11141. this._visibleInstances.defaultRenderId = renderId;
  11142. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11143. }
  11144. if (!this._visibleInstances[renderId]) {
  11145. this._visibleInstances[renderId] = new Array();
  11146. }
  11147. this._visibleInstances[renderId].push(instance);
  11148. };
  11149. Mesh.prototype.refreshBoundingInfo = function () {
  11150. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11151. if (data) {
  11152. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11153. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11154. }
  11155. if (this.subMeshes) {
  11156. for (var index = 0; index < this.subMeshes.length; index++) {
  11157. this.subMeshes[index].refreshBoundingInfo();
  11158. }
  11159. }
  11160. this._updateBoundingInfo();
  11161. };
  11162. Mesh.prototype._createGlobalSubMesh = function () {
  11163. var totalVertices = this.getTotalVertices();
  11164. if (!totalVertices || !this.getIndices()) {
  11165. return null;
  11166. }
  11167. this.releaseSubMeshes();
  11168. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11169. };
  11170. Mesh.prototype.subdivide = function (count) {
  11171. if (count < 1) {
  11172. return;
  11173. }
  11174. var totalIndices = this.getTotalIndices();
  11175. var subdivisionSize = (totalIndices / count) | 0;
  11176. var offset = 0;
  11177. while (subdivisionSize % 3 !== 0) {
  11178. subdivisionSize++;
  11179. }
  11180. this.releaseSubMeshes();
  11181. for (var index = 0; index < count; index++) {
  11182. if (offset >= totalIndices) {
  11183. break;
  11184. }
  11185. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11186. offset += subdivisionSize;
  11187. }
  11188. this.synchronizeInstances();
  11189. };
  11190. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11191. if (kind instanceof Array) {
  11192. var temp = data;
  11193. data = kind;
  11194. kind = temp;
  11195. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11196. }
  11197. if (!this._geometry) {
  11198. var vertexData = new BABYLON.VertexData();
  11199. vertexData.set(data, kind);
  11200. var scene = this.getScene();
  11201. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11202. }
  11203. else {
  11204. this._geometry.setVerticesData(kind, data, updatable, stride);
  11205. }
  11206. };
  11207. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11208. if (!this._geometry) {
  11209. return;
  11210. }
  11211. if (!makeItUnique) {
  11212. this._geometry.updateVerticesData(kind, data, updateExtends);
  11213. }
  11214. else {
  11215. this.makeGeometryUnique();
  11216. this.updateVerticesData(kind, data, updateExtends, false);
  11217. }
  11218. };
  11219. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11220. if (!this._geometry) {
  11221. return;
  11222. }
  11223. if (!makeItUnique) {
  11224. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11225. }
  11226. else {
  11227. this.makeGeometryUnique();
  11228. this.updateVerticesDataDirectly(kind, data, offset, false);
  11229. }
  11230. };
  11231. // Mesh positions update function :
  11232. // updates the mesh positions according to the positionFunction returned values.
  11233. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11234. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11235. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11236. if (computeNormals === void 0) { computeNormals = true; }
  11237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11238. positionFunction(positions);
  11239. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11240. if (computeNormals) {
  11241. var indices = this.getIndices();
  11242. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11243. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11244. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11245. }
  11246. };
  11247. Mesh.prototype.makeGeometryUnique = function () {
  11248. if (!this._geometry) {
  11249. return;
  11250. }
  11251. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11252. geometry.applyToMesh(this);
  11253. };
  11254. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11255. if (!this._geometry) {
  11256. var vertexData = new BABYLON.VertexData();
  11257. vertexData.indices = indices;
  11258. var scene = this.getScene();
  11259. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11260. }
  11261. else {
  11262. this._geometry.setIndices(indices, totalVertices);
  11263. }
  11264. };
  11265. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11266. var engine = this.getScene().getEngine();
  11267. // Wireframe
  11268. var indexToBind;
  11269. switch (fillMode) {
  11270. case BABYLON.Material.PointFillMode:
  11271. indexToBind = null;
  11272. break;
  11273. case BABYLON.Material.WireFrameFillMode:
  11274. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11275. break;
  11276. default:
  11277. case BABYLON.Material.TriangleFillMode:
  11278. indexToBind = this._geometry.getIndexBuffer();
  11279. break;
  11280. }
  11281. // VBOs
  11282. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11283. };
  11284. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11285. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11286. return;
  11287. }
  11288. var engine = this.getScene().getEngine();
  11289. switch (fillMode) {
  11290. case BABYLON.Material.PointFillMode:
  11291. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11292. break;
  11293. case BABYLON.Material.WireFrameFillMode:
  11294. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11295. break;
  11296. default:
  11297. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11298. }
  11299. };
  11300. Mesh.prototype.registerBeforeRender = function (func) {
  11301. this._onBeforeRenderCallbacks.push(func);
  11302. };
  11303. Mesh.prototype.unregisterBeforeRender = function (func) {
  11304. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11305. if (index > -1) {
  11306. this._onBeforeRenderCallbacks.splice(index, 1);
  11307. }
  11308. };
  11309. Mesh.prototype.registerAfterRender = function (func) {
  11310. this._onAfterRenderCallbacks.push(func);
  11311. };
  11312. Mesh.prototype.unregisterAfterRender = function (func) {
  11313. var index = this._onAfterRenderCallbacks.indexOf(func);
  11314. if (index > -1) {
  11315. this._onAfterRenderCallbacks.splice(index, 1);
  11316. }
  11317. };
  11318. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11319. var scene = this.getScene();
  11320. this._batchCache.mustReturn = false;
  11321. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11322. this._batchCache.visibleInstances[subMeshId] = null;
  11323. if (this._visibleInstances) {
  11324. var currentRenderId = scene.getRenderId();
  11325. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11326. var selfRenderId = this._renderId;
  11327. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11328. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11329. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11330. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11331. }
  11332. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11333. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11334. this._batchCache.mustReturn = true;
  11335. return this._batchCache;
  11336. }
  11337. if (currentRenderId !== selfRenderId) {
  11338. this._batchCache.renderSelf[subMeshId] = false;
  11339. }
  11340. }
  11341. this._renderIdForInstances[subMeshId] = currentRenderId;
  11342. }
  11343. return this._batchCache;
  11344. };
  11345. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11346. var visibleInstances = batch.visibleInstances[subMesh._id];
  11347. var matricesCount = visibleInstances.length + 1;
  11348. var bufferSize = matricesCount * 16 * 4;
  11349. while (this._instancesBufferSize < bufferSize) {
  11350. this._instancesBufferSize *= 2;
  11351. }
  11352. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11353. if (this._worldMatricesInstancesBuffer) {
  11354. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11355. }
  11356. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11357. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11358. }
  11359. var offset = 0;
  11360. var instancesCount = 0;
  11361. var world = this.getWorldMatrix();
  11362. if (batch.renderSelf[subMesh._id]) {
  11363. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11364. offset += 16;
  11365. instancesCount++;
  11366. }
  11367. if (visibleInstances) {
  11368. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11369. var instance = visibleInstances[instanceIndex];
  11370. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11371. offset += 16;
  11372. instancesCount++;
  11373. }
  11374. }
  11375. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11376. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11377. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11378. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11379. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11380. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11381. this._draw(subMesh, fillMode, instancesCount);
  11382. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11383. };
  11384. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11385. var scene = this.getScene();
  11386. var engine = scene.getEngine();
  11387. if (hardwareInstancedRendering) {
  11388. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11389. }
  11390. else {
  11391. if (batch.renderSelf[subMesh._id]) {
  11392. // Draw
  11393. if (onBeforeDraw) {
  11394. onBeforeDraw(false, this.getWorldMatrix());
  11395. }
  11396. this._draw(subMesh, fillMode);
  11397. }
  11398. if (batch.visibleInstances[subMesh._id]) {
  11399. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11400. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11401. // World
  11402. var world = instance.getWorldMatrix();
  11403. if (onBeforeDraw) {
  11404. onBeforeDraw(true, world);
  11405. }
  11406. // Draw
  11407. this._draw(subMesh, fillMode);
  11408. }
  11409. }
  11410. }
  11411. };
  11412. Mesh.prototype.render = function (subMesh) {
  11413. var scene = this.getScene();
  11414. // Managing instances
  11415. var batch = this._getInstancesRenderList(subMesh._id);
  11416. if (batch.mustReturn) {
  11417. return;
  11418. }
  11419. // Checking geometry state
  11420. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11421. return;
  11422. }
  11423. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11424. this._onBeforeRenderCallbacks[callbackIndex](this);
  11425. }
  11426. var engine = scene.getEngine();
  11427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11428. // Material
  11429. var effectiveMaterial = subMesh.getMaterial();
  11430. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11431. return;
  11432. }
  11433. // Outline - step 1
  11434. var savedDepthWrite = engine.getDepthWrite();
  11435. if (this.renderOutline) {
  11436. engine.setDepthWrite(false);
  11437. scene.getOutlineRenderer().render(subMesh, batch);
  11438. engine.setDepthWrite(savedDepthWrite);
  11439. }
  11440. effectiveMaterial._preBind();
  11441. var effect = effectiveMaterial.getEffect();
  11442. // Bind
  11443. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11444. this._bind(subMesh, effect, fillMode);
  11445. var world = this.getWorldMatrix();
  11446. effectiveMaterial.bind(world, this);
  11447. // Draw
  11448. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11449. if (isInstance) {
  11450. effectiveMaterial.bindOnlyWorldMatrix(world);
  11451. }
  11452. });
  11453. // Unbind
  11454. effectiveMaterial.unbind();
  11455. // Outline - step 2
  11456. if (this.renderOutline && savedDepthWrite) {
  11457. engine.setDepthWrite(true);
  11458. engine.setColorWrite(false);
  11459. scene.getOutlineRenderer().render(subMesh, batch);
  11460. engine.setColorWrite(true);
  11461. }
  11462. // Overlay
  11463. if (this.renderOverlay) {
  11464. var currentMode = engine.getAlphaMode();
  11465. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11466. scene.getOutlineRenderer().render(subMesh, batch, true);
  11467. engine.setAlphaMode(currentMode);
  11468. }
  11469. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11470. this._onAfterRenderCallbacks[callbackIndex](this);
  11471. }
  11472. };
  11473. Mesh.prototype.getEmittedParticleSystems = function () {
  11474. var results = new Array();
  11475. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11476. var particleSystem = this.getScene().particleSystems[index];
  11477. if (particleSystem.emitter === this) {
  11478. results.push(particleSystem);
  11479. }
  11480. }
  11481. return results;
  11482. };
  11483. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11484. var results = new Array();
  11485. var descendants = this.getDescendants();
  11486. descendants.push(this);
  11487. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11488. var particleSystem = this.getScene().particleSystems[index];
  11489. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11490. results.push(particleSystem);
  11491. }
  11492. }
  11493. return results;
  11494. };
  11495. Mesh.prototype.getChildren = function () {
  11496. var results = [];
  11497. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11498. var mesh = this.getScene().meshes[index];
  11499. if (mesh.parent === this) {
  11500. results.push(mesh);
  11501. }
  11502. }
  11503. return results;
  11504. };
  11505. Mesh.prototype._checkDelayState = function () {
  11506. var _this = this;
  11507. var that = this;
  11508. var scene = this.getScene();
  11509. if (this._geometry) {
  11510. this._geometry.load(scene);
  11511. }
  11512. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11513. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11514. scene._addPendingData(that);
  11515. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11516. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11517. if (data instanceof ArrayBuffer) {
  11518. _this._delayLoadingFunction(data, _this);
  11519. }
  11520. else {
  11521. _this._delayLoadingFunction(JSON.parse(data), _this);
  11522. }
  11523. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11524. scene._removePendingData(_this);
  11525. }, function () {
  11526. }, scene.database, getBinaryData);
  11527. }
  11528. };
  11529. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11530. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11531. return false;
  11532. }
  11533. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11534. return false;
  11535. }
  11536. this._checkDelayState();
  11537. return true;
  11538. };
  11539. Mesh.prototype.setMaterialByID = function (id) {
  11540. var materials = this.getScene().materials;
  11541. for (var index = 0; index < materials.length; index++) {
  11542. if (materials[index].id === id) {
  11543. this.material = materials[index];
  11544. return;
  11545. }
  11546. }
  11547. // Multi
  11548. var multiMaterials = this.getScene().multiMaterials;
  11549. for (index = 0; index < multiMaterials.length; index++) {
  11550. if (multiMaterials[index].id === id) {
  11551. this.material = multiMaterials[index];
  11552. return;
  11553. }
  11554. }
  11555. };
  11556. Mesh.prototype.getAnimatables = function () {
  11557. var results = [];
  11558. if (this.material) {
  11559. results.push(this.material);
  11560. }
  11561. if (this.skeleton) {
  11562. results.push(this.skeleton);
  11563. }
  11564. return results;
  11565. };
  11566. // Geometry
  11567. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11568. // Position
  11569. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11570. return;
  11571. }
  11572. this._resetPointsArrayCache();
  11573. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11574. var temp = [];
  11575. for (var index = 0; index < data.length; index += 3) {
  11576. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11577. }
  11578. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11579. // Normals
  11580. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11581. return;
  11582. }
  11583. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11584. for (index = 0; index < data.length; index += 3) {
  11585. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11586. }
  11587. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11588. };
  11589. // Cache
  11590. Mesh.prototype._resetPointsArrayCache = function () {
  11591. this._positions = null;
  11592. };
  11593. Mesh.prototype._generatePointsArray = function () {
  11594. if (this._positions)
  11595. return true;
  11596. this._positions = [];
  11597. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11598. if (!data) {
  11599. return false;
  11600. }
  11601. for (var index = 0; index < data.length; index += 3) {
  11602. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11603. }
  11604. return true;
  11605. };
  11606. // Clone
  11607. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11608. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11609. };
  11610. // Dispose
  11611. Mesh.prototype.dispose = function (doNotRecurse) {
  11612. if (this._geometry) {
  11613. this._geometry.releaseForMesh(this, true);
  11614. }
  11615. // Instances
  11616. if (this._worldMatricesInstancesBuffer) {
  11617. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11618. this._worldMatricesInstancesBuffer = null;
  11619. }
  11620. while (this.instances.length) {
  11621. this.instances[0].dispose();
  11622. }
  11623. _super.prototype.dispose.call(this, doNotRecurse);
  11624. };
  11625. // Geometric tools
  11626. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11627. var _this = this;
  11628. var scene = this.getScene();
  11629. var onload = function (img) {
  11630. // Getting height map data
  11631. var canvas = document.createElement("canvas");
  11632. var context = canvas.getContext("2d");
  11633. var heightMapWidth = img.width;
  11634. var heightMapHeight = img.height;
  11635. canvas.width = heightMapWidth;
  11636. canvas.height = heightMapHeight;
  11637. context.drawImage(img, 0, 0);
  11638. // Create VertexData from map data
  11639. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11640. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11641. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11642. //execute success callback, if set
  11643. if (onSuccess) {
  11644. onSuccess(_this);
  11645. }
  11646. };
  11647. BABYLON.Tools.LoadImage(url, onload, function () {
  11648. }, scene.database);
  11649. };
  11650. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11652. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11653. return;
  11654. }
  11655. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11656. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11657. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11658. var position = BABYLON.Vector3.Zero();
  11659. var normal = BABYLON.Vector3.Zero();
  11660. var uv = BABYLON.Vector2.Zero();
  11661. for (var index = 0; index < positions.length; index += 3) {
  11662. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11663. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11664. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11665. // Compute height
  11666. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11667. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11668. var pos = (u + v * heightMapWidth) * 4;
  11669. var r = buffer[pos] / 255.0;
  11670. var g = buffer[pos + 1] / 255.0;
  11671. var b = buffer[pos + 2] / 255.0;
  11672. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11673. normal.normalize();
  11674. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11675. position = position.add(normal);
  11676. position.toArray(positions, index);
  11677. }
  11678. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11679. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11680. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11681. };
  11682. Mesh.prototype.convertToFlatShadedMesh = function () {
  11683. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11684. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11685. var kinds = this.getVerticesDataKinds();
  11686. var vbs = [];
  11687. var data = [];
  11688. var newdata = [];
  11689. var updatableNormals = false;
  11690. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11691. var kind = kinds[kindIndex];
  11692. var vertexBuffer = this.getVertexBuffer(kind);
  11693. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11694. updatableNormals = vertexBuffer.isUpdatable();
  11695. kinds.splice(kindIndex, 1);
  11696. kindIndex--;
  11697. continue;
  11698. }
  11699. vbs[kind] = vertexBuffer;
  11700. data[kind] = vbs[kind].getData();
  11701. newdata[kind] = [];
  11702. }
  11703. // Save previous submeshes
  11704. var previousSubmeshes = this.subMeshes.slice(0);
  11705. var indices = this.getIndices();
  11706. var totalIndices = this.getTotalIndices();
  11707. for (var index = 0; index < totalIndices; index++) {
  11708. var vertexIndex = indices[index];
  11709. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11710. kind = kinds[kindIndex];
  11711. var stride = vbs[kind].getStrideSize();
  11712. for (var offset = 0; offset < stride; offset++) {
  11713. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11714. }
  11715. }
  11716. }
  11717. // Updating faces & normal
  11718. var normals = [];
  11719. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11720. for (index = 0; index < totalIndices; index += 3) {
  11721. indices[index] = index;
  11722. indices[index + 1] = index + 1;
  11723. indices[index + 2] = index + 2;
  11724. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11725. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11726. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11727. var p1p2 = p1.subtract(p2);
  11728. var p3p2 = p3.subtract(p2);
  11729. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11730. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11731. normals.push(normal.x);
  11732. normals.push(normal.y);
  11733. normals.push(normal.z);
  11734. }
  11735. }
  11736. this.setIndices(indices);
  11737. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11738. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11739. kind = kinds[kindIndex];
  11740. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11741. }
  11742. // Updating submeshes
  11743. this.releaseSubMeshes();
  11744. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11745. var previousOne = previousSubmeshes[submeshIndex];
  11746. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11747. }
  11748. this.synchronizeInstances();
  11749. };
  11750. // Instances
  11751. Mesh.prototype.createInstance = function (name) {
  11752. return new BABYLON.InstancedMesh(name, this);
  11753. };
  11754. Mesh.prototype.synchronizeInstances = function () {
  11755. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11756. var instance = this.instances[instanceIndex];
  11757. instance._syncSubMeshes();
  11758. }
  11759. };
  11760. /**
  11761. * Simplify the mesh according to the given array of settings.
  11762. * Function will return immediately and will simplify async.
  11763. * @param settings a collection of simplification settings.
  11764. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11765. * @param type the type of simplification to run.
  11766. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11767. */
  11768. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11769. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11770. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11771. this.getScene().simplificationQueue.addTask({
  11772. settings: settings,
  11773. parallelProcessing: parallelProcessing,
  11774. mesh: this,
  11775. simplificationType: simplificationType,
  11776. successCallback: successCallback
  11777. });
  11778. };
  11779. /**
  11780. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11781. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11782. * This should be used together with the simplification to avoid disappearing triangles.
  11783. * @param successCallback an optional success callback to be called after the optimization finished.
  11784. */
  11785. Mesh.prototype.optimizeIndices = function (successCallback) {
  11786. var _this = this;
  11787. var indices = this.getIndices();
  11788. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11789. var vectorPositions = [];
  11790. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11791. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11792. }
  11793. var dupes = [];
  11794. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11795. var realPos = vectorPositions.length - 1 - iteration;
  11796. var testedPosition = vectorPositions[realPos];
  11797. for (var j = 0; j < realPos; ++j) {
  11798. var againstPosition = vectorPositions[j];
  11799. if (testedPosition.equals(againstPosition)) {
  11800. dupes[realPos] = j;
  11801. break;
  11802. }
  11803. }
  11804. }, function () {
  11805. for (var i = 0; i < indices.length; ++i) {
  11806. indices[i] = dupes[indices[i]] || indices[i];
  11807. }
  11808. //indices are now reordered
  11809. var originalSubMeshes = _this.subMeshes.slice(0);
  11810. _this.setIndices(indices);
  11811. _this.subMeshes = originalSubMeshes;
  11812. if (successCallback) {
  11813. successCallback(_this);
  11814. }
  11815. });
  11816. };
  11817. // Statics
  11818. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11819. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11820. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11821. if (ribbonInstance) {
  11822. // positionFunction : ribbon case
  11823. // only pathArray and sideOrientation parameters are taken into account for positions update
  11824. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11825. var positionFunction = function (positions) {
  11826. var minlg = pathArray[0].length;
  11827. var i = 0;
  11828. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11829. for (var si = 1; si <= ns; si++) {
  11830. for (var p = 0; p < pathArray.length; p++) {
  11831. var path = pathArray[p];
  11832. var l = path.length;
  11833. minlg = (minlg < l) ? minlg : l;
  11834. var j = 0;
  11835. while (j < minlg) {
  11836. positions[i] = path[j].x;
  11837. positions[i + 1] = path[j].y;
  11838. positions[i + 2] = path[j].z;
  11839. j++;
  11840. i += 3;
  11841. }
  11842. }
  11843. }
  11844. };
  11845. return positionFunction;
  11846. };
  11847. var sideOrientation = ribbonInstance.sideOrientation;
  11848. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11849. ribbonInstance.updateMeshPositions(positionFunction, true);
  11850. return ribbonInstance;
  11851. }
  11852. else {
  11853. var ribbon = new Mesh(name, scene);
  11854. ribbon.sideOrientation = sideOrientation;
  11855. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11856. vertexData.applyToMesh(ribbon, updatable);
  11857. return ribbon;
  11858. }
  11859. };
  11860. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  11861. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11862. var disc = new Mesh(name, scene);
  11863. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  11864. vertexData.applyToMesh(disc, updatable);
  11865. return disc;
  11866. };
  11867. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11868. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11869. var box = new Mesh(name, scene);
  11870. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11871. vertexData.applyToMesh(box, updatable);
  11872. return box;
  11873. };
  11874. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11875. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11876. var sphere = new Mesh(name, scene);
  11877. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11878. vertexData.applyToMesh(sphere, updatable);
  11879. return sphere;
  11880. };
  11881. // Cylinder and cone (Code inspired by SharpDX.org)
  11882. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11883. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11884. // subdivisions is a new parameter, we need to support old signature
  11885. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11886. if (scene !== undefined) {
  11887. updatable = scene;
  11888. }
  11889. scene = subdivisions;
  11890. subdivisions = 1;
  11891. }
  11892. var cylinder = new Mesh(name, scene);
  11893. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11894. vertexData.applyToMesh(cylinder, updatable);
  11895. return cylinder;
  11896. };
  11897. // Torus (Code from SharpDX.org)
  11898. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11899. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11900. var torus = new Mesh(name, scene);
  11901. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11902. vertexData.applyToMesh(torus, updatable);
  11903. return torus;
  11904. };
  11905. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11906. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11907. var torusKnot = new Mesh(name, scene);
  11908. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11909. vertexData.applyToMesh(torusKnot, updatable);
  11910. return torusKnot;
  11911. };
  11912. // Lines
  11913. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11914. if (linesInstance === void 0) { linesInstance = null; }
  11915. if (linesInstance) {
  11916. var positionsOfLines = function (points) {
  11917. var positionFunction = function (positions) {
  11918. var i = 0;
  11919. for (var p = 0; p < points.length; p++) {
  11920. positions[i] = points[p].x;
  11921. positions[i + 1] = points[p].y;
  11922. positions[i + 2] = points[p].z;
  11923. i += 3;
  11924. }
  11925. };
  11926. return positionFunction;
  11927. };
  11928. var positionFunction = positionsOfLines(points);
  11929. linesInstance.updateMeshPositions(positionFunction, false);
  11930. return linesInstance;
  11931. }
  11932. // lines creation
  11933. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11934. var vertexData = BABYLON.VertexData.CreateLines(points);
  11935. vertexData.applyToMesh(lines, updatable);
  11936. return lines;
  11937. };
  11938. // Extrusion
  11939. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  11940. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11941. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11942. scale = scale || 1;
  11943. rotation = rotation || 0;
  11944. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  11945. return extruded;
  11946. };
  11947. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  11948. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11949. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11950. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  11951. return extrudedCustom;
  11952. };
  11953. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  11954. // extrusion geometry
  11955. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  11956. var tangents = path3D.getTangents();
  11957. var normals = path3D.getNormals();
  11958. var binormals = path3D.getBinormals();
  11959. var distances = path3D.getDistances();
  11960. var angle = 0;
  11961. var returnScale = function (i, distance) {
  11962. return scale;
  11963. };
  11964. var returnRotation = function (i, distance) {
  11965. return rotation;
  11966. };
  11967. var rotate = custom ? rotateFunction : returnRotation;
  11968. var scl = custom ? scaleFunction : returnScale;
  11969. var index = 0;
  11970. for (var i = 0; i < curve.length; i++) {
  11971. var shapePath = new Array();
  11972. var angleStep = rotate(i, distances[i]);
  11973. var scaleRatio = scl(i, distances[i]);
  11974. for (var p = 0; p < shape.length; p++) {
  11975. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11976. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11977. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11978. shapePath.push(rotated);
  11979. }
  11980. shapePaths[index] = shapePath;
  11981. angle += angleStep;
  11982. index++;
  11983. }
  11984. return shapePaths;
  11985. };
  11986. if (instance) {
  11987. var path3D = (instance.path3D).update(curve);
  11988. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  11989. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  11990. return instance;
  11991. }
  11992. // extruded shape creation
  11993. var path3D = new BABYLON.Path3D(curve);
  11994. var newShapePaths = new Array();
  11995. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  11996. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  11997. extrudedGeneric.pathArray = pathArray;
  11998. extrudedGeneric.path3D = path3D;
  11999. return extrudedGeneric;
  12000. };
  12001. // Plane & ground
  12002. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  12003. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12004. var plane = new Mesh(name, scene);
  12005. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  12006. vertexData.applyToMesh(plane, updatable);
  12007. return plane;
  12008. };
  12009. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  12010. var ground = new BABYLON.GroundMesh(name, scene);
  12011. ground._setReady(false);
  12012. ground._subdivisions = subdivisions;
  12013. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  12014. vertexData.applyToMesh(ground, updatable);
  12015. ground._setReady(true);
  12016. return ground;
  12017. };
  12018. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12019. var tiledGround = new Mesh(name, scene);
  12020. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12021. vertexData.applyToMesh(tiledGround, updatable);
  12022. return tiledGround;
  12023. };
  12024. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12025. var ground = new BABYLON.GroundMesh(name, scene);
  12026. ground._subdivisions = subdivisions;
  12027. ground._setReady(false);
  12028. var onload = function (img) {
  12029. // Getting height map data
  12030. var canvas = document.createElement("canvas");
  12031. var context = canvas.getContext("2d");
  12032. var heightMapWidth = img.width;
  12033. var heightMapHeight = img.height;
  12034. canvas.width = heightMapWidth;
  12035. canvas.height = heightMapHeight;
  12036. context.drawImage(img, 0, 0);
  12037. // Create VertexData from map data
  12038. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12039. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12040. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12041. vertexData.applyToMesh(ground, updatable);
  12042. ground._setReady(true);
  12043. //execute ready callback, if set
  12044. if (onReady) {
  12045. onReady(ground);
  12046. }
  12047. };
  12048. BABYLON.Tools.LoadImage(url, onload, function () {
  12049. }, scene.database);
  12050. return ground;
  12051. };
  12052. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12053. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12054. if (tubeInstance === void 0) { tubeInstance = null; }
  12055. // tube geometry
  12056. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12057. var tangents = path3D.getTangents();
  12058. var normals = path3D.getNormals();
  12059. var distances = path3D.getDistances();
  12060. var pi2 = Math.PI * 2;
  12061. var step = pi2 / tessellation;
  12062. var returnRadius = function (i, distance) { return radius; };
  12063. var radiusFunctionFinal = radiusFunction || returnRadius;
  12064. var circlePath;
  12065. var rad;
  12066. var normal;
  12067. var rotated;
  12068. var rotationMatrix;
  12069. var index = 0;
  12070. for (var i = 0; i < path.length; i++) {
  12071. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12072. circlePath = Array(); // current circle array
  12073. normal = normals[i]; // current normal
  12074. for (var ang = 0; ang < pi2; ang += step) {
  12075. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12076. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12077. circlePath.push(rotated);
  12078. }
  12079. circlePaths[index] = circlePath;
  12080. index++;
  12081. }
  12082. return circlePaths;
  12083. };
  12084. if (tubeInstance) {
  12085. var path3D = (tubeInstance.path3D).update(path);
  12086. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12087. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12088. return tubeInstance;
  12089. }
  12090. // tube creation
  12091. var path3D = new BABYLON.Path3D(path);
  12092. var newPathArray = new Array();
  12093. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12094. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12095. tube.pathArray = pathArray;
  12096. tube.path3D = path3D;
  12097. tube.tessellation = tessellation;
  12098. return tube;
  12099. };
  12100. // Decals
  12101. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12102. if (angle === void 0) { angle = 0; }
  12103. var indices = sourceMesh.getIndices();
  12104. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12105. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12106. // Getting correct rotation
  12107. if (!normal) {
  12108. var target = new BABYLON.Vector3(0, 0, 1);
  12109. var camera = sourceMesh.getScene().activeCamera;
  12110. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12111. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12112. }
  12113. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12114. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12115. var pitch = Math.atan2(normal.y, len);
  12116. // Matrix
  12117. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12118. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12119. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12120. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12121. var vertexData = new BABYLON.VertexData();
  12122. vertexData.indices = [];
  12123. vertexData.positions = [];
  12124. vertexData.normals = [];
  12125. vertexData.uvs = [];
  12126. var currentVertexDataIndex = 0;
  12127. var extractDecalVector3 = function (indexId) {
  12128. var vertexId = indices[indexId];
  12129. var result = new BABYLON.PositionNormalVertex();
  12130. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12131. // Send vector to decal local world
  12132. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12133. // Get normal
  12134. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12135. return result;
  12136. };
  12137. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12138. var clip = function (vertices, axis) {
  12139. if (vertices.length === 0) {
  12140. return vertices;
  12141. }
  12142. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12143. var clipVertices = function (v0, v1) {
  12144. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12145. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12146. };
  12147. var result = new Array();
  12148. for (var index = 0; index < vertices.length; index += 3) {
  12149. var v1Out;
  12150. var v2Out;
  12151. var v3Out;
  12152. var total = 0;
  12153. var nV1, nV2, nV3, nV4;
  12154. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12155. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12156. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12157. v1Out = d1 > 0;
  12158. v2Out = d2 > 0;
  12159. v3Out = d3 > 0;
  12160. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12161. switch (total) {
  12162. case 0:
  12163. result.push(vertices[index]);
  12164. result.push(vertices[index + 1]);
  12165. result.push(vertices[index + 2]);
  12166. break;
  12167. case 1:
  12168. if (v1Out) {
  12169. nV1 = vertices[index + 1];
  12170. nV2 = vertices[index + 2];
  12171. nV3 = clipVertices(vertices[index], nV1);
  12172. nV4 = clipVertices(vertices[index], nV2);
  12173. }
  12174. if (v2Out) {
  12175. nV1 = vertices[index];
  12176. nV2 = vertices[index + 2];
  12177. nV3 = clipVertices(vertices[index + 1], nV1);
  12178. nV4 = clipVertices(vertices[index + 1], nV2);
  12179. result.push(nV3);
  12180. result.push(nV2.clone());
  12181. result.push(nV1.clone());
  12182. result.push(nV2.clone());
  12183. result.push(nV3.clone());
  12184. result.push(nV4);
  12185. break;
  12186. }
  12187. if (v3Out) {
  12188. nV1 = vertices[index];
  12189. nV2 = vertices[index + 1];
  12190. nV3 = clipVertices(vertices[index + 2], nV1);
  12191. nV4 = clipVertices(vertices[index + 2], nV2);
  12192. }
  12193. result.push(nV1.clone());
  12194. result.push(nV2.clone());
  12195. result.push(nV3);
  12196. result.push(nV4);
  12197. result.push(nV3.clone());
  12198. result.push(nV2.clone());
  12199. break;
  12200. case 2:
  12201. if (!v1Out) {
  12202. nV1 = vertices[index].clone();
  12203. nV2 = clipVertices(nV1, vertices[index + 1]);
  12204. nV3 = clipVertices(nV1, vertices[index + 2]);
  12205. result.push(nV1);
  12206. result.push(nV2);
  12207. result.push(nV3);
  12208. }
  12209. if (!v2Out) {
  12210. nV1 = vertices[index + 1].clone();
  12211. nV2 = clipVertices(nV1, vertices[index + 2]);
  12212. nV3 = clipVertices(nV1, vertices[index]);
  12213. result.push(nV1);
  12214. result.push(nV2);
  12215. result.push(nV3);
  12216. }
  12217. if (!v3Out) {
  12218. nV1 = vertices[index + 2].clone();
  12219. nV2 = clipVertices(nV1, vertices[index]);
  12220. nV3 = clipVertices(nV1, vertices[index + 1]);
  12221. result.push(nV1);
  12222. result.push(nV2);
  12223. result.push(nV3);
  12224. }
  12225. break;
  12226. case 3:
  12227. break;
  12228. }
  12229. }
  12230. return result;
  12231. };
  12232. for (var index = 0; index < indices.length; index += 3) {
  12233. var faceVertices = new Array();
  12234. faceVertices.push(extractDecalVector3(index));
  12235. faceVertices.push(extractDecalVector3(index + 1));
  12236. faceVertices.push(extractDecalVector3(index + 2));
  12237. // Clip
  12238. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12239. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12240. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12241. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12242. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12243. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12244. if (faceVertices.length === 0) {
  12245. continue;
  12246. }
  12247. // Add UVs and get back to world
  12248. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12249. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12250. var vertex = faceVertices[vIndex];
  12251. vertexData.indices.push(currentVertexDataIndex);
  12252. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12253. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12254. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12255. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12256. currentVertexDataIndex++;
  12257. }
  12258. }
  12259. // Return mesh
  12260. var decal = new Mesh(name, sourceMesh.getScene());
  12261. vertexData.applyToMesh(decal);
  12262. decal.position = position.clone();
  12263. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12264. return decal;
  12265. };
  12266. // Tools
  12267. Mesh.MinMax = function (meshes) {
  12268. var minVector = null;
  12269. var maxVector = null;
  12270. for (var i in meshes) {
  12271. var mesh = meshes[i];
  12272. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12273. if (!minVector) {
  12274. minVector = boundingBox.minimumWorld;
  12275. maxVector = boundingBox.maximumWorld;
  12276. continue;
  12277. }
  12278. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12279. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12280. }
  12281. return {
  12282. min: minVector,
  12283. max: maxVector
  12284. };
  12285. };
  12286. Mesh.Center = function (meshesOrMinMaxVector) {
  12287. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12288. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12289. };
  12290. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12291. if (disposeSource === void 0) { disposeSource = true; }
  12292. var source = meshes[0];
  12293. var material = source.material;
  12294. var scene = source.getScene();
  12295. if (!allow32BitsIndices) {
  12296. var totalVertices = 0;
  12297. for (var index = 0; index < meshes.length; index++) {
  12298. totalVertices += meshes[index].getTotalVertices();
  12299. if (totalVertices > 65536) {
  12300. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12301. return null;
  12302. }
  12303. }
  12304. }
  12305. // Merge
  12306. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12307. vertexData.transform(source.getWorldMatrix());
  12308. for (index = 1; index < meshes.length; index++) {
  12309. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12310. otherVertexData.transform(meshes[index].getWorldMatrix());
  12311. vertexData.merge(otherVertexData);
  12312. }
  12313. var newMesh = new Mesh(source.name + "_merged", scene);
  12314. vertexData.applyToMesh(newMesh);
  12315. // Setting properties
  12316. newMesh.material = material;
  12317. newMesh.checkCollisions = source.checkCollisions;
  12318. // Cleaning
  12319. if (disposeSource) {
  12320. for (index = 0; index < meshes.length; index++) {
  12321. meshes[index].dispose();
  12322. }
  12323. }
  12324. return newMesh;
  12325. };
  12326. // Consts
  12327. Mesh._FRONTSIDE = 0;
  12328. Mesh._BACKSIDE = 1;
  12329. Mesh._DOUBLESIDE = 2;
  12330. Mesh._DEFAULTSIDE = 0;
  12331. return Mesh;
  12332. })(BABYLON.AbstractMesh);
  12333. BABYLON.Mesh = Mesh;
  12334. })(BABYLON || (BABYLON = {}));
  12335. //# sourceMappingURL=babylon.mesh.js.map
  12336. var BABYLON;
  12337. (function (BABYLON) {
  12338. var GroundMesh = (function (_super) {
  12339. __extends(GroundMesh, _super);
  12340. function GroundMesh(name, scene) {
  12341. _super.call(this, name, scene);
  12342. this.generateOctree = false;
  12343. this._worldInverse = new BABYLON.Matrix();
  12344. }
  12345. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12346. get: function () {
  12347. return this._subdivisions;
  12348. },
  12349. enumerable: true,
  12350. configurable: true
  12351. });
  12352. GroundMesh.prototype.optimize = function (chunksCount) {
  12353. this.subdivide(this._subdivisions);
  12354. this.createOrUpdateSubmeshesOctree(32);
  12355. };
  12356. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12357. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12358. this.getWorldMatrix().invertToRef(this._worldInverse);
  12359. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12360. var pickInfo = this.intersects(ray);
  12361. if (pickInfo.hit) {
  12362. return pickInfo.pickedPoint.y;
  12363. }
  12364. return 0;
  12365. };
  12366. return GroundMesh;
  12367. })(BABYLON.Mesh);
  12368. BABYLON.GroundMesh = GroundMesh;
  12369. })(BABYLON || (BABYLON = {}));
  12370. //# sourceMappingURL=babylon.groundMesh.js.map
  12371. var BABYLON;
  12372. (function (BABYLON) {
  12373. /**
  12374. * Creates an instance based on a source mesh.
  12375. */
  12376. var InstancedMesh = (function (_super) {
  12377. __extends(InstancedMesh, _super);
  12378. function InstancedMesh(name, source) {
  12379. _super.call(this, name, source.getScene());
  12380. source.instances.push(this);
  12381. this._sourceMesh = source;
  12382. this.position.copyFrom(source.position);
  12383. this.rotation.copyFrom(source.rotation);
  12384. this.scaling.copyFrom(source.scaling);
  12385. if (source.rotationQuaternion) {
  12386. this.rotationQuaternion = source.rotationQuaternion.clone();
  12387. }
  12388. this.infiniteDistance = source.infiniteDistance;
  12389. this.setPivotMatrix(source.getPivotMatrix());
  12390. this.refreshBoundingInfo();
  12391. this._syncSubMeshes();
  12392. }
  12393. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12394. // Methods
  12395. get: function () {
  12396. return this._sourceMesh.receiveShadows;
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. Object.defineProperty(InstancedMesh.prototype, "material", {
  12402. get: function () {
  12403. return this._sourceMesh.material;
  12404. },
  12405. enumerable: true,
  12406. configurable: true
  12407. });
  12408. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12409. get: function () {
  12410. return this._sourceMesh.visibility;
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12416. get: function () {
  12417. return this._sourceMesh.skeleton;
  12418. },
  12419. enumerable: true,
  12420. configurable: true
  12421. });
  12422. InstancedMesh.prototype.getTotalVertices = function () {
  12423. return this._sourceMesh.getTotalVertices();
  12424. };
  12425. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12426. get: function () {
  12427. return this._sourceMesh;
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. InstancedMesh.prototype.getVerticesData = function (kind) {
  12433. return this._sourceMesh.getVerticesData(kind);
  12434. };
  12435. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12436. return this._sourceMesh.isVerticesDataPresent(kind);
  12437. };
  12438. InstancedMesh.prototype.getIndices = function () {
  12439. return this._sourceMesh.getIndices();
  12440. };
  12441. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12442. get: function () {
  12443. return this._sourceMesh._positions;
  12444. },
  12445. enumerable: true,
  12446. configurable: true
  12447. });
  12448. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12449. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12450. if (data) {
  12451. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12452. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12453. }
  12454. this._updateBoundingInfo();
  12455. };
  12456. InstancedMesh.prototype._preActivate = function () {
  12457. if (this._currentLOD) {
  12458. this._currentLOD._preActivate();
  12459. }
  12460. };
  12461. InstancedMesh.prototype._activate = function (renderId) {
  12462. if (this._currentLOD) {
  12463. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12464. }
  12465. };
  12466. InstancedMesh.prototype.getLOD = function (camera) {
  12467. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12468. if (this._currentLOD === this.sourceMesh) {
  12469. return this;
  12470. }
  12471. return this._currentLOD;
  12472. };
  12473. InstancedMesh.prototype._syncSubMeshes = function () {
  12474. this.releaseSubMeshes();
  12475. if (this._sourceMesh.subMeshes) {
  12476. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12477. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12478. }
  12479. }
  12480. };
  12481. InstancedMesh.prototype._generatePointsArray = function () {
  12482. return this._sourceMesh._generatePointsArray();
  12483. };
  12484. // Clone
  12485. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12486. var result = this._sourceMesh.createInstance(name);
  12487. // Deep copy
  12488. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12489. // Bounding info
  12490. this.refreshBoundingInfo();
  12491. // Parent
  12492. if (newParent) {
  12493. result.parent = newParent;
  12494. }
  12495. if (!doNotCloneChildren) {
  12496. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12497. var mesh = this.getScene().meshes[index];
  12498. if (mesh.parent === this) {
  12499. mesh.clone(mesh.name, result);
  12500. }
  12501. }
  12502. }
  12503. result.computeWorldMatrix(true);
  12504. return result;
  12505. };
  12506. // Dispoe
  12507. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12508. // Remove from mesh
  12509. var index = this._sourceMesh.instances.indexOf(this);
  12510. this._sourceMesh.instances.splice(index, 1);
  12511. _super.prototype.dispose.call(this, doNotRecurse);
  12512. };
  12513. return InstancedMesh;
  12514. })(BABYLON.AbstractMesh);
  12515. BABYLON.InstancedMesh = InstancedMesh;
  12516. })(BABYLON || (BABYLON = {}));
  12517. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12518. (function (BABYLON) {
  12519. var SubMesh = (function () {
  12520. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12521. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12522. this.materialIndex = materialIndex;
  12523. this.verticesStart = verticesStart;
  12524. this.verticesCount = verticesCount;
  12525. this.indexStart = indexStart;
  12526. this.indexCount = indexCount;
  12527. this._renderId = 0;
  12528. this._mesh = mesh;
  12529. this._renderingMesh = renderingMesh || mesh;
  12530. mesh.subMeshes.push(this);
  12531. this._id = mesh.subMeshes.length - 1;
  12532. if (createBoundingBox) {
  12533. this.refreshBoundingInfo();
  12534. mesh.computeWorldMatrix(true);
  12535. }
  12536. }
  12537. SubMesh.prototype.getBoundingInfo = function () {
  12538. return this._boundingInfo;
  12539. };
  12540. SubMesh.prototype.getMesh = function () {
  12541. return this._mesh;
  12542. };
  12543. SubMesh.prototype.getRenderingMesh = function () {
  12544. return this._renderingMesh;
  12545. };
  12546. SubMesh.prototype.getMaterial = function () {
  12547. var rootMaterial = this._renderingMesh.material;
  12548. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12549. var multiMaterial = rootMaterial;
  12550. return multiMaterial.getSubMaterial(this.materialIndex);
  12551. }
  12552. if (!rootMaterial) {
  12553. return this._mesh.getScene().defaultMaterial;
  12554. }
  12555. return rootMaterial;
  12556. };
  12557. // Methods
  12558. SubMesh.prototype.refreshBoundingInfo = function () {
  12559. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12560. if (!data) {
  12561. this._boundingInfo = this._mesh._boundingInfo;
  12562. return;
  12563. }
  12564. var indices = this._renderingMesh.getIndices();
  12565. var extend;
  12566. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12567. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12568. }
  12569. else {
  12570. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12571. }
  12572. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12573. };
  12574. SubMesh.prototype._checkCollision = function (collider) {
  12575. return this._boundingInfo._checkCollision(collider);
  12576. };
  12577. SubMesh.prototype.updateBoundingInfo = function (world) {
  12578. if (!this._boundingInfo) {
  12579. this.refreshBoundingInfo();
  12580. }
  12581. this._boundingInfo._update(world);
  12582. };
  12583. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12584. return this._boundingInfo.isInFrustum(frustumPlanes);
  12585. };
  12586. SubMesh.prototype.render = function () {
  12587. this._renderingMesh.render(this);
  12588. };
  12589. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12590. if (!this._linesIndexBuffer) {
  12591. var linesIndices = [];
  12592. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12593. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12594. }
  12595. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12596. this.linesIndexCount = linesIndices.length;
  12597. }
  12598. return this._linesIndexBuffer;
  12599. };
  12600. SubMesh.prototype.canIntersects = function (ray) {
  12601. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12602. };
  12603. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12604. var intersectInfo = null;
  12605. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12606. var p0 = positions[indices[index]];
  12607. var p1 = positions[indices[index + 1]];
  12608. var p2 = positions[indices[index + 2]];
  12609. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12610. if (currentIntersectInfo) {
  12611. if (currentIntersectInfo.distance < 0) {
  12612. continue;
  12613. }
  12614. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12615. intersectInfo = currentIntersectInfo;
  12616. intersectInfo.faceId = index / 3;
  12617. if (fastCheck) {
  12618. break;
  12619. }
  12620. }
  12621. }
  12622. }
  12623. return intersectInfo;
  12624. };
  12625. // Clone
  12626. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12627. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12628. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12629. return result;
  12630. };
  12631. // Dispose
  12632. SubMesh.prototype.dispose = function () {
  12633. if (this._linesIndexBuffer) {
  12634. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12635. this._linesIndexBuffer = null;
  12636. }
  12637. // Remove from mesh
  12638. var index = this._mesh.subMeshes.indexOf(this);
  12639. this._mesh.subMeshes.splice(index, 1);
  12640. };
  12641. // Statics
  12642. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12643. var minVertexIndex = Number.MAX_VALUE;
  12644. var maxVertexIndex = -Number.MAX_VALUE;
  12645. renderingMesh = renderingMesh || mesh;
  12646. var indices = renderingMesh.getIndices();
  12647. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12648. var vertexIndex = indices[index];
  12649. if (vertexIndex < minVertexIndex)
  12650. minVertexIndex = vertexIndex;
  12651. if (vertexIndex > maxVertexIndex)
  12652. maxVertexIndex = vertexIndex;
  12653. }
  12654. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12655. };
  12656. return SubMesh;
  12657. })();
  12658. BABYLON.SubMesh = SubMesh;
  12659. })(BABYLON || (BABYLON = {}));
  12660. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12661. (function (BABYLON) {
  12662. var BaseTexture = (function () {
  12663. function BaseTexture(scene) {
  12664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12665. this.hasAlpha = false;
  12666. this.getAlphaFromRGB = false;
  12667. this.level = 1;
  12668. this.isCube = false;
  12669. this.isRenderTarget = false;
  12670. this.animations = new Array();
  12671. this.coordinatesIndex = 0;
  12672. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12673. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12674. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12675. this.anisotropicFilteringLevel = 4;
  12676. this._scene = scene;
  12677. this._scene.textures.push(this);
  12678. }
  12679. BaseTexture.prototype.getScene = function () {
  12680. return this._scene;
  12681. };
  12682. BaseTexture.prototype.getTextureMatrix = function () {
  12683. return null;
  12684. };
  12685. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12686. return null;
  12687. };
  12688. BaseTexture.prototype.getInternalTexture = function () {
  12689. return this._texture;
  12690. };
  12691. BaseTexture.prototype.isReady = function () {
  12692. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12693. return true;
  12694. }
  12695. if (this._texture) {
  12696. return this._texture.isReady;
  12697. }
  12698. return false;
  12699. };
  12700. BaseTexture.prototype.getSize = function () {
  12701. if (this._texture._width) {
  12702. return { width: this._texture._width, height: this._texture._height };
  12703. }
  12704. if (this._texture._size) {
  12705. return { width: this._texture._size, height: this._texture._size };
  12706. }
  12707. return { width: 0, height: 0 };
  12708. };
  12709. BaseTexture.prototype.getBaseSize = function () {
  12710. if (!this.isReady())
  12711. return { width: 0, height: 0 };
  12712. if (this._texture._size) {
  12713. return { width: this._texture._size, height: this._texture._size };
  12714. }
  12715. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12716. };
  12717. BaseTexture.prototype.scale = function (ratio) {
  12718. };
  12719. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12720. get: function () {
  12721. return false;
  12722. },
  12723. enumerable: true,
  12724. configurable: true
  12725. });
  12726. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12727. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12728. for (var index = 0; index < texturesCache.length; index++) {
  12729. var texturesCacheEntry = texturesCache[index];
  12730. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12731. texturesCache.splice(index, 1);
  12732. return;
  12733. }
  12734. }
  12735. };
  12736. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12737. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12738. for (var index = 0; index < texturesCache.length; index++) {
  12739. var texturesCacheEntry = texturesCache[index];
  12740. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12741. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12742. texturesCacheEntry.references++;
  12743. return texturesCacheEntry;
  12744. }
  12745. }
  12746. }
  12747. return null;
  12748. };
  12749. BaseTexture.prototype.delayLoad = function () {
  12750. };
  12751. BaseTexture.prototype.releaseInternalTexture = function () {
  12752. if (!this._texture) {
  12753. return;
  12754. }
  12755. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12756. this._texture.references--;
  12757. // Final reference ?
  12758. if (this._texture.references === 0) {
  12759. var index = texturesCache.indexOf(this._texture);
  12760. texturesCache.splice(index, 1);
  12761. this._scene.getEngine()._releaseTexture(this._texture);
  12762. delete this._texture;
  12763. }
  12764. };
  12765. BaseTexture.prototype.clone = function () {
  12766. return null;
  12767. };
  12768. BaseTexture.prototype.dispose = function () {
  12769. // Remove from scene
  12770. var index = this._scene.textures.indexOf(this);
  12771. if (index >= 0) {
  12772. this._scene.textures.splice(index, 1);
  12773. }
  12774. if (this._texture === undefined) {
  12775. return;
  12776. }
  12777. this.releaseInternalTexture();
  12778. // Callback
  12779. if (this.onDispose) {
  12780. this.onDispose();
  12781. }
  12782. };
  12783. return BaseTexture;
  12784. })();
  12785. BABYLON.BaseTexture = BaseTexture;
  12786. })(BABYLON || (BABYLON = {}));
  12787. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12788. (function (BABYLON) {
  12789. var RenderingGroup = (function () {
  12790. function RenderingGroup(index, scene) {
  12791. this.index = index;
  12792. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12793. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12794. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12795. this._scene = scene;
  12796. }
  12797. RenderingGroup.prototype.render = function (customRenderFunction) {
  12798. if (customRenderFunction) {
  12799. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12800. return true;
  12801. }
  12802. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12803. return false;
  12804. }
  12805. var engine = this._scene.getEngine();
  12806. // Opaque
  12807. var subIndex;
  12808. var submesh;
  12809. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12810. submesh = this._opaqueSubMeshes.data[subIndex];
  12811. submesh.render();
  12812. }
  12813. // Alpha test
  12814. engine.setAlphaTesting(true);
  12815. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12816. submesh = this._alphaTestSubMeshes.data[subIndex];
  12817. submesh.render();
  12818. }
  12819. engine.setAlphaTesting(false);
  12820. // Transparent
  12821. if (this._transparentSubMeshes.length) {
  12822. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12823. submesh = this._transparentSubMeshes.data[subIndex];
  12824. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12825. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12826. }
  12827. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12828. sortedArray.sort(function (a, b) {
  12829. // Alpha index first
  12830. if (a._alphaIndex > b._alphaIndex) {
  12831. return 1;
  12832. }
  12833. if (a._alphaIndex < b._alphaIndex) {
  12834. return -1;
  12835. }
  12836. // Then distance to camera
  12837. if (a._distanceToCamera < b._distanceToCamera) {
  12838. return 1;
  12839. }
  12840. if (a._distanceToCamera > b._distanceToCamera) {
  12841. return -1;
  12842. }
  12843. return 0;
  12844. });
  12845. // Rendering
  12846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12847. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12848. submesh = sortedArray[subIndex];
  12849. submesh.render();
  12850. }
  12851. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12852. }
  12853. return true;
  12854. };
  12855. RenderingGroup.prototype.prepare = function () {
  12856. this._opaqueSubMeshes.reset();
  12857. this._transparentSubMeshes.reset();
  12858. this._alphaTestSubMeshes.reset();
  12859. };
  12860. RenderingGroup.prototype.dispatch = function (subMesh) {
  12861. var material = subMesh.getMaterial();
  12862. var mesh = subMesh.getMesh();
  12863. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12864. this._transparentSubMeshes.push(subMesh);
  12865. }
  12866. else if (material.needAlphaTesting()) {
  12867. this._alphaTestSubMeshes.push(subMesh);
  12868. }
  12869. else {
  12870. this._opaqueSubMeshes.push(subMesh); // Opaque
  12871. }
  12872. };
  12873. return RenderingGroup;
  12874. })();
  12875. BABYLON.RenderingGroup = RenderingGroup;
  12876. })(BABYLON || (BABYLON = {}));
  12877. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12878. (function (BABYLON) {
  12879. var RenderingManager = (function () {
  12880. function RenderingManager(scene) {
  12881. this._renderingGroups = new Array();
  12882. this._scene = scene;
  12883. }
  12884. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12885. if (this._scene._activeParticleSystems.length === 0) {
  12886. return;
  12887. }
  12888. // Particles
  12889. var beforeParticlesDate = BABYLON.Tools.Now;
  12890. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12891. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12892. if (particleSystem.renderingGroupId !== index) {
  12893. continue;
  12894. }
  12895. this._clearDepthBuffer();
  12896. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12897. this._scene._activeParticles += particleSystem.render();
  12898. }
  12899. }
  12900. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12901. };
  12902. RenderingManager.prototype._renderSprites = function (index) {
  12903. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12904. return;
  12905. }
  12906. // Sprites
  12907. var beforeSpritessDate = BABYLON.Tools.Now;
  12908. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12909. var spriteManager = this._scene.spriteManagers[id];
  12910. if (spriteManager.renderingGroupId === index) {
  12911. this._clearDepthBuffer();
  12912. spriteManager.render();
  12913. }
  12914. }
  12915. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12916. };
  12917. RenderingManager.prototype._clearDepthBuffer = function () {
  12918. if (this._depthBufferAlreadyCleaned) {
  12919. return;
  12920. }
  12921. this._scene.getEngine().clear(0, false, true);
  12922. this._depthBufferAlreadyCleaned = true;
  12923. };
  12924. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12925. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12926. this._depthBufferAlreadyCleaned = false;
  12927. var renderingGroup = this._renderingGroups[index];
  12928. var needToStepBack = false;
  12929. if (renderingGroup) {
  12930. this._clearDepthBuffer();
  12931. if (!renderingGroup.render(customRenderFunction)) {
  12932. this._renderingGroups.splice(index, 1);
  12933. needToStepBack = true;
  12934. }
  12935. }
  12936. if (renderSprites) {
  12937. this._renderSprites(index);
  12938. }
  12939. if (renderParticles) {
  12940. this._renderParticles(index, activeMeshes);
  12941. }
  12942. if (needToStepBack) {
  12943. index--;
  12944. }
  12945. }
  12946. };
  12947. RenderingManager.prototype.reset = function () {
  12948. for (var index in this._renderingGroups) {
  12949. var renderingGroup = this._renderingGroups[index];
  12950. renderingGroup.prepare();
  12951. }
  12952. };
  12953. RenderingManager.prototype.dispatch = function (subMesh) {
  12954. var mesh = subMesh.getMesh();
  12955. var renderingGroupId = mesh.renderingGroupId || 0;
  12956. if (!this._renderingGroups[renderingGroupId]) {
  12957. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12958. }
  12959. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12960. };
  12961. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12962. return RenderingManager;
  12963. })();
  12964. BABYLON.RenderingManager = RenderingManager;
  12965. })(BABYLON || (BABYLON = {}));
  12966. //# sourceMappingURL=babylon.renderingManager.js.map
  12967. var BABYLON;
  12968. (function (BABYLON) {
  12969. var Texture = (function (_super) {
  12970. __extends(Texture, _super);
  12971. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12972. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12973. if (onLoad === void 0) { onLoad = null; }
  12974. if (onError === void 0) { onError = null; }
  12975. if (buffer === void 0) { buffer = null; }
  12976. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12977. _super.call(this, scene);
  12978. this.uOffset = 0;
  12979. this.vOffset = 0;
  12980. this.uScale = 1.0;
  12981. this.vScale = 1.0;
  12982. this.uAng = 0;
  12983. this.vAng = 0;
  12984. this.wAng = 0;
  12985. this.name = url;
  12986. this.url = url;
  12987. this._noMipmap = noMipmap;
  12988. this._invertY = invertY;
  12989. this._samplingMode = samplingMode;
  12990. this._buffer = buffer;
  12991. this._deleteBuffer = deleteBuffer;
  12992. if (!url) {
  12993. return;
  12994. }
  12995. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12996. if (!this._texture) {
  12997. if (!scene.useDelayedTextureLoading) {
  12998. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12999. if (deleteBuffer) {
  13000. delete this._buffer;
  13001. }
  13002. }
  13003. else {
  13004. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13005. }
  13006. }
  13007. }
  13008. Texture.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, this._samplingMode);
  13014. if (!this._texture) {
  13015. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13016. if (this._deleteBuffer) {
  13017. delete this._buffer;
  13018. }
  13019. }
  13020. };
  13021. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13022. if (!this._texture) {
  13023. return;
  13024. }
  13025. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13026. };
  13027. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13028. x -= this.uOffset + 0.5;
  13029. y -= this.vOffset + 0.5;
  13030. z -= 0.5;
  13031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13032. t.x *= this.uScale;
  13033. t.y *= this.vScale;
  13034. t.x += 0.5;
  13035. t.y += 0.5;
  13036. t.z += 0.5;
  13037. };
  13038. Texture.prototype.getTextureMatrix = function () {
  13039. 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) {
  13040. return this._cachedTextureMatrix;
  13041. }
  13042. this._cachedUOffset = this.uOffset;
  13043. this._cachedVOffset = this.vOffset;
  13044. this._cachedUScale = this.uScale;
  13045. this._cachedVScale = this.vScale;
  13046. this._cachedUAng = this.uAng;
  13047. this._cachedVAng = this.vAng;
  13048. this._cachedWAng = this.wAng;
  13049. if (!this._cachedTextureMatrix) {
  13050. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13051. this._rowGenerationMatrix = new BABYLON.Matrix();
  13052. this._t0 = BABYLON.Vector3.Zero();
  13053. this._t1 = BABYLON.Vector3.Zero();
  13054. this._t2 = BABYLON.Vector3.Zero();
  13055. }
  13056. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13057. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13058. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13059. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13060. this._t1.subtractInPlace(this._t0);
  13061. this._t2.subtractInPlace(this._t0);
  13062. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13063. this._cachedTextureMatrix.m[0] = this._t1.x;
  13064. this._cachedTextureMatrix.m[1] = this._t1.y;
  13065. this._cachedTextureMatrix.m[2] = this._t1.z;
  13066. this._cachedTextureMatrix.m[4] = this._t2.x;
  13067. this._cachedTextureMatrix.m[5] = this._t2.y;
  13068. this._cachedTextureMatrix.m[6] = this._t2.z;
  13069. this._cachedTextureMatrix.m[8] = this._t0.x;
  13070. this._cachedTextureMatrix.m[9] = this._t0.y;
  13071. this._cachedTextureMatrix.m[10] = this._t0.z;
  13072. return this._cachedTextureMatrix;
  13073. };
  13074. Texture.prototype.getReflectionTextureMatrix = function () {
  13075. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13076. return this._cachedTextureMatrix;
  13077. }
  13078. if (!this._cachedTextureMatrix) {
  13079. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13080. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13081. }
  13082. this._cachedCoordinatesMode = this.coordinatesMode;
  13083. switch (this.coordinatesMode) {
  13084. case Texture.SPHERICAL_MODE:
  13085. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13086. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13087. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13088. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13089. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13090. break;
  13091. case Texture.PLANAR_MODE:
  13092. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13093. this._cachedTextureMatrix[0] = this.uScale;
  13094. this._cachedTextureMatrix[5] = this.vScale;
  13095. this._cachedTextureMatrix[12] = this.uOffset;
  13096. this._cachedTextureMatrix[13] = this.vOffset;
  13097. break;
  13098. case Texture.PROJECTION_MODE:
  13099. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13100. this._projectionModeMatrix.m[0] = 0.5;
  13101. this._projectionModeMatrix.m[5] = -0.5;
  13102. this._projectionModeMatrix.m[10] = 0.0;
  13103. this._projectionModeMatrix.m[12] = 0.5;
  13104. this._projectionModeMatrix.m[13] = 0.5;
  13105. this._projectionModeMatrix.m[14] = 1.0;
  13106. this._projectionModeMatrix.m[15] = 1.0;
  13107. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13108. break;
  13109. default:
  13110. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13111. break;
  13112. }
  13113. return this._cachedTextureMatrix;
  13114. };
  13115. Texture.prototype.clone = function () {
  13116. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13117. // Base texture
  13118. newTexture.hasAlpha = this.hasAlpha;
  13119. newTexture.level = this.level;
  13120. newTexture.wrapU = this.wrapU;
  13121. newTexture.wrapV = this.wrapV;
  13122. newTexture.coordinatesIndex = this.coordinatesIndex;
  13123. newTexture.coordinatesMode = this.coordinatesMode;
  13124. // Texture
  13125. newTexture.uOffset = this.uOffset;
  13126. newTexture.vOffset = this.vOffset;
  13127. newTexture.uScale = this.uScale;
  13128. newTexture.vScale = this.vScale;
  13129. newTexture.uAng = this.uAng;
  13130. newTexture.vAng = this.vAng;
  13131. newTexture.wAng = this.wAng;
  13132. return newTexture;
  13133. };
  13134. // Statics
  13135. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13136. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13137. if (onLoad === void 0) { onLoad = null; }
  13138. if (onError === void 0) { onError = null; }
  13139. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13140. };
  13141. // Constants
  13142. Texture.NEAREST_SAMPLINGMODE = 1;
  13143. Texture.BILINEAR_SAMPLINGMODE = 2;
  13144. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13145. Texture.EXPLICIT_MODE = 0;
  13146. Texture.SPHERICAL_MODE = 1;
  13147. Texture.PLANAR_MODE = 2;
  13148. Texture.CUBIC_MODE = 3;
  13149. Texture.PROJECTION_MODE = 4;
  13150. Texture.SKYBOX_MODE = 5;
  13151. Texture.CLAMP_ADDRESSMODE = 0;
  13152. Texture.WRAP_ADDRESSMODE = 1;
  13153. Texture.MIRROR_ADDRESSMODE = 2;
  13154. return Texture;
  13155. })(BABYLON.BaseTexture);
  13156. BABYLON.Texture = Texture;
  13157. })(BABYLON || (BABYLON = {}));
  13158. //# sourceMappingURL=babylon.texture.js.map
  13159. var BABYLON;
  13160. (function (BABYLON) {
  13161. var CubeTexture = (function (_super) {
  13162. __extends(CubeTexture, _super);
  13163. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13164. _super.call(this, scene);
  13165. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13166. this.name = rootUrl;
  13167. this.url = rootUrl;
  13168. this._noMipmap = noMipmap;
  13169. this.hasAlpha = false;
  13170. this._texture = this._getFromCache(rootUrl, noMipmap);
  13171. if (!extensions) {
  13172. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13173. }
  13174. this._extensions = extensions;
  13175. if (!this._texture) {
  13176. if (!scene.useDelayedTextureLoading) {
  13177. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13178. }
  13179. else {
  13180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13181. }
  13182. }
  13183. this.isCube = true;
  13184. this._textureMatrix = BABYLON.Matrix.Identity();
  13185. }
  13186. CubeTexture.prototype.clone = function () {
  13187. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13188. // Base texture
  13189. newTexture.level = this.level;
  13190. newTexture.wrapU = this.wrapU;
  13191. newTexture.wrapV = this.wrapV;
  13192. newTexture.coordinatesIndex = this.coordinatesIndex;
  13193. newTexture.coordinatesMode = this.coordinatesMode;
  13194. return newTexture;
  13195. };
  13196. // Methods
  13197. CubeTexture.prototype.delayLoad = function () {
  13198. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13199. return;
  13200. }
  13201. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13202. this._texture = this._getFromCache(this.url, this._noMipmap);
  13203. if (!this._texture) {
  13204. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13205. }
  13206. };
  13207. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13208. return this._textureMatrix;
  13209. };
  13210. return CubeTexture;
  13211. })(BABYLON.BaseTexture);
  13212. BABYLON.CubeTexture = CubeTexture;
  13213. })(BABYLON || (BABYLON = {}));
  13214. //# sourceMappingURL=babylon.cubeTexture.js.map
  13215. var BABYLON;
  13216. (function (BABYLON) {
  13217. var RenderTargetTexture = (function (_super) {
  13218. __extends(RenderTargetTexture, _super);
  13219. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13220. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13221. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13222. _super.call(this, null, scene, !generateMipMaps);
  13223. this.renderList = new Array();
  13224. this.renderParticles = true;
  13225. this.renderSprites = false;
  13226. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13227. this._currentRefreshId = -1;
  13228. this._refreshRate = 1;
  13229. this.name = name;
  13230. this.isRenderTarget = true;
  13231. this._size = size;
  13232. this._generateMipMaps = generateMipMaps;
  13233. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13234. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13235. // Rendering groups
  13236. this._renderingManager = new BABYLON.RenderingManager(scene);
  13237. }
  13238. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13239. this._currentRefreshId = -1;
  13240. };
  13241. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13242. get: function () {
  13243. return this._refreshRate;
  13244. },
  13245. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13246. set: function (value) {
  13247. this._refreshRate = value;
  13248. this.resetRefreshCounter();
  13249. },
  13250. enumerable: true,
  13251. configurable: true
  13252. });
  13253. RenderTargetTexture.prototype._shouldRender = function () {
  13254. if (this._currentRefreshId === -1) {
  13255. this._currentRefreshId = 1;
  13256. return true;
  13257. }
  13258. if (this.refreshRate === this._currentRefreshId) {
  13259. this._currentRefreshId = 1;
  13260. return true;
  13261. }
  13262. this._currentRefreshId++;
  13263. return false;
  13264. };
  13265. RenderTargetTexture.prototype.isReady = function () {
  13266. if (!this.getScene().renderTargetsEnabled) {
  13267. return false;
  13268. }
  13269. return _super.prototype.isReady.call(this);
  13270. };
  13271. RenderTargetTexture.prototype.getRenderSize = function () {
  13272. return this._size;
  13273. };
  13274. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13275. get: function () {
  13276. return true;
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. RenderTargetTexture.prototype.scale = function (ratio) {
  13282. var newSize = this._size * ratio;
  13283. this.resize(newSize, this._generateMipMaps);
  13284. };
  13285. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13286. this.releaseInternalTexture();
  13287. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13288. };
  13289. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13290. var scene = this.getScene();
  13291. var engine = scene.getEngine();
  13292. if (this._waitingRenderList) {
  13293. this.renderList = [];
  13294. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13295. var id = this._waitingRenderList[index];
  13296. this.renderList.push(scene.getMeshByID(id));
  13297. }
  13298. delete this._waitingRenderList;
  13299. }
  13300. if (this.renderList && this.renderList.length === 0) {
  13301. return;
  13302. }
  13303. // Bind
  13304. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13305. engine.bindFramebuffer(this._texture);
  13306. }
  13307. this._renderingManager.reset();
  13308. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13309. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13310. var mesh = currentRenderList[meshIndex];
  13311. if (mesh) {
  13312. if (!mesh.isReady()) {
  13313. // Reset _currentRefreshId
  13314. this.resetRefreshCounter();
  13315. continue;
  13316. }
  13317. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13318. mesh._activate(scene.getRenderId());
  13319. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13320. var subMesh = mesh.subMeshes[subIndex];
  13321. scene._activeVertices += subMesh.indexCount;
  13322. this._renderingManager.dispatch(subMesh);
  13323. }
  13324. }
  13325. }
  13326. }
  13327. if (this.onBeforeRender) {
  13328. this.onBeforeRender();
  13329. }
  13330. // Clear
  13331. if (this.onClear) {
  13332. this.onClear(engine);
  13333. }
  13334. else {
  13335. engine.clear(scene.clearColor, true, true);
  13336. }
  13337. if (!this._doNotChangeAspectRatio) {
  13338. scene.updateTransformMatrix(true);
  13339. }
  13340. // Render
  13341. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13342. if (useCameraPostProcess) {
  13343. scene.postProcessManager._finalizeFrame(false, this._texture);
  13344. }
  13345. if (!this._doNotChangeAspectRatio) {
  13346. scene.updateTransformMatrix(true);
  13347. }
  13348. if (this.onAfterRender) {
  13349. this.onAfterRender();
  13350. }
  13351. // Dump ?
  13352. if (dumpForDebug) {
  13353. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13354. }
  13355. // Unbind
  13356. engine.unBindFramebuffer(this._texture);
  13357. if (this.onAfterUnbind) {
  13358. this.onAfterUnbind();
  13359. }
  13360. };
  13361. RenderTargetTexture.prototype.clone = function () {
  13362. var textureSize = this.getSize();
  13363. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13364. // Base texture
  13365. newTexture.hasAlpha = this.hasAlpha;
  13366. newTexture.level = this.level;
  13367. // RenderTarget Texture
  13368. newTexture.coordinatesMode = this.coordinatesMode;
  13369. newTexture.renderList = this.renderList.slice(0);
  13370. return newTexture;
  13371. };
  13372. return RenderTargetTexture;
  13373. })(BABYLON.Texture);
  13374. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13375. })(BABYLON || (BABYLON = {}));
  13376. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13377. var BABYLON;
  13378. (function (BABYLON) {
  13379. var ProceduralTexture = (function (_super) {
  13380. __extends(ProceduralTexture, _super);
  13381. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13382. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13383. _super.call(this, null, scene, !generateMipMaps);
  13384. this._currentRefreshId = -1;
  13385. this._refreshRate = 1;
  13386. this._vertexDeclaration = [2];
  13387. this._vertexStrideSize = 2 * 4;
  13388. this._uniforms = new Array();
  13389. this._samplers = new Array();
  13390. this._textures = new Array();
  13391. this._floats = new Array();
  13392. this._floatsArrays = {};
  13393. this._colors3 = new Array();
  13394. this._colors4 = new Array();
  13395. this._vectors2 = new Array();
  13396. this._vectors3 = new Array();
  13397. this._matrices = new Array();
  13398. this._fallbackTextureUsed = false;
  13399. scene._proceduralTextures.push(this);
  13400. this.name = name;
  13401. this.isRenderTarget = true;
  13402. this._size = size;
  13403. this._generateMipMaps = generateMipMaps;
  13404. this.setFragment(fragment);
  13405. this._fallbackTexture = fallbackTexture;
  13406. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13407. // VBO
  13408. var vertices = [];
  13409. vertices.push(1, 1);
  13410. vertices.push(-1, 1);
  13411. vertices.push(-1, -1);
  13412. vertices.push(1, -1);
  13413. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13414. // Indices
  13415. var indices = [];
  13416. indices.push(0);
  13417. indices.push(1);
  13418. indices.push(2);
  13419. indices.push(0);
  13420. indices.push(2);
  13421. indices.push(3);
  13422. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13423. }
  13424. ProceduralTexture.prototype.reset = function () {
  13425. if (this._effect === undefined) {
  13426. return;
  13427. }
  13428. var engine = this.getScene().getEngine();
  13429. engine._releaseEffect(this._effect);
  13430. };
  13431. ProceduralTexture.prototype.isReady = function () {
  13432. var _this = this;
  13433. var engine = this.getScene().getEngine();
  13434. var shaders;
  13435. if (!this._fragment) {
  13436. return false;
  13437. }
  13438. if (this._fallbackTextureUsed) {
  13439. return true;
  13440. }
  13441. if (this._fragment.fragmentElement !== undefined) {
  13442. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13443. }
  13444. else {
  13445. shaders = { vertex: "procedural", fragment: this._fragment };
  13446. }
  13447. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13448. _this.releaseInternalTexture();
  13449. if (_this._fallbackTexture) {
  13450. _this._texture = _this._fallbackTexture._texture;
  13451. _this._texture.references++;
  13452. }
  13453. _this._fallbackTextureUsed = true;
  13454. });
  13455. return this._effect.isReady();
  13456. };
  13457. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13458. this._currentRefreshId = -1;
  13459. };
  13460. ProceduralTexture.prototype.setFragment = function (fragment) {
  13461. this._fragment = fragment;
  13462. };
  13463. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13464. get: function () {
  13465. return this._refreshRate;
  13466. },
  13467. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13468. set: function (value) {
  13469. this._refreshRate = value;
  13470. this.resetRefreshCounter();
  13471. },
  13472. enumerable: true,
  13473. configurable: true
  13474. });
  13475. ProceduralTexture.prototype._shouldRender = function () {
  13476. if (!this.isReady() || !this._texture) {
  13477. return false;
  13478. }
  13479. if (this._fallbackTextureUsed) {
  13480. return false;
  13481. }
  13482. if (this._currentRefreshId === -1) {
  13483. this._currentRefreshId = 1;
  13484. return true;
  13485. }
  13486. if (this.refreshRate === this._currentRefreshId) {
  13487. this._currentRefreshId = 1;
  13488. return true;
  13489. }
  13490. this._currentRefreshId++;
  13491. return false;
  13492. };
  13493. ProceduralTexture.prototype.getRenderSize = function () {
  13494. return this._size;
  13495. };
  13496. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13497. if (this._fallbackTextureUsed) {
  13498. return;
  13499. }
  13500. this.releaseInternalTexture();
  13501. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13502. };
  13503. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13504. if (this._uniforms.indexOf(uniformName) === -1) {
  13505. this._uniforms.push(uniformName);
  13506. }
  13507. };
  13508. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13509. if (this._samplers.indexOf(name) === -1) {
  13510. this._samplers.push(name);
  13511. }
  13512. this._textures[name] = texture;
  13513. return this;
  13514. };
  13515. ProceduralTexture.prototype.setFloat = function (name, value) {
  13516. this._checkUniform(name);
  13517. this._floats[name] = value;
  13518. return this;
  13519. };
  13520. ProceduralTexture.prototype.setFloats = function (name, value) {
  13521. this._checkUniform(name);
  13522. this._floatsArrays[name] = value;
  13523. return this;
  13524. };
  13525. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13526. this._checkUniform(name);
  13527. this._colors3[name] = value;
  13528. return this;
  13529. };
  13530. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13531. this._checkUniform(name);
  13532. this._colors4[name] = value;
  13533. return this;
  13534. };
  13535. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13536. this._checkUniform(name);
  13537. this._vectors2[name] = value;
  13538. return this;
  13539. };
  13540. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13541. this._checkUniform(name);
  13542. this._vectors3[name] = value;
  13543. return this;
  13544. };
  13545. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13546. this._checkUniform(name);
  13547. this._matrices[name] = value;
  13548. return this;
  13549. };
  13550. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13551. var scene = this.getScene();
  13552. var engine = scene.getEngine();
  13553. engine.bindFramebuffer(this._texture);
  13554. // Clear
  13555. engine.clear(scene.clearColor, true, true);
  13556. // Render
  13557. engine.enableEffect(this._effect);
  13558. engine.setState(false);
  13559. for (var name in this._textures) {
  13560. this._effect.setTexture(name, this._textures[name]);
  13561. }
  13562. for (name in this._floats) {
  13563. this._effect.setFloat(name, this._floats[name]);
  13564. }
  13565. for (name in this._floatsArrays) {
  13566. this._effect.setArray(name, this._floatsArrays[name]);
  13567. }
  13568. for (name in this._colors3) {
  13569. this._effect.setColor3(name, this._colors3[name]);
  13570. }
  13571. for (name in this._colors4) {
  13572. var color = this._colors4[name];
  13573. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13574. }
  13575. for (name in this._vectors2) {
  13576. this._effect.setVector2(name, this._vectors2[name]);
  13577. }
  13578. for (name in this._vectors3) {
  13579. this._effect.setVector3(name, this._vectors3[name]);
  13580. }
  13581. for (name in this._matrices) {
  13582. this._effect.setMatrix(name, this._matrices[name]);
  13583. }
  13584. // VBOs
  13585. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13586. // Draw order
  13587. engine.draw(true, 0, 6);
  13588. // Unbind
  13589. engine.unBindFramebuffer(this._texture);
  13590. };
  13591. ProceduralTexture.prototype.clone = function () {
  13592. var textureSize = this.getSize();
  13593. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13594. // Base texture
  13595. newTexture.hasAlpha = this.hasAlpha;
  13596. newTexture.level = this.level;
  13597. // RenderTarget Texture
  13598. newTexture.coordinatesMode = this.coordinatesMode;
  13599. return newTexture;
  13600. };
  13601. ProceduralTexture.prototype.dispose = function () {
  13602. var index = this.getScene()._proceduralTextures.indexOf(this);
  13603. if (index >= 0) {
  13604. this.getScene()._proceduralTextures.splice(index, 1);
  13605. }
  13606. _super.prototype.dispose.call(this);
  13607. };
  13608. return ProceduralTexture;
  13609. })(BABYLON.Texture);
  13610. BABYLON.ProceduralTexture = ProceduralTexture;
  13611. })(BABYLON || (BABYLON = {}));
  13612. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13613. var BABYLON;
  13614. (function (BABYLON) {
  13615. var WoodProceduralTexture = (function (_super) {
  13616. __extends(WoodProceduralTexture, _super);
  13617. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13618. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13619. this._ampScale = 100.0;
  13620. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13621. this.updateShaderUniforms();
  13622. this.refreshRate = 0;
  13623. }
  13624. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13625. this.setFloat("ampScale", this._ampScale);
  13626. this.setColor3("woodColor", this._woodColor);
  13627. };
  13628. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13629. get: function () {
  13630. return this._ampScale;
  13631. },
  13632. set: function (value) {
  13633. this._ampScale = value;
  13634. this.updateShaderUniforms();
  13635. },
  13636. enumerable: true,
  13637. configurable: true
  13638. });
  13639. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13640. get: function () {
  13641. return this._woodColor;
  13642. },
  13643. set: function (value) {
  13644. this._woodColor = value;
  13645. this.updateShaderUniforms();
  13646. },
  13647. enumerable: true,
  13648. configurable: true
  13649. });
  13650. return WoodProceduralTexture;
  13651. })(BABYLON.ProceduralTexture);
  13652. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13653. var FireProceduralTexture = (function (_super) {
  13654. __extends(FireProceduralTexture, _super);
  13655. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13656. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13657. this._time = 0.0;
  13658. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13659. this._autoGenerateTime = true;
  13660. this._alphaThreshold = 0.5;
  13661. this._fireColors = FireProceduralTexture.RedFireColors;
  13662. this.updateShaderUniforms();
  13663. this.refreshRate = 1;
  13664. }
  13665. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13666. this.setFloat("time", this._time);
  13667. this.setVector2("speed", this._speed);
  13668. this.setColor3("c1", this._fireColors[0]);
  13669. this.setColor3("c2", this._fireColors[1]);
  13670. this.setColor3("c3", this._fireColors[2]);
  13671. this.setColor3("c4", this._fireColors[3]);
  13672. this.setColor3("c5", this._fireColors[4]);
  13673. this.setColor3("c6", this._fireColors[5]);
  13674. this.setFloat("alphaThreshold", this._alphaThreshold);
  13675. };
  13676. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13677. if (this._autoGenerateTime) {
  13678. this._time += this.getScene().getAnimationRatio() * 0.03;
  13679. this.updateShaderUniforms();
  13680. }
  13681. _super.prototype.render.call(this, useCameraPostProcess);
  13682. };
  13683. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13684. get: function () {
  13685. return [
  13686. new BABYLON.Color3(0.5, 0.0, 1.0),
  13687. new BABYLON.Color3(0.9, 0.0, 1.0),
  13688. new BABYLON.Color3(0.2, 0.0, 1.0),
  13689. new BABYLON.Color3(1.0, 0.9, 1.0),
  13690. new BABYLON.Color3(0.1, 0.1, 1.0),
  13691. new BABYLON.Color3(0.9, 0.9, 1.0)
  13692. ];
  13693. },
  13694. enumerable: true,
  13695. configurable: true
  13696. });
  13697. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13698. get: function () {
  13699. return [
  13700. new BABYLON.Color3(0.5, 1.0, 0.0),
  13701. new BABYLON.Color3(0.5, 1.0, 0.0),
  13702. new BABYLON.Color3(0.3, 0.4, 0.0),
  13703. new BABYLON.Color3(0.5, 1.0, 0.0),
  13704. new BABYLON.Color3(0.2, 0.0, 0.0),
  13705. new BABYLON.Color3(0.5, 1.0, 0.0)
  13706. ];
  13707. },
  13708. enumerable: true,
  13709. configurable: true
  13710. });
  13711. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13712. get: function () {
  13713. return [
  13714. new BABYLON.Color3(0.5, 0.0, 0.1),
  13715. new BABYLON.Color3(0.9, 0.0, 0.0),
  13716. new BABYLON.Color3(0.2, 0.0, 0.0),
  13717. new BABYLON.Color3(1.0, 0.9, 0.0),
  13718. new BABYLON.Color3(0.1, 0.1, 0.1),
  13719. new BABYLON.Color3(0.9, 0.9, 0.9)
  13720. ];
  13721. },
  13722. enumerable: true,
  13723. configurable: true
  13724. });
  13725. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13726. get: function () {
  13727. return [
  13728. new BABYLON.Color3(0.1, 0.0, 0.5),
  13729. new BABYLON.Color3(0.0, 0.0, 0.5),
  13730. new BABYLON.Color3(0.1, 0.0, 0.2),
  13731. new BABYLON.Color3(0.0, 0.0, 1.0),
  13732. new BABYLON.Color3(0.1, 0.2, 0.3),
  13733. new BABYLON.Color3(0.0, 0.2, 0.9)
  13734. ];
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13740. get: function () {
  13741. return this._fireColors;
  13742. },
  13743. set: function (value) {
  13744. this._fireColors = value;
  13745. this.updateShaderUniforms();
  13746. },
  13747. enumerable: true,
  13748. configurable: true
  13749. });
  13750. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13751. get: function () {
  13752. return this._time;
  13753. },
  13754. set: function (value) {
  13755. this._time = value;
  13756. this.updateShaderUniforms();
  13757. },
  13758. enumerable: true,
  13759. configurable: true
  13760. });
  13761. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13762. get: function () {
  13763. return this._speed;
  13764. },
  13765. set: function (value) {
  13766. this._speed = value;
  13767. this.updateShaderUniforms();
  13768. },
  13769. enumerable: true,
  13770. configurable: true
  13771. });
  13772. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13773. get: function () {
  13774. return this._alphaThreshold;
  13775. },
  13776. set: function (value) {
  13777. this._alphaThreshold = value;
  13778. this.updateShaderUniforms();
  13779. },
  13780. enumerable: true,
  13781. configurable: true
  13782. });
  13783. return FireProceduralTexture;
  13784. })(BABYLON.ProceduralTexture);
  13785. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13786. var CloudProceduralTexture = (function (_super) {
  13787. __extends(CloudProceduralTexture, _super);
  13788. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13789. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13790. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13791. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13792. this.updateShaderUniforms();
  13793. this.refreshRate = 0;
  13794. }
  13795. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13796. this.setColor3("skyColor", this._skyColor);
  13797. this.setColor3("cloudColor", this._cloudColor);
  13798. };
  13799. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13800. get: function () {
  13801. return this._skyColor;
  13802. },
  13803. set: function (value) {
  13804. this._skyColor = value;
  13805. this.updateShaderUniforms();
  13806. },
  13807. enumerable: true,
  13808. configurable: true
  13809. });
  13810. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13811. get: function () {
  13812. return this._cloudColor;
  13813. },
  13814. set: function (value) {
  13815. this._cloudColor = value;
  13816. this.updateShaderUniforms();
  13817. },
  13818. enumerable: true,
  13819. configurable: true
  13820. });
  13821. return CloudProceduralTexture;
  13822. })(BABYLON.ProceduralTexture);
  13823. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13824. var GrassProceduralTexture = (function (_super) {
  13825. __extends(GrassProceduralTexture, _super);
  13826. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13827. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13828. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13829. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13830. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13831. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13832. this._grassColors = [
  13833. new BABYLON.Color3(0.29, 0.38, 0.02),
  13834. new BABYLON.Color3(0.36, 0.49, 0.09),
  13835. new BABYLON.Color3(0.51, 0.6, 0.28)
  13836. ];
  13837. this.updateShaderUniforms();
  13838. this.refreshRate = 0;
  13839. }
  13840. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13841. this.setColor3("herb1Color", this._grassColors[0]);
  13842. this.setColor3("herb2Color", this._grassColors[1]);
  13843. this.setColor3("herb3Color", this._grassColors[2]);
  13844. this.setColor3("groundColor", this._groundColor);
  13845. };
  13846. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13847. get: function () {
  13848. return this._grassColors;
  13849. },
  13850. set: function (value) {
  13851. this._grassColors = value;
  13852. this.updateShaderUniforms();
  13853. },
  13854. enumerable: true,
  13855. configurable: true
  13856. });
  13857. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13858. get: function () {
  13859. return this._groundColor;
  13860. },
  13861. set: function (value) {
  13862. this.groundColor = value;
  13863. this.updateShaderUniforms();
  13864. },
  13865. enumerable: true,
  13866. configurable: true
  13867. });
  13868. return GrassProceduralTexture;
  13869. })(BABYLON.ProceduralTexture);
  13870. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13871. var RoadProceduralTexture = (function (_super) {
  13872. __extends(RoadProceduralTexture, _super);
  13873. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13874. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13875. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13876. this.updateShaderUniforms();
  13877. this.refreshRate = 0;
  13878. }
  13879. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13880. this.setColor3("roadColor", this._roadColor);
  13881. };
  13882. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13883. get: function () {
  13884. return this._roadColor;
  13885. },
  13886. set: function (value) {
  13887. this._roadColor = value;
  13888. this.updateShaderUniforms();
  13889. },
  13890. enumerable: true,
  13891. configurable: true
  13892. });
  13893. return RoadProceduralTexture;
  13894. })(BABYLON.ProceduralTexture);
  13895. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13896. var BrickProceduralTexture = (function (_super) {
  13897. __extends(BrickProceduralTexture, _super);
  13898. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13899. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13900. this._numberOfBricksHeight = 15;
  13901. this._numberOfBricksWidth = 5;
  13902. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13903. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13904. this.updateShaderUniforms();
  13905. this.refreshRate = 0;
  13906. }
  13907. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13908. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13909. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13910. this.setColor3("brickColor", this._brickColor);
  13911. this.setColor3("jointColor", this._jointColor);
  13912. };
  13913. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13914. get: function () {
  13915. return this._numberOfBricksHeight;
  13916. },
  13917. set: function (value) {
  13918. this._numberOfBricksHeight = value;
  13919. this.updateShaderUniforms();
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13925. get: function () {
  13926. return this._numberOfBricksWidth;
  13927. },
  13928. set: function (value) {
  13929. this._numberOfBricksHeight = value;
  13930. this.updateShaderUniforms();
  13931. },
  13932. enumerable: true,
  13933. configurable: true
  13934. });
  13935. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13936. get: function () {
  13937. return this._jointColor;
  13938. },
  13939. set: function (value) {
  13940. this._jointColor = value;
  13941. this.updateShaderUniforms();
  13942. },
  13943. enumerable: true,
  13944. configurable: true
  13945. });
  13946. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13947. get: function () {
  13948. return this._brickColor;
  13949. },
  13950. set: function (value) {
  13951. this._brickColor = value;
  13952. this.updateShaderUniforms();
  13953. },
  13954. enumerable: true,
  13955. configurable: true
  13956. });
  13957. return BrickProceduralTexture;
  13958. })(BABYLON.ProceduralTexture);
  13959. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13960. var MarbleProceduralTexture = (function (_super) {
  13961. __extends(MarbleProceduralTexture, _super);
  13962. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13963. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13964. this._numberOfTilesHeight = 3;
  13965. this._numberOfTilesWidth = 3;
  13966. this._amplitude = 9.0;
  13967. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13968. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13969. this.updateShaderUniforms();
  13970. this.refreshRate = 0;
  13971. }
  13972. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13973. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13974. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13975. this.setFloat("amplitude", this._amplitude);
  13976. this.setColor3("marbleColor", this._marbleColor);
  13977. this.setColor3("jointColor", this._jointColor);
  13978. };
  13979. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13980. get: function () {
  13981. return this._numberOfTilesHeight;
  13982. },
  13983. set: function (value) {
  13984. this._numberOfTilesHeight = value;
  13985. this.updateShaderUniforms();
  13986. },
  13987. enumerable: true,
  13988. configurable: true
  13989. });
  13990. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13991. get: function () {
  13992. return this._numberOfTilesWidth;
  13993. },
  13994. set: function (value) {
  13995. this._numberOfTilesWidth = value;
  13996. this.updateShaderUniforms();
  13997. },
  13998. enumerable: true,
  13999. configurable: true
  14000. });
  14001. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  14002. get: function () {
  14003. return this._jointColor;
  14004. },
  14005. set: function (value) {
  14006. this._jointColor = value;
  14007. this.updateShaderUniforms();
  14008. },
  14009. enumerable: true,
  14010. configurable: true
  14011. });
  14012. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  14013. get: function () {
  14014. return this._marbleColor;
  14015. },
  14016. set: function (value) {
  14017. this._marbleColor = value;
  14018. this.updateShaderUniforms();
  14019. },
  14020. enumerable: true,
  14021. configurable: true
  14022. });
  14023. return MarbleProceduralTexture;
  14024. })(BABYLON.ProceduralTexture);
  14025. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14026. })(BABYLON || (BABYLON = {}));
  14027. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14028. var BABYLON;
  14029. (function (BABYLON) {
  14030. var CustomProceduralTexture = (function (_super) {
  14031. __extends(CustomProceduralTexture, _super);
  14032. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14033. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14034. this._animate = true;
  14035. this._time = 0;
  14036. this._texturePath = texturePath;
  14037. //Try to load json
  14038. this.loadJson(texturePath);
  14039. this.refreshRate = 1;
  14040. }
  14041. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14042. var _this = this;
  14043. var that = this;
  14044. function noConfigFile() {
  14045. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14046. try {
  14047. that.setFragment(that._texturePath);
  14048. }
  14049. catch (ex) {
  14050. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14051. }
  14052. }
  14053. var configFileUrl = jsonUrl + "/config.json";
  14054. var xhr = new XMLHttpRequest();
  14055. xhr.open("GET", configFileUrl, true);
  14056. xhr.addEventListener("load", function () {
  14057. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14058. try {
  14059. _this._config = JSON.parse(xhr.response);
  14060. _this.updateShaderUniforms();
  14061. _this.updateTextures();
  14062. _this.setFragment(_this._texturePath + "/custom");
  14063. _this._animate = _this._config.animate;
  14064. _this.refreshRate = _this._config.refreshrate;
  14065. }
  14066. catch (ex) {
  14067. noConfigFile();
  14068. }
  14069. }
  14070. else {
  14071. noConfigFile();
  14072. }
  14073. }, false);
  14074. xhr.addEventListener("error", function () {
  14075. noConfigFile();
  14076. }, false);
  14077. try {
  14078. xhr.send();
  14079. }
  14080. catch (ex) {
  14081. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14082. }
  14083. };
  14084. CustomProceduralTexture.prototype.isReady = function () {
  14085. if (!_super.prototype.isReady.call(this)) {
  14086. return false;
  14087. }
  14088. for (var name in this._textures) {
  14089. var texture = this._textures[name];
  14090. if (!texture.isReady()) {
  14091. return false;
  14092. }
  14093. }
  14094. return true;
  14095. };
  14096. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14097. if (this._animate) {
  14098. this._time += this.getScene().getAnimationRatio() * 0.03;
  14099. this.updateShaderUniforms();
  14100. }
  14101. _super.prototype.render.call(this, useCameraPostProcess);
  14102. };
  14103. CustomProceduralTexture.prototype.updateTextures = function () {
  14104. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14105. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14106. }
  14107. };
  14108. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14109. if (this._config) {
  14110. for (var j = 0; j < this._config.uniforms.length; j++) {
  14111. var uniform = this._config.uniforms[j];
  14112. switch (uniform.type) {
  14113. case "float":
  14114. this.setFloat(uniform.name, uniform.value);
  14115. break;
  14116. case "color3":
  14117. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14118. break;
  14119. case "color4":
  14120. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14121. break;
  14122. case "vector2":
  14123. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14124. break;
  14125. case "vector3":
  14126. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14127. break;
  14128. }
  14129. }
  14130. }
  14131. this.setFloat("time", this._time);
  14132. };
  14133. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14134. get: function () {
  14135. return this._animate;
  14136. },
  14137. set: function (value) {
  14138. this._animate = value;
  14139. },
  14140. enumerable: true,
  14141. configurable: true
  14142. });
  14143. return CustomProceduralTexture;
  14144. })(BABYLON.ProceduralTexture);
  14145. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14146. })(BABYLON || (BABYLON = {}));
  14147. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14148. var BABYLON;
  14149. (function (BABYLON) {
  14150. var MirrorTexture = (function (_super) {
  14151. __extends(MirrorTexture, _super);
  14152. function MirrorTexture(name, size, scene, generateMipMaps) {
  14153. var _this = this;
  14154. _super.call(this, name, size, scene, generateMipMaps, true);
  14155. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14156. this._transformMatrix = BABYLON.Matrix.Zero();
  14157. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14158. this.onBeforeRender = function () {
  14159. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14160. _this._savedViewMatrix = scene.getViewMatrix();
  14161. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14162. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14163. scene.clipPlane = _this.mirrorPlane;
  14164. scene.getEngine().cullBackFaces = false;
  14165. };
  14166. this.onAfterRender = function () {
  14167. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14168. scene.getEngine().cullBackFaces = true;
  14169. delete scene.clipPlane;
  14170. };
  14171. }
  14172. MirrorTexture.prototype.clone = function () {
  14173. var textureSize = this.getSize();
  14174. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14175. // Base texture
  14176. newTexture.hasAlpha = this.hasAlpha;
  14177. newTexture.level = this.level;
  14178. // Mirror Texture
  14179. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14180. newTexture.renderList = this.renderList.slice(0);
  14181. return newTexture;
  14182. };
  14183. return MirrorTexture;
  14184. })(BABYLON.RenderTargetTexture);
  14185. BABYLON.MirrorTexture = MirrorTexture;
  14186. })(BABYLON || (BABYLON = {}));
  14187. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14188. var BABYLON;
  14189. (function (BABYLON) {
  14190. var DynamicTexture = (function (_super) {
  14191. __extends(DynamicTexture, _super);
  14192. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14193. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14194. _super.call(this, null, scene, !generateMipMaps);
  14195. this.name = name;
  14196. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14197. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14198. this._generateMipMaps = generateMipMaps;
  14199. if (options.getContext) {
  14200. this._canvas = options;
  14201. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14202. }
  14203. else {
  14204. this._canvas = document.createElement("canvas");
  14205. if (options.width) {
  14206. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14207. }
  14208. else {
  14209. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14210. }
  14211. }
  14212. var textureSize = this.getSize();
  14213. this._canvas.width = textureSize.width;
  14214. this._canvas.height = textureSize.height;
  14215. this._context = this._canvas.getContext("2d");
  14216. }
  14217. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14218. get: function () {
  14219. return true;
  14220. },
  14221. enumerable: true,
  14222. configurable: true
  14223. });
  14224. DynamicTexture.prototype.scale = function (ratio) {
  14225. var textureSize = this.getSize();
  14226. textureSize.width *= ratio;
  14227. textureSize.height *= ratio;
  14228. this._canvas.width = textureSize.width;
  14229. this._canvas.height = textureSize.height;
  14230. this.releaseInternalTexture();
  14231. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14232. };
  14233. DynamicTexture.prototype.getContext = function () {
  14234. return this._context;
  14235. };
  14236. DynamicTexture.prototype.clear = function () {
  14237. var size = this.getSize();
  14238. this._context.fillRect(0, 0, size.width, size.height);
  14239. };
  14240. DynamicTexture.prototype.update = function (invertY) {
  14241. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14242. };
  14243. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14244. if (update === void 0) { update = true; }
  14245. var size = this.getSize();
  14246. if (clearColor) {
  14247. this._context.fillStyle = clearColor;
  14248. this._context.fillRect(0, 0, size.width, size.height);
  14249. }
  14250. this._context.font = font;
  14251. if (x === null) {
  14252. var textSize = this._context.measureText(text);
  14253. x = (size.width - textSize.width) / 2;
  14254. }
  14255. this._context.fillStyle = color;
  14256. this._context.fillText(text, x, y);
  14257. if (update) {
  14258. this.update(invertY);
  14259. }
  14260. };
  14261. DynamicTexture.prototype.clone = function () {
  14262. var textureSize = this.getSize();
  14263. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14264. // Base texture
  14265. newTexture.hasAlpha = this.hasAlpha;
  14266. newTexture.level = this.level;
  14267. // Dynamic Texture
  14268. newTexture.wrapU = this.wrapU;
  14269. newTexture.wrapV = this.wrapV;
  14270. return newTexture;
  14271. };
  14272. return DynamicTexture;
  14273. })(BABYLON.Texture);
  14274. BABYLON.DynamicTexture = DynamicTexture;
  14275. })(BABYLON || (BABYLON = {}));
  14276. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14277. var BABYLON;
  14278. (function (BABYLON) {
  14279. var VideoTexture = (function (_super) {
  14280. __extends(VideoTexture, _super);
  14281. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14282. var _this = this;
  14283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14284. _super.call(this, null, scene, !generateMipMaps, invertY);
  14285. this._autoLaunch = true;
  14286. this.name = name;
  14287. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14288. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14289. var requiredWidth = size.width || size;
  14290. var requiredHeight = size.height || size;
  14291. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14292. var textureSize = this.getSize();
  14293. this.video = document.createElement("video");
  14294. this.video.width = textureSize.width;
  14295. this.video.height = textureSize.height;
  14296. this.video.autoplay = false;
  14297. this.video.loop = true;
  14298. this.video.addEventListener("canplaythrough", function () {
  14299. if (_this._texture) {
  14300. _this._texture.isReady = true;
  14301. }
  14302. });
  14303. urls.forEach(function (url) {
  14304. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14305. var source = document.createElement("source");
  14306. source.src = url;
  14307. _this.video.appendChild(source);
  14308. });
  14309. this._lastUpdate = BABYLON.Tools.Now;
  14310. }
  14311. VideoTexture.prototype.update = function () {
  14312. if (this._autoLaunch) {
  14313. this._autoLaunch = false;
  14314. this.video.play();
  14315. }
  14316. var now = BABYLON.Tools.Now;
  14317. if (now - this._lastUpdate < 15) {
  14318. return false;
  14319. }
  14320. this._lastUpdate = now;
  14321. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14322. return true;
  14323. };
  14324. return VideoTexture;
  14325. })(BABYLON.Texture);
  14326. BABYLON.VideoTexture = VideoTexture;
  14327. })(BABYLON || (BABYLON = {}));
  14328. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14329. (function (BABYLON) {
  14330. var EffectFallbacks = (function () {
  14331. function EffectFallbacks() {
  14332. this._defines = {};
  14333. this._currentRank = 32;
  14334. this._maxRank = -1;
  14335. }
  14336. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14337. if (!this._defines[rank]) {
  14338. if (rank < this._currentRank) {
  14339. this._currentRank = rank;
  14340. }
  14341. if (rank > this._maxRank) {
  14342. this._maxRank = rank;
  14343. }
  14344. this._defines[rank] = new Array();
  14345. }
  14346. this._defines[rank].push(define);
  14347. };
  14348. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14349. get: function () {
  14350. return this._currentRank <= this._maxRank;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14356. var currentFallbacks = this._defines[this._currentRank];
  14357. for (var index = 0; index < currentFallbacks.length; index++) {
  14358. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14359. }
  14360. this._currentRank++;
  14361. return currentDefines;
  14362. };
  14363. return EffectFallbacks;
  14364. })();
  14365. BABYLON.EffectFallbacks = EffectFallbacks;
  14366. var Effect = (function () {
  14367. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14368. var _this = this;
  14369. this._isReady = false;
  14370. this._compilationError = "";
  14371. this._valueCache = [];
  14372. this._engine = engine;
  14373. this.name = baseName;
  14374. this.defines = defines;
  14375. this._uniformsNames = uniformsNames.concat(samplers);
  14376. this._samplers = samplers;
  14377. this._attributesNames = attributesNames;
  14378. this.onError = onError;
  14379. this.onCompiled = onCompiled;
  14380. var vertexSource;
  14381. var fragmentSource;
  14382. if (baseName.vertexElement) {
  14383. vertexSource = document.getElementById(baseName.vertexElement);
  14384. if (!vertexSource) {
  14385. vertexSource = baseName.vertexElement;
  14386. }
  14387. }
  14388. else {
  14389. vertexSource = baseName.vertex || baseName;
  14390. }
  14391. if (baseName.fragmentElement) {
  14392. fragmentSource = document.getElementById(baseName.fragmentElement);
  14393. if (!fragmentSource) {
  14394. fragmentSource = baseName.fragmentElement;
  14395. }
  14396. }
  14397. else {
  14398. fragmentSource = baseName.fragment || baseName;
  14399. }
  14400. this._loadVertexShader(vertexSource, function (vertexCode) {
  14401. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14402. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14403. });
  14404. });
  14405. }
  14406. // Properties
  14407. Effect.prototype.isReady = function () {
  14408. return this._isReady;
  14409. };
  14410. Effect.prototype.getProgram = function () {
  14411. return this._program;
  14412. };
  14413. Effect.prototype.getAttributesNames = function () {
  14414. return this._attributesNames;
  14415. };
  14416. Effect.prototype.getAttributeLocation = function (index) {
  14417. return this._attributes[index];
  14418. };
  14419. Effect.prototype.getAttributeLocationByName = function (name) {
  14420. var index = this._attributesNames.indexOf(name);
  14421. return this._attributes[index];
  14422. };
  14423. Effect.prototype.getAttributesCount = function () {
  14424. return this._attributes.length;
  14425. };
  14426. Effect.prototype.getUniformIndex = function (uniformName) {
  14427. return this._uniformsNames.indexOf(uniformName);
  14428. };
  14429. Effect.prototype.getUniform = function (uniformName) {
  14430. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14431. };
  14432. Effect.prototype.getSamplers = function () {
  14433. return this._samplers;
  14434. };
  14435. Effect.prototype.getCompilationError = function () {
  14436. return this._compilationError;
  14437. };
  14438. // Methods
  14439. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14440. // DOM element ?
  14441. if (vertex instanceof HTMLElement) {
  14442. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14443. callback(vertexCode);
  14444. return;
  14445. }
  14446. // Is in local store ?
  14447. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14448. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14449. return;
  14450. }
  14451. var vertexShaderUrl;
  14452. if (vertex[0] === ".") {
  14453. vertexShaderUrl = vertex;
  14454. }
  14455. else {
  14456. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14457. }
  14458. // Vertex shader
  14459. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14460. };
  14461. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14462. // DOM element ?
  14463. if (fragment instanceof HTMLElement) {
  14464. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14465. callback(fragmentCode);
  14466. return;
  14467. }
  14468. // Is in local store ?
  14469. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14470. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14471. return;
  14472. }
  14473. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14474. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14475. return;
  14476. }
  14477. var fragmentShaderUrl;
  14478. if (fragment[0] === ".") {
  14479. fragmentShaderUrl = fragment;
  14480. }
  14481. else {
  14482. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14483. }
  14484. // Fragment shader
  14485. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14486. };
  14487. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14488. try {
  14489. var engine = this._engine;
  14490. if (!engine.getCaps().highPrecisionShaderSupported) {
  14491. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14492. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14493. }
  14494. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14496. this._attributes = engine.getAttributes(this._program, attributesNames);
  14497. for (var index = 0; index < this._samplers.length; index++) {
  14498. var sampler = this.getUniform(this._samplers[index]);
  14499. if (sampler == null) {
  14500. this._samplers.splice(index, 1);
  14501. index--;
  14502. }
  14503. }
  14504. engine.bindSamplers(this);
  14505. this._isReady = true;
  14506. if (this.onCompiled) {
  14507. this.onCompiled(this);
  14508. }
  14509. }
  14510. catch (e) {
  14511. // Is it a problem with precision?
  14512. if (e.message.indexOf("highp") !== -1) {
  14513. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14514. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14515. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14516. return;
  14517. }
  14518. // Let's go through fallbacks then
  14519. if (fallbacks && fallbacks.isMoreFallbacks) {
  14520. defines = fallbacks.reduce(defines);
  14521. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14522. }
  14523. else {
  14524. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14525. BABYLON.Tools.Error("Defines: " + defines);
  14526. BABYLON.Tools.Error("Error: " + e.message);
  14527. this._compilationError = e.message;
  14528. if (this.onError) {
  14529. this.onError(this, this._compilationError);
  14530. }
  14531. }
  14532. }
  14533. };
  14534. Effect.prototype._bindTexture = function (channel, texture) {
  14535. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14536. };
  14537. Effect.prototype.setTexture = function (channel, texture) {
  14538. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14539. };
  14540. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14541. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14542. };
  14543. //public _cacheMatrix(uniformName, matrix) {
  14544. // if (!this._valueCache[uniformName]) {
  14545. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14546. // }
  14547. // for (var index = 0; index < 16; index++) {
  14548. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14549. // }
  14550. //};
  14551. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14552. if (!this._valueCache[uniformName]) {
  14553. this._valueCache[uniformName] = [x, y];
  14554. return;
  14555. }
  14556. this._valueCache[uniformName][0] = x;
  14557. this._valueCache[uniformName][1] = y;
  14558. };
  14559. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14560. if (!this._valueCache[uniformName]) {
  14561. this._valueCache[uniformName] = [x, y, z];
  14562. return;
  14563. }
  14564. this._valueCache[uniformName][0] = x;
  14565. this._valueCache[uniformName][1] = y;
  14566. this._valueCache[uniformName][2] = z;
  14567. };
  14568. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14569. if (!this._valueCache[uniformName]) {
  14570. this._valueCache[uniformName] = [x, y, z, w];
  14571. return;
  14572. }
  14573. this._valueCache[uniformName][0] = x;
  14574. this._valueCache[uniformName][1] = y;
  14575. this._valueCache[uniformName][2] = z;
  14576. this._valueCache[uniformName][3] = w;
  14577. };
  14578. Effect.prototype.setArray = function (uniformName, array) {
  14579. this._engine.setArray(this.getUniform(uniformName), array);
  14580. return this;
  14581. };
  14582. Effect.prototype.setArray2 = function (uniformName, array) {
  14583. this._engine.setArray2(this.getUniform(uniformName), array);
  14584. return this;
  14585. };
  14586. Effect.prototype.setArray3 = function (uniformName, array) {
  14587. this._engine.setArray3(this.getUniform(uniformName), array);
  14588. return this;
  14589. };
  14590. Effect.prototype.setArray4 = function (uniformName, array) {
  14591. this._engine.setArray4(this.getUniform(uniformName), array);
  14592. return this;
  14593. };
  14594. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14595. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14596. return this;
  14597. };
  14598. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14599. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14600. // return;
  14601. //this._cacheMatrix(uniformName, matrix);
  14602. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14603. return this;
  14604. };
  14605. Effect.prototype.setFloat = function (uniformName, value) {
  14606. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14607. return this;
  14608. this._valueCache[uniformName] = value;
  14609. this._engine.setFloat(this.getUniform(uniformName), value);
  14610. return this;
  14611. };
  14612. Effect.prototype.setBool = function (uniformName, bool) {
  14613. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14614. return this;
  14615. this._valueCache[uniformName] = bool;
  14616. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14617. return this;
  14618. };
  14619. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14620. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14621. return this;
  14622. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14623. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14624. return this;
  14625. };
  14626. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14627. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14628. return this;
  14629. this._cacheFloat2(uniformName, x, y);
  14630. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14631. return this;
  14632. };
  14633. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14634. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14635. return this;
  14636. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14637. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14638. return this;
  14639. };
  14640. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14641. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14642. return this;
  14643. this._cacheFloat3(uniformName, x, y, z);
  14644. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14645. return this;
  14646. };
  14647. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14648. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14649. return this;
  14650. this._cacheFloat4(uniformName, x, y, z, w);
  14651. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14652. return this;
  14653. };
  14654. Effect.prototype.setColor3 = function (uniformName, color3) {
  14655. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14656. return this;
  14657. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14658. this._engine.setColor3(this.getUniform(uniformName), color3);
  14659. return this;
  14660. };
  14661. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14662. 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)
  14663. return this;
  14664. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14665. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14666. return this;
  14667. };
  14668. // Statics
  14669. 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}",
  14670. 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}",
  14671. 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}",
  14672. 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}",
  14673. 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}",
  14674. 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}",
  14675. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14676. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14677. 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}",
  14678. 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}",
  14679. 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}",
  14680. 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}",
  14681. 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}",
  14682. 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}",
  14683. 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}",
  14684. 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}",
  14685. 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}",
  14686. 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}",
  14687. 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}",
  14688. 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}",
  14689. 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}",
  14690. 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}",
  14691. 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}",
  14692. 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}",
  14693. 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}",
  14694. 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}",
  14695. 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}",
  14696. 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}",
  14697. 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}",
  14698. 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}",
  14699. 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}",
  14700. 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}",
  14701. 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}",
  14702. 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}",
  14703. 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}",
  14704. 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}",
  14705. 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}",
  14706. 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}",
  14707. 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}",
  14708. 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}",
  14709. 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}",
  14710. 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}",
  14711. 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}",
  14712. 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}",
  14713. 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}",
  14714. 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}",
  14715. 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}",
  14716. 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}",
  14717. };
  14718. return Effect;
  14719. })();
  14720. BABYLON.Effect = Effect;
  14721. })(BABYLON || (BABYLON = {}));
  14722. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14723. (function (BABYLON) {
  14724. var Material = (function () {
  14725. function Material(name, scene, doNotAdd) {
  14726. this.name = name;
  14727. this.checkReadyOnEveryCall = true;
  14728. this.checkReadyOnlyOnce = false;
  14729. this.state = "";
  14730. this.alpha = 1.0;
  14731. this.backFaceCulling = true;
  14732. this._wasPreviouslyReady = false;
  14733. this._fillMode = Material.TriangleFillMode;
  14734. this.pointSize = 1.0;
  14735. this.zOffset = 0;
  14736. this.id = name;
  14737. this._scene = scene;
  14738. if (!doNotAdd) {
  14739. scene.materials.push(this);
  14740. }
  14741. }
  14742. Object.defineProperty(Material, "TriangleFillMode", {
  14743. get: function () {
  14744. return Material._TriangleFillMode;
  14745. },
  14746. enumerable: true,
  14747. configurable: true
  14748. });
  14749. Object.defineProperty(Material, "WireFrameFillMode", {
  14750. get: function () {
  14751. return Material._WireFrameFillMode;
  14752. },
  14753. enumerable: true,
  14754. configurable: true
  14755. });
  14756. Object.defineProperty(Material, "PointFillMode", {
  14757. get: function () {
  14758. return Material._PointFillMode;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(Material.prototype, "wireframe", {
  14764. get: function () {
  14765. return this._fillMode === Material.WireFrameFillMode;
  14766. },
  14767. set: function (value) {
  14768. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14769. },
  14770. enumerable: true,
  14771. configurable: true
  14772. });
  14773. Object.defineProperty(Material.prototype, "pointsCloud", {
  14774. get: function () {
  14775. return this._fillMode === Material.PointFillMode;
  14776. },
  14777. set: function (value) {
  14778. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14779. },
  14780. enumerable: true,
  14781. configurable: true
  14782. });
  14783. Object.defineProperty(Material.prototype, "fillMode", {
  14784. get: function () {
  14785. return this._fillMode;
  14786. },
  14787. set: function (value) {
  14788. this._fillMode = value;
  14789. },
  14790. enumerable: true,
  14791. configurable: true
  14792. });
  14793. Material.prototype.isReady = function (mesh, useInstances) {
  14794. return true;
  14795. };
  14796. Material.prototype.getEffect = function () {
  14797. return this._effect;
  14798. };
  14799. Material.prototype.getScene = function () {
  14800. return this._scene;
  14801. };
  14802. Material.prototype.needAlphaBlending = function () {
  14803. return (this.alpha < 1.0);
  14804. };
  14805. Material.prototype.needAlphaTesting = function () {
  14806. return false;
  14807. };
  14808. Material.prototype.getAlphaTestTexture = function () {
  14809. return null;
  14810. };
  14811. Material.prototype.trackCreation = function (onCompiled, onError) {
  14812. };
  14813. Material.prototype._preBind = function () {
  14814. var engine = this._scene.getEngine();
  14815. engine.enableEffect(this._effect);
  14816. engine.setState(this.backFaceCulling, this.zOffset);
  14817. };
  14818. Material.prototype.bind = function (world, mesh) {
  14819. this._scene._cachedMaterial = this;
  14820. if (this.onBind) {
  14821. this.onBind(this, mesh);
  14822. }
  14823. };
  14824. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14825. };
  14826. Material.prototype.unbind = function () {
  14827. };
  14828. Material.prototype.dispose = function (forceDisposeEffect) {
  14829. // Remove from scene
  14830. var index = this._scene.materials.indexOf(this);
  14831. this._scene.materials.splice(index, 1);
  14832. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14833. if (forceDisposeEffect && this._effect) {
  14834. this._scene.getEngine()._releaseEffect(this._effect);
  14835. this._effect = null;
  14836. }
  14837. // Callback
  14838. if (this.onDispose) {
  14839. this.onDispose();
  14840. }
  14841. };
  14842. Material._TriangleFillMode = 0;
  14843. Material._WireFrameFillMode = 1;
  14844. Material._PointFillMode = 2;
  14845. return Material;
  14846. })();
  14847. BABYLON.Material = Material;
  14848. })(BABYLON || (BABYLON = {}));
  14849. //# sourceMappingURL=babylon.material.js.map
  14850. var BABYLON;
  14851. (function (BABYLON) {
  14852. var maxSimultaneousLights = 4;
  14853. var FresnelParameters = (function () {
  14854. function FresnelParameters() {
  14855. this.isEnabled = true;
  14856. this.leftColor = BABYLON.Color3.White();
  14857. this.rightColor = BABYLON.Color3.Black();
  14858. this.bias = 0;
  14859. this.power = 1;
  14860. }
  14861. return FresnelParameters;
  14862. })();
  14863. BABYLON.FresnelParameters = FresnelParameters;
  14864. var StandardMaterial = (function (_super) {
  14865. __extends(StandardMaterial, _super);
  14866. function StandardMaterial(name, scene) {
  14867. var _this = this;
  14868. _super.call(this, name, scene);
  14869. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14870. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14871. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14872. this.specularPower = 64;
  14873. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14874. this.useAlphaFromDiffuseTexture = false;
  14875. this.useSpecularOverAlpha = true;
  14876. this.fogEnabled = true;
  14877. this._cachedDefines = null;
  14878. this._renderTargets = new BABYLON.SmartArray(16);
  14879. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14880. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14881. this._scaledDiffuse = new BABYLON.Color3();
  14882. this._scaledSpecular = new BABYLON.Color3();
  14883. this.getRenderTargetTextures = function () {
  14884. _this._renderTargets.reset();
  14885. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14886. _this._renderTargets.push(_this.reflectionTexture);
  14887. }
  14888. return _this._renderTargets;
  14889. };
  14890. }
  14891. StandardMaterial.prototype.needAlphaBlending = function () {
  14892. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14893. };
  14894. StandardMaterial.prototype.needAlphaTesting = function () {
  14895. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14896. };
  14897. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14898. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14899. };
  14900. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14901. return this.diffuseTexture;
  14902. };
  14903. // Methods
  14904. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14905. if (this.checkReadyOnlyOnce) {
  14906. if (this._wasPreviouslyReady) {
  14907. }
  14908. }
  14909. var scene = this.getScene();
  14910. if (!this.checkReadyOnEveryCall) {
  14911. if (this._renderId === scene.getRenderId()) {
  14912. }
  14913. }
  14914. var engine = scene.getEngine();
  14915. var defines = [];
  14916. var fallbacks = new BABYLON.EffectFallbacks();
  14917. var needNormals = false;
  14918. var needUVs = false;
  14919. // Textures
  14920. if (scene.texturesEnabled) {
  14921. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14922. if (!this.diffuseTexture.isReady()) {
  14923. return false;
  14924. }
  14925. else {
  14926. needUVs = true;
  14927. defines.push("#define DIFFUSE");
  14928. }
  14929. }
  14930. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14931. if (!this.ambientTexture.isReady()) {
  14932. return false;
  14933. }
  14934. else {
  14935. needUVs = true;
  14936. defines.push("#define AMBIENT");
  14937. }
  14938. }
  14939. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14940. if (!this.opacityTexture.isReady()) {
  14941. return false;
  14942. }
  14943. else {
  14944. needUVs = true;
  14945. defines.push("#define OPACITY");
  14946. if (this.opacityTexture.getAlphaFromRGB) {
  14947. defines.push("#define OPACITYRGB");
  14948. }
  14949. }
  14950. }
  14951. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14952. if (!this.reflectionTexture.isReady()) {
  14953. return false;
  14954. }
  14955. else {
  14956. needNormals = true;
  14957. needUVs = true;
  14958. defines.push("#define REFLECTION");
  14959. fallbacks.addFallback(0, "REFLECTION");
  14960. }
  14961. }
  14962. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14963. if (!this.emissiveTexture.isReady()) {
  14964. return false;
  14965. }
  14966. else {
  14967. needUVs = true;
  14968. defines.push("#define EMISSIVE");
  14969. }
  14970. }
  14971. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14972. if (!this.specularTexture.isReady()) {
  14973. return false;
  14974. }
  14975. else {
  14976. needUVs = true;
  14977. defines.push("#define SPECULAR");
  14978. fallbacks.addFallback(0, "SPECULAR");
  14979. }
  14980. }
  14981. }
  14982. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14983. if (!this.bumpTexture.isReady()) {
  14984. return false;
  14985. }
  14986. else {
  14987. needUVs = true;
  14988. defines.push("#define BUMP");
  14989. fallbacks.addFallback(0, "BUMP");
  14990. }
  14991. }
  14992. // Effect
  14993. if (this.useSpecularOverAlpha) {
  14994. defines.push("#define SPECULAROVERALPHA");
  14995. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14996. }
  14997. if (scene.clipPlane) {
  14998. defines.push("#define CLIPPLANE");
  14999. }
  15000. if (engine.getAlphaTesting()) {
  15001. defines.push("#define ALPHATEST");
  15002. }
  15003. if (this._shouldUseAlphaFromDiffuseTexture()) {
  15004. defines.push("#define ALPHAFROMDIFFUSE");
  15005. }
  15006. // Point size
  15007. if (this.pointsCloud || scene.forcePointsCloud) {
  15008. defines.push("#define POINTSIZE");
  15009. }
  15010. // Fog
  15011. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15012. defines.push("#define FOG");
  15013. fallbacks.addFallback(1, "FOG");
  15014. }
  15015. var shadowsActivated = false;
  15016. var lightIndex = 0;
  15017. if (scene.lightsEnabled) {
  15018. for (var index = 0; index < scene.lights.length; index++) {
  15019. var light = scene.lights[index];
  15020. if (!light.isEnabled()) {
  15021. continue;
  15022. }
  15023. // Excluded check
  15024. if (light._excludedMeshesIds.length > 0) {
  15025. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15026. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15027. if (excludedMesh) {
  15028. light.excludedMeshes.push(excludedMesh);
  15029. }
  15030. }
  15031. light._excludedMeshesIds = [];
  15032. }
  15033. // Included check
  15034. if (light._includedOnlyMeshesIds.length > 0) {
  15035. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15036. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15037. if (includedOnlyMesh) {
  15038. light.includedOnlyMeshes.push(includedOnlyMesh);
  15039. }
  15040. }
  15041. light._includedOnlyMeshesIds = [];
  15042. }
  15043. if (!light.canAffectMesh(mesh)) {
  15044. continue;
  15045. }
  15046. needNormals = true;
  15047. defines.push("#define LIGHT" + lightIndex);
  15048. if (lightIndex > 0) {
  15049. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15050. }
  15051. var type;
  15052. if (light instanceof BABYLON.SpotLight) {
  15053. type = "#define SPOTLIGHT" + lightIndex;
  15054. }
  15055. else if (light instanceof BABYLON.HemisphericLight) {
  15056. type = "#define HEMILIGHT" + lightIndex;
  15057. }
  15058. else {
  15059. type = "#define POINTDIRLIGHT" + lightIndex;
  15060. }
  15061. defines.push(type);
  15062. if (lightIndex > 0) {
  15063. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15064. }
  15065. // Shadows
  15066. if (scene.shadowsEnabled) {
  15067. var shadowGenerator = light.getShadowGenerator();
  15068. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15069. defines.push("#define SHADOW" + lightIndex);
  15070. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15071. if (!shadowsActivated) {
  15072. defines.push("#define SHADOWS");
  15073. shadowsActivated = true;
  15074. }
  15075. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15076. defines.push("#define SHADOWVSM" + lightIndex);
  15077. if (lightIndex > 0) {
  15078. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15079. }
  15080. }
  15081. if (shadowGenerator.usePoissonSampling) {
  15082. defines.push("#define SHADOWPCF" + lightIndex);
  15083. if (lightIndex > 0) {
  15084. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15085. }
  15086. }
  15087. }
  15088. }
  15089. lightIndex++;
  15090. if (lightIndex === maxSimultaneousLights)
  15091. break;
  15092. }
  15093. }
  15094. if (StandardMaterial.FresnelEnabled) {
  15095. // Fresnel
  15096. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15097. var fresnelRank = 1;
  15098. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15099. defines.push("#define DIFFUSEFRESNEL");
  15100. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15101. fresnelRank++;
  15102. }
  15103. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15104. defines.push("#define OPACITYFRESNEL");
  15105. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15106. fresnelRank++;
  15107. }
  15108. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15109. defines.push("#define REFLECTIONFRESNEL");
  15110. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15111. fresnelRank++;
  15112. }
  15113. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15114. defines.push("#define EMISSIVEFRESNEL");
  15115. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15116. fresnelRank++;
  15117. }
  15118. needNormals = true;
  15119. defines.push("#define FRESNEL");
  15120. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15121. }
  15122. }
  15123. // Attribs
  15124. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15125. if (mesh) {
  15126. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15127. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15128. defines.push("#define NORMAL");
  15129. }
  15130. if (needUVs) {
  15131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15132. attribs.push(BABYLON.VertexBuffer.UVKind);
  15133. defines.push("#define UV1");
  15134. }
  15135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15137. defines.push("#define UV2");
  15138. }
  15139. }
  15140. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15141. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15142. defines.push("#define VERTEXCOLOR");
  15143. if (mesh.hasVertexAlpha) {
  15144. defines.push("#define VERTEXALPHA");
  15145. }
  15146. }
  15147. if (mesh.useBones) {
  15148. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15149. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15150. defines.push("#define BONES");
  15151. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15152. defines.push("#define BONES4");
  15153. fallbacks.addFallback(0, "BONES4");
  15154. }
  15155. // Instances
  15156. if (useInstances) {
  15157. defines.push("#define INSTANCES");
  15158. attribs.push("world0");
  15159. attribs.push("world1");
  15160. attribs.push("world2");
  15161. attribs.push("world3");
  15162. }
  15163. }
  15164. // Get correct effect
  15165. var join = defines.join("\n");
  15166. if (this._cachedDefines !== join) {
  15167. this._cachedDefines = join;
  15168. scene.resetCachedMaterial();
  15169. // Legacy browser patch
  15170. var shaderName = "default";
  15171. if (!scene.getEngine().getCaps().standardDerivatives) {
  15172. shaderName = "legacydefault";
  15173. }
  15174. 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);
  15175. }
  15176. if (!this._effect.isReady()) {
  15177. return false;
  15178. }
  15179. this._renderId = scene.getRenderId();
  15180. this._wasPreviouslyReady = true;
  15181. return true;
  15182. };
  15183. StandardMaterial.prototype.unbind = function () {
  15184. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15185. this._effect.setTexture("reflection2DSampler", null);
  15186. }
  15187. };
  15188. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15189. this._effect.setMatrix("world", world);
  15190. };
  15191. StandardMaterial.prototype.bind = function (world, mesh) {
  15192. var scene = this.getScene();
  15193. // Matrices
  15194. this.bindOnlyWorldMatrix(world);
  15195. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15196. // Bones
  15197. if (mesh && mesh.useBones) {
  15198. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15199. }
  15200. if (scene.getCachedMaterial() !== this) {
  15201. if (StandardMaterial.FresnelEnabled) {
  15202. // Fresnel
  15203. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15204. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15205. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15206. }
  15207. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15208. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15209. }
  15210. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15211. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15212. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15213. }
  15214. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15215. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15216. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15217. }
  15218. }
  15219. // Textures
  15220. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15221. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15222. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15223. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15224. }
  15225. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15226. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15227. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15228. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15229. }
  15230. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15231. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15232. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15233. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15234. }
  15235. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15236. if (this.reflectionTexture.isCube) {
  15237. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15238. }
  15239. else {
  15240. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15241. }
  15242. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15243. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15244. }
  15245. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15246. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15247. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15248. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15249. }
  15250. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15251. this._effect.setTexture("specularSampler", this.specularTexture);
  15252. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15253. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15254. }
  15255. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15256. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15257. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15258. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15259. }
  15260. // Clip plane
  15261. if (scene.clipPlane) {
  15262. var clipPlane = scene.clipPlane;
  15263. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15264. }
  15265. // Point size
  15266. if (this.pointsCloud) {
  15267. this._effect.setFloat("pointSize", this.pointSize);
  15268. }
  15269. // Colors
  15270. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15271. // Scaling down color according to emissive
  15272. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15273. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15274. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15275. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15276. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15277. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15278. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15279. }
  15280. // Scaling down color according to emissive
  15281. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15282. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15283. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15284. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15285. if (scene.lightsEnabled) {
  15286. var lightIndex = 0;
  15287. for (var index = 0; index < scene.lights.length; index++) {
  15288. var light = scene.lights[index];
  15289. if (!light.isEnabled()) {
  15290. continue;
  15291. }
  15292. if (!light.canAffectMesh(mesh)) {
  15293. continue;
  15294. }
  15295. if (light instanceof BABYLON.PointLight) {
  15296. // Point Light
  15297. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15298. }
  15299. else if (light instanceof BABYLON.DirectionalLight) {
  15300. // Directional Light
  15301. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15302. }
  15303. else if (light instanceof BABYLON.SpotLight) {
  15304. // Spot Light
  15305. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15306. }
  15307. else if (light instanceof BABYLON.HemisphericLight) {
  15308. // Hemispheric Light
  15309. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15310. }
  15311. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15312. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15313. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15314. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15315. // Shadows
  15316. if (scene.shadowsEnabled) {
  15317. var shadowGenerator = light.getShadowGenerator();
  15318. if (mesh.receiveShadows && shadowGenerator) {
  15319. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15320. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15321. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15322. }
  15323. }
  15324. lightIndex++;
  15325. if (lightIndex === maxSimultaneousLights)
  15326. break;
  15327. }
  15328. }
  15329. // View
  15330. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15331. this._effect.setMatrix("view", scene.getViewMatrix());
  15332. }
  15333. // Fog
  15334. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15335. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15336. this._effect.setColor3("vFogColor", scene.fogColor);
  15337. }
  15338. _super.prototype.bind.call(this, world, mesh);
  15339. };
  15340. StandardMaterial.prototype.getAnimatables = function () {
  15341. var results = [];
  15342. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15343. results.push(this.diffuseTexture);
  15344. }
  15345. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15346. results.push(this.ambientTexture);
  15347. }
  15348. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15349. results.push(this.opacityTexture);
  15350. }
  15351. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15352. results.push(this.reflectionTexture);
  15353. }
  15354. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15355. results.push(this.emissiveTexture);
  15356. }
  15357. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15358. results.push(this.specularTexture);
  15359. }
  15360. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15361. results.push(this.bumpTexture);
  15362. }
  15363. return results;
  15364. };
  15365. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15366. if (this.diffuseTexture) {
  15367. this.diffuseTexture.dispose();
  15368. }
  15369. if (this.ambientTexture) {
  15370. this.ambientTexture.dispose();
  15371. }
  15372. if (this.opacityTexture) {
  15373. this.opacityTexture.dispose();
  15374. }
  15375. if (this.reflectionTexture) {
  15376. this.reflectionTexture.dispose();
  15377. }
  15378. if (this.emissiveTexture) {
  15379. this.emissiveTexture.dispose();
  15380. }
  15381. if (this.specularTexture) {
  15382. this.specularTexture.dispose();
  15383. }
  15384. if (this.bumpTexture) {
  15385. this.bumpTexture.dispose();
  15386. }
  15387. _super.prototype.dispose.call(this, forceDisposeEffect);
  15388. };
  15389. StandardMaterial.prototype.clone = function (name) {
  15390. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15391. // Base material
  15392. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15393. newStandardMaterial.alpha = this.alpha;
  15394. newStandardMaterial.fillMode = this.fillMode;
  15395. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15396. // Standard material
  15397. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15398. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15399. }
  15400. if (this.ambientTexture && this.ambientTexture.clone) {
  15401. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15402. }
  15403. if (this.opacityTexture && this.opacityTexture.clone) {
  15404. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15405. }
  15406. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15407. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15408. }
  15409. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15410. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15411. }
  15412. if (this.specularTexture && this.specularTexture.clone) {
  15413. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15414. }
  15415. if (this.bumpTexture && this.bumpTexture.clone) {
  15416. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15417. }
  15418. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15419. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15420. newStandardMaterial.specularColor = this.specularColor.clone();
  15421. newStandardMaterial.specularPower = this.specularPower;
  15422. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15423. return newStandardMaterial;
  15424. };
  15425. // Statics
  15426. // Flags used to enable or disable a type of texture for all Standard Materials
  15427. StandardMaterial.DiffuseTextureEnabled = true;
  15428. StandardMaterial.AmbientTextureEnabled = true;
  15429. StandardMaterial.OpacityTextureEnabled = true;
  15430. StandardMaterial.ReflectionTextureEnabled = true;
  15431. StandardMaterial.EmissiveTextureEnabled = true;
  15432. StandardMaterial.SpecularTextureEnabled = true;
  15433. StandardMaterial.BumpTextureEnabled = true;
  15434. StandardMaterial.FresnelEnabled = true;
  15435. return StandardMaterial;
  15436. })(BABYLON.Material);
  15437. BABYLON.StandardMaterial = StandardMaterial;
  15438. })(BABYLON || (BABYLON = {}));
  15439. //# sourceMappingURL=babylon.standardMaterial.js.map
  15440. var BABYLON;
  15441. (function (BABYLON) {
  15442. var MultiMaterial = (function (_super) {
  15443. __extends(MultiMaterial, _super);
  15444. function MultiMaterial(name, scene) {
  15445. _super.call(this, name, scene, true);
  15446. this.subMaterials = new Array();
  15447. scene.multiMaterials.push(this);
  15448. }
  15449. // Properties
  15450. MultiMaterial.prototype.getSubMaterial = function (index) {
  15451. if (index < 0 || index >= this.subMaterials.length) {
  15452. return this.getScene().defaultMaterial;
  15453. }
  15454. return this.subMaterials[index];
  15455. };
  15456. // Methods
  15457. MultiMaterial.prototype.isReady = function (mesh) {
  15458. for (var index = 0; index < this.subMaterials.length; index++) {
  15459. var subMaterial = this.subMaterials[index];
  15460. if (subMaterial) {
  15461. if (!this.subMaterials[index].isReady(mesh)) {
  15462. return false;
  15463. }
  15464. }
  15465. }
  15466. return true;
  15467. };
  15468. return MultiMaterial;
  15469. })(BABYLON.Material);
  15470. BABYLON.MultiMaterial = MultiMaterial;
  15471. })(BABYLON || (BABYLON = {}));
  15472. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15473. (function (BABYLON) {
  15474. var Database = (function () {
  15475. function Database(urlToScene, callbackManifestChecked) {
  15476. // Handling various flavors of prefixed version of IndexedDB
  15477. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15478. this.callbackManifestChecked = callbackManifestChecked;
  15479. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15480. this.db = null;
  15481. this.enableSceneOffline = false;
  15482. this.enableTexturesOffline = false;
  15483. this.manifestVersionFound = 0;
  15484. this.mustUpdateRessources = false;
  15485. this.hasReachedQuota = false;
  15486. this.checkManifestFile();
  15487. }
  15488. Database.prototype.checkManifestFile = function () {
  15489. var _this = this;
  15490. function noManifestFile() {
  15491. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15492. that.enableSceneOffline = false;
  15493. that.enableTexturesOffline = false;
  15494. that.callbackManifestChecked(false);
  15495. }
  15496. var that = this;
  15497. var manifestURL = this.currentSceneUrl + ".manifest";
  15498. var xhr = new XMLHttpRequest();
  15499. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15500. xhr.open("GET", manifestURLTimeStamped, true);
  15501. xhr.addEventListener("load", function () {
  15502. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15503. try {
  15504. var manifestFile = JSON.parse(xhr.response);
  15505. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15506. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15507. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15508. _this.manifestVersionFound = manifestFile.version;
  15509. }
  15510. if (_this.callbackManifestChecked) {
  15511. _this.callbackManifestChecked(true);
  15512. }
  15513. }
  15514. catch (ex) {
  15515. noManifestFile();
  15516. }
  15517. }
  15518. else {
  15519. noManifestFile();
  15520. }
  15521. }, false);
  15522. xhr.addEventListener("error", function (event) {
  15523. noManifestFile();
  15524. }, false);
  15525. try {
  15526. xhr.send();
  15527. }
  15528. catch (ex) {
  15529. BABYLON.Tools.Error("Error on XHR send request.");
  15530. that.callbackManifestChecked(false);
  15531. }
  15532. };
  15533. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15534. var _this = this;
  15535. function handleError() {
  15536. that.isSupported = false;
  15537. if (errorCallback)
  15538. errorCallback();
  15539. }
  15540. var that = this;
  15541. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15542. // Your browser doesn't support IndexedDB
  15543. this.isSupported = false;
  15544. if (errorCallback)
  15545. errorCallback();
  15546. }
  15547. else {
  15548. // If the DB hasn't been opened or created yet
  15549. if (!this.db) {
  15550. this.hasReachedQuota = false;
  15551. this.isSupported = true;
  15552. var request = this.idbFactory.open("babylonjs", 1);
  15553. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15554. request.onerror = function (event) {
  15555. handleError();
  15556. };
  15557. // executes when a version change transaction cannot complete due to other active transactions
  15558. request.onblocked = function (event) {
  15559. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15560. handleError();
  15561. };
  15562. // DB has been opened successfully
  15563. request.onsuccess = function (event) {
  15564. _this.db = request.result;
  15565. successCallback();
  15566. };
  15567. // Initialization of the DB. Creating Scenes & Textures stores
  15568. request.onupgradeneeded = function (event) {
  15569. _this.db = (event.target).result;
  15570. try {
  15571. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15572. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15573. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15574. }
  15575. catch (ex) {
  15576. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15577. handleError();
  15578. }
  15579. };
  15580. }
  15581. else {
  15582. if (successCallback)
  15583. successCallback();
  15584. }
  15585. }
  15586. };
  15587. Database.prototype.loadImageFromDB = function (url, image) {
  15588. var _this = this;
  15589. var completeURL = Database.ReturnFullUrlLocation(url);
  15590. var saveAndLoadImage = function () {
  15591. if (!_this.hasReachedQuota && _this.db !== null) {
  15592. // the texture is not yet in the DB, let's try to save it
  15593. _this._saveImageIntoDBAsync(completeURL, image);
  15594. }
  15595. else {
  15596. image.src = url;
  15597. }
  15598. };
  15599. if (!this.mustUpdateRessources) {
  15600. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15601. }
  15602. else {
  15603. saveAndLoadImage();
  15604. }
  15605. };
  15606. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15607. if (this.isSupported && this.db !== null) {
  15608. var texture;
  15609. var transaction = this.db.transaction(["textures"]);
  15610. transaction.onabort = function (event) {
  15611. image.src = url;
  15612. };
  15613. transaction.oncomplete = function (event) {
  15614. var blobTextureURL;
  15615. if (texture) {
  15616. var URL = window.URL || window.webkitURL;
  15617. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15618. image.onerror = function () {
  15619. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15620. image.src = url;
  15621. };
  15622. image.src = blobTextureURL;
  15623. }
  15624. else {
  15625. notInDBCallback();
  15626. }
  15627. };
  15628. var getRequest = transaction.objectStore("textures").get(url);
  15629. getRequest.onsuccess = function (event) {
  15630. texture = (event.target).result;
  15631. };
  15632. getRequest.onerror = function (event) {
  15633. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15634. image.src = url;
  15635. };
  15636. }
  15637. else {
  15638. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15639. image.src = url;
  15640. }
  15641. };
  15642. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15643. var _this = this;
  15644. if (this.isSupported) {
  15645. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15646. var generateBlobUrl = function () {
  15647. var blobTextureURL;
  15648. if (blob) {
  15649. var URL = window.URL || window.webkitURL;
  15650. try {
  15651. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15652. }
  15653. catch (ex) {
  15654. blobTextureURL = URL.createObjectURL(blob);
  15655. }
  15656. }
  15657. image.src = blobTextureURL;
  15658. };
  15659. if (Database.isUASupportingBlobStorage) {
  15660. var xhr = new XMLHttpRequest(), blob;
  15661. xhr.open("GET", url, true);
  15662. xhr.responseType = "blob";
  15663. xhr.addEventListener("load", function () {
  15664. if (xhr.status === 200) {
  15665. // Blob as response (XHR2)
  15666. blob = xhr.response;
  15667. var transaction = _this.db.transaction(["textures"], "readwrite");
  15668. // the transaction could abort because of a QuotaExceededError error
  15669. transaction.onabort = function (event) {
  15670. try {
  15671. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15672. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15673. this.hasReachedQuota = true;
  15674. }
  15675. }
  15676. catch (ex) {
  15677. }
  15678. generateBlobUrl();
  15679. };
  15680. transaction.oncomplete = function (event) {
  15681. generateBlobUrl();
  15682. };
  15683. var newTexture = { textureUrl: url, data: blob };
  15684. try {
  15685. // Put the blob into the dabase
  15686. var addRequest = transaction.objectStore("textures").put(newTexture);
  15687. addRequest.onsuccess = function (event) {
  15688. };
  15689. addRequest.onerror = function (event) {
  15690. generateBlobUrl();
  15691. };
  15692. }
  15693. catch (ex) {
  15694. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15695. if (ex.code === 25) {
  15696. Database.isUASupportingBlobStorage = false;
  15697. }
  15698. image.src = url;
  15699. }
  15700. }
  15701. else {
  15702. image.src = url;
  15703. }
  15704. }, false);
  15705. xhr.addEventListener("error", function (event) {
  15706. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15707. image.src = url;
  15708. }, false);
  15709. xhr.send();
  15710. }
  15711. else {
  15712. image.src = url;
  15713. }
  15714. }
  15715. else {
  15716. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15717. image.src = url;
  15718. }
  15719. };
  15720. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15721. var _this = this;
  15722. var updateVersion = function (event) {
  15723. // the version is not yet in the DB or we need to update it
  15724. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15725. };
  15726. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15727. };
  15728. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15729. var _this = this;
  15730. if (this.isSupported) {
  15731. var version;
  15732. try {
  15733. var transaction = this.db.transaction(["versions"]);
  15734. transaction.oncomplete = function (event) {
  15735. if (version) {
  15736. // If the version in the JSON file is > than the version in DB
  15737. if (_this.manifestVersionFound > version.data) {
  15738. _this.mustUpdateRessources = true;
  15739. updateInDBCallback();
  15740. }
  15741. else {
  15742. callback(version.data);
  15743. }
  15744. }
  15745. else {
  15746. _this.mustUpdateRessources = true;
  15747. updateInDBCallback();
  15748. }
  15749. };
  15750. transaction.onabort = function (event) {
  15751. callback(-1);
  15752. };
  15753. var getRequest = transaction.objectStore("versions").get(url);
  15754. getRequest.onsuccess = function (event) {
  15755. version = (event.target).result;
  15756. };
  15757. getRequest.onerror = function (event) {
  15758. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15759. callback(-1);
  15760. };
  15761. }
  15762. catch (ex) {
  15763. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15764. callback(-1);
  15765. }
  15766. }
  15767. else {
  15768. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15769. callback(-1);
  15770. }
  15771. };
  15772. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15773. var _this = this;
  15774. if (this.isSupported && !this.hasReachedQuota) {
  15775. try {
  15776. // Open a transaction to the database
  15777. var transaction = this.db.transaction(["versions"], "readwrite");
  15778. // the transaction could abort because of a QuotaExceededError error
  15779. transaction.onabort = function (event) {
  15780. try {
  15781. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15782. _this.hasReachedQuota = true;
  15783. }
  15784. }
  15785. catch (ex) {
  15786. }
  15787. callback(-1);
  15788. };
  15789. transaction.oncomplete = function (event) {
  15790. callback(_this.manifestVersionFound);
  15791. };
  15792. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15793. // Put the scene into the database
  15794. var addRequest = transaction.objectStore("versions").put(newVersion);
  15795. addRequest.onsuccess = function (event) {
  15796. };
  15797. addRequest.onerror = function (event) {
  15798. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15799. };
  15800. }
  15801. catch (ex) {
  15802. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15803. callback(-1);
  15804. }
  15805. }
  15806. else {
  15807. callback(-1);
  15808. }
  15809. };
  15810. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15811. var _this = this;
  15812. var completeUrl = Database.ReturnFullUrlLocation(url);
  15813. var saveAndLoadFile = function (event) {
  15814. // the scene is not yet in the DB, let's try to save it
  15815. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15816. };
  15817. this._checkVersionFromDB(completeUrl, function (version) {
  15818. if (version !== -1) {
  15819. if (!_this.mustUpdateRessources) {
  15820. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15821. }
  15822. else {
  15823. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15824. }
  15825. }
  15826. else {
  15827. errorCallback();
  15828. }
  15829. });
  15830. };
  15831. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15832. if (this.isSupported) {
  15833. var targetStore;
  15834. if (url.indexOf(".babylon") !== -1) {
  15835. targetStore = "scenes";
  15836. }
  15837. else {
  15838. targetStore = "textures";
  15839. }
  15840. var file;
  15841. var transaction = this.db.transaction([targetStore]);
  15842. transaction.oncomplete = function (event) {
  15843. if (file) {
  15844. callback(file.data);
  15845. }
  15846. else {
  15847. notInDBCallback();
  15848. }
  15849. };
  15850. transaction.onabort = function (event) {
  15851. notInDBCallback();
  15852. };
  15853. var getRequest = transaction.objectStore(targetStore).get(url);
  15854. getRequest.onsuccess = function (event) {
  15855. file = (event.target).result;
  15856. };
  15857. getRequest.onerror = function (event) {
  15858. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15859. notInDBCallback();
  15860. };
  15861. }
  15862. else {
  15863. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15864. callback();
  15865. }
  15866. };
  15867. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15868. var _this = this;
  15869. if (this.isSupported) {
  15870. var targetStore;
  15871. if (url.indexOf(".babylon") !== -1) {
  15872. targetStore = "scenes";
  15873. }
  15874. else {
  15875. targetStore = "textures";
  15876. }
  15877. // Create XHR
  15878. var xhr = new XMLHttpRequest(), fileData;
  15879. xhr.open("GET", url, true);
  15880. if (useArrayBuffer) {
  15881. xhr.responseType = "arraybuffer";
  15882. }
  15883. xhr.onprogress = progressCallback;
  15884. xhr.addEventListener("load", function () {
  15885. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15886. // Blob as response (XHR2)
  15887. //fileData = xhr.responseText;
  15888. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15889. if (!_this.hasReachedQuota) {
  15890. // Open a transaction to the database
  15891. var transaction = _this.db.transaction([targetStore], "readwrite");
  15892. // the transaction could abort because of a QuotaExceededError error
  15893. transaction.onabort = function (event) {
  15894. try {
  15895. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15896. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15897. this.hasReachedQuota = true;
  15898. }
  15899. }
  15900. catch (ex) {
  15901. }
  15902. callback(fileData);
  15903. };
  15904. transaction.oncomplete = function (event) {
  15905. callback(fileData);
  15906. };
  15907. var newFile;
  15908. if (targetStore === "scenes") {
  15909. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15910. }
  15911. else {
  15912. newFile = { textureUrl: url, data: fileData };
  15913. }
  15914. try {
  15915. // Put the scene into the database
  15916. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15917. addRequest.onsuccess = function (event) {
  15918. };
  15919. addRequest.onerror = function (event) {
  15920. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15921. };
  15922. }
  15923. catch (ex) {
  15924. callback(fileData);
  15925. }
  15926. }
  15927. else {
  15928. callback(fileData);
  15929. }
  15930. }
  15931. else {
  15932. callback();
  15933. }
  15934. }, false);
  15935. xhr.addEventListener("error", function (event) {
  15936. BABYLON.Tools.Error("error on XHR request.");
  15937. callback();
  15938. }, false);
  15939. xhr.send();
  15940. }
  15941. else {
  15942. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15943. callback();
  15944. }
  15945. };
  15946. Database.isUASupportingBlobStorage = true;
  15947. Database.parseURL = function (url) {
  15948. var a = document.createElement('a');
  15949. a.href = url;
  15950. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15951. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15952. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15953. return absLocation;
  15954. };
  15955. Database.ReturnFullUrlLocation = function (url) {
  15956. if (url.indexOf("http:/") === -1) {
  15957. return (BABYLON.Database.parseURL(window.location.href) + url);
  15958. }
  15959. else {
  15960. return url;
  15961. }
  15962. };
  15963. return Database;
  15964. })();
  15965. BABYLON.Database = Database;
  15966. })(BABYLON || (BABYLON = {}));
  15967. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15968. (function (BABYLON) {
  15969. var SpriteManager = (function () {
  15970. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15972. this.name = name;
  15973. this.cellSize = cellSize;
  15974. this.sprites = new Array();
  15975. this.renderingGroupId = 0;
  15976. this.fogEnabled = true;
  15977. this._vertexDeclaration = [4, 4, 4, 4];
  15978. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15979. this._capacity = capacity;
  15980. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15981. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15982. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15983. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15984. this._scene = scene;
  15985. this._scene.spriteManagers.push(this);
  15986. // VBO
  15987. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15988. var indices = [];
  15989. var index = 0;
  15990. for (var count = 0; count < capacity; count++) {
  15991. indices.push(index);
  15992. indices.push(index + 1);
  15993. indices.push(index + 2);
  15994. indices.push(index);
  15995. indices.push(index + 2);
  15996. indices.push(index + 3);
  15997. index += 4;
  15998. }
  15999. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16000. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16001. // Effects
  16002. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  16003. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  16004. }
  16005. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  16006. var arrayOffset = index * 16;
  16007. if (offsetX === 0)
  16008. offsetX = this._epsilon;
  16009. else if (offsetX === 1)
  16010. offsetX = 1 - this._epsilon;
  16011. if (offsetY === 0)
  16012. offsetY = this._epsilon;
  16013. else if (offsetY === 1)
  16014. offsetY = 1 - this._epsilon;
  16015. this._vertices[arrayOffset] = sprite.position.x;
  16016. this._vertices[arrayOffset + 1] = sprite.position.y;
  16017. this._vertices[arrayOffset + 2] = sprite.position.z;
  16018. this._vertices[arrayOffset + 3] = sprite.angle;
  16019. this._vertices[arrayOffset + 4] = sprite.width;
  16020. this._vertices[arrayOffset + 5] = sprite.height;
  16021. this._vertices[arrayOffset + 6] = offsetX;
  16022. this._vertices[arrayOffset + 7] = offsetY;
  16023. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16024. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16025. var offset = (sprite.cellIndex / rowSize) >> 0;
  16026. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16027. this._vertices[arrayOffset + 11] = offset;
  16028. // Color
  16029. this._vertices[arrayOffset + 12] = sprite.color.r;
  16030. this._vertices[arrayOffset + 13] = sprite.color.g;
  16031. this._vertices[arrayOffset + 14] = sprite.color.b;
  16032. this._vertices[arrayOffset + 15] = sprite.color.a;
  16033. };
  16034. SpriteManager.prototype.render = function () {
  16035. // Check
  16036. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16037. return;
  16038. var engine = this._scene.getEngine();
  16039. var baseSize = this._spriteTexture.getBaseSize();
  16040. // Sprites
  16041. var deltaTime = engine.getDeltaTime();
  16042. var max = Math.min(this._capacity, this.sprites.length);
  16043. var rowSize = baseSize.width / this.cellSize;
  16044. var offset = 0;
  16045. for (var index = 0; index < max; index++) {
  16046. var sprite = this.sprites[index];
  16047. if (!sprite) {
  16048. continue;
  16049. }
  16050. sprite._animate(deltaTime);
  16051. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16052. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16053. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16054. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16055. }
  16056. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16057. // Render
  16058. var effect = this._effectBase;
  16059. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16060. effect = this._effectFog;
  16061. }
  16062. engine.enableEffect(effect);
  16063. var viewMatrix = this._scene.getViewMatrix();
  16064. effect.setTexture("diffuseSampler", this._spriteTexture);
  16065. effect.setMatrix("view", viewMatrix);
  16066. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16067. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16068. // Fog
  16069. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16070. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16071. effect.setColor3("vFogColor", this._scene.fogColor);
  16072. }
  16073. // VBOs
  16074. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16075. // Draw order
  16076. engine.setDepthFunctionToLessOrEqual();
  16077. effect.setBool("alphaTest", true);
  16078. engine.setColorWrite(false);
  16079. engine.draw(true, 0, max * 6);
  16080. engine.setColorWrite(true);
  16081. effect.setBool("alphaTest", false);
  16082. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16083. engine.draw(true, 0, max * 6);
  16084. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16085. };
  16086. SpriteManager.prototype.dispose = function () {
  16087. if (this._vertexBuffer) {
  16088. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16089. this._vertexBuffer = null;
  16090. }
  16091. if (this._indexBuffer) {
  16092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16093. this._indexBuffer = null;
  16094. }
  16095. if (this._spriteTexture) {
  16096. this._spriteTexture.dispose();
  16097. this._spriteTexture = null;
  16098. }
  16099. // Remove from scene
  16100. var index = this._scene.spriteManagers.indexOf(this);
  16101. this._scene.spriteManagers.splice(index, 1);
  16102. // Callback
  16103. if (this.onDispose) {
  16104. this.onDispose();
  16105. }
  16106. };
  16107. return SpriteManager;
  16108. })();
  16109. BABYLON.SpriteManager = SpriteManager;
  16110. })(BABYLON || (BABYLON = {}));
  16111. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16112. (function (BABYLON) {
  16113. var Sprite = (function () {
  16114. function Sprite(name, manager) {
  16115. this.name = name;
  16116. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16117. this.width = 1.0;
  16118. this.height = 1.0;
  16119. this.angle = 0;
  16120. this.cellIndex = 0;
  16121. this.invertU = 0;
  16122. this.invertV = 0;
  16123. this.animations = new Array();
  16124. this._animationStarted = false;
  16125. this._loopAnimation = false;
  16126. this._fromIndex = 0;
  16127. this._toIndex = 0;
  16128. this._delay = 0;
  16129. this._direction = 1;
  16130. this._frameCount = 0;
  16131. this._time = 0;
  16132. this._manager = manager;
  16133. this._manager.sprites.push(this);
  16134. this.position = BABYLON.Vector3.Zero();
  16135. }
  16136. Object.defineProperty(Sprite.prototype, "size", {
  16137. get: function () {
  16138. return this.width;
  16139. },
  16140. set: function (value) {
  16141. this.width = value;
  16142. this.height = value;
  16143. },
  16144. enumerable: true,
  16145. configurable: true
  16146. });
  16147. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16148. this._fromIndex = from;
  16149. this._toIndex = to;
  16150. this._loopAnimation = loop;
  16151. this._delay = delay;
  16152. this._animationStarted = true;
  16153. this._direction = from < to ? 1 : -1;
  16154. this.cellIndex = from;
  16155. this._time = 0;
  16156. };
  16157. Sprite.prototype.stopAnimation = function () {
  16158. this._animationStarted = false;
  16159. };
  16160. Sprite.prototype._animate = function (deltaTime) {
  16161. if (!this._animationStarted)
  16162. return;
  16163. this._time += deltaTime;
  16164. if (this._time > this._delay) {
  16165. this._time = this._time % this._delay;
  16166. this.cellIndex += this._direction;
  16167. if (this.cellIndex == this._toIndex) {
  16168. if (this._loopAnimation) {
  16169. this.cellIndex = this._fromIndex;
  16170. }
  16171. else {
  16172. this._animationStarted = false;
  16173. if (this.disposeWhenFinishedAnimating) {
  16174. this.dispose();
  16175. }
  16176. }
  16177. }
  16178. }
  16179. };
  16180. Sprite.prototype.dispose = function () {
  16181. for (var i = 0; i < this._manager.sprites.length; i++) {
  16182. if (this._manager.sprites[i] == this) {
  16183. this._manager.sprites.splice(i, 1);
  16184. }
  16185. }
  16186. };
  16187. return Sprite;
  16188. })();
  16189. BABYLON.Sprite = Sprite;
  16190. })(BABYLON || (BABYLON = {}));
  16191. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16192. (function (BABYLON) {
  16193. var Layer = (function () {
  16194. function Layer(name, imgUrl, scene, isBackground, color) {
  16195. this.name = name;
  16196. this._vertexDeclaration = [2];
  16197. this._vertexStrideSize = 2 * 4;
  16198. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16199. this.isBackground = isBackground === undefined ? true : isBackground;
  16200. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16201. this._scene = scene;
  16202. this._scene.layers.push(this);
  16203. // VBO
  16204. var vertices = [];
  16205. vertices.push(1, 1);
  16206. vertices.push(-1, 1);
  16207. vertices.push(-1, -1);
  16208. vertices.push(1, -1);
  16209. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16210. // Indices
  16211. var indices = [];
  16212. indices.push(0);
  16213. indices.push(1);
  16214. indices.push(2);
  16215. indices.push(0);
  16216. indices.push(2);
  16217. indices.push(3);
  16218. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16219. // Effects
  16220. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16221. }
  16222. Layer.prototype.render = function () {
  16223. // Check
  16224. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16225. return;
  16226. var engine = this._scene.getEngine();
  16227. // Render
  16228. engine.enableEffect(this._effect);
  16229. engine.setState(false);
  16230. // Texture
  16231. this._effect.setTexture("textureSampler", this.texture);
  16232. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16233. // Color
  16234. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16235. // VBOs
  16236. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16237. // Draw order
  16238. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16239. engine.draw(true, 0, 6);
  16240. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16241. };
  16242. Layer.prototype.dispose = function () {
  16243. if (this._vertexBuffer) {
  16244. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16245. this._vertexBuffer = null;
  16246. }
  16247. if (this._indexBuffer) {
  16248. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16249. this._indexBuffer = null;
  16250. }
  16251. if (this.texture) {
  16252. this.texture.dispose();
  16253. this.texture = null;
  16254. }
  16255. // Remove from scene
  16256. var index = this._scene.layers.indexOf(this);
  16257. this._scene.layers.splice(index, 1);
  16258. // Callback
  16259. if (this.onDispose) {
  16260. this.onDispose();
  16261. }
  16262. };
  16263. return Layer;
  16264. })();
  16265. BABYLON.Layer = Layer;
  16266. })(BABYLON || (BABYLON = {}));
  16267. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16268. (function (BABYLON) {
  16269. var Particle = (function () {
  16270. function Particle() {
  16271. this.position = BABYLON.Vector3.Zero();
  16272. this.direction = BABYLON.Vector3.Zero();
  16273. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16274. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16275. this.lifeTime = 1.0;
  16276. this.age = 0;
  16277. this.size = 0;
  16278. this.angle = 0;
  16279. this.angularSpeed = 0;
  16280. }
  16281. Particle.prototype.copyTo = function (other) {
  16282. other.position.copyFrom(this.position);
  16283. other.direction.copyFrom(this.direction);
  16284. other.color.copyFrom(this.color);
  16285. other.colorStep.copyFrom(this.colorStep);
  16286. other.lifeTime = this.lifeTime;
  16287. other.age = this.age;
  16288. other.size = this.size;
  16289. other.angle = this.angle;
  16290. other.angularSpeed = this.angularSpeed;
  16291. };
  16292. return Particle;
  16293. })();
  16294. BABYLON.Particle = Particle;
  16295. })(BABYLON || (BABYLON = {}));
  16296. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16297. (function (BABYLON) {
  16298. var randomNumber = function (min, max) {
  16299. if (min === max) {
  16300. return (min);
  16301. }
  16302. var random = Math.random();
  16303. return ((random * (max - min)) + min);
  16304. };
  16305. var ParticleSystem = (function () {
  16306. function ParticleSystem(name, capacity, scene, customEffect) {
  16307. var _this = this;
  16308. this.name = name;
  16309. this.renderingGroupId = 0;
  16310. this.emitter = null;
  16311. this.emitRate = 10;
  16312. this.manualEmitCount = -1;
  16313. this.updateSpeed = 0.01;
  16314. this.targetStopDuration = 0;
  16315. this.disposeOnStop = false;
  16316. this.minEmitPower = 1;
  16317. this.maxEmitPower = 1;
  16318. this.minLifeTime = 1;
  16319. this.maxLifeTime = 1;
  16320. this.minSize = 1;
  16321. this.maxSize = 1;
  16322. this.minAngularSpeed = 0;
  16323. this.maxAngularSpeed = 0;
  16324. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16325. this.forceDepthWrite = false;
  16326. this.gravity = BABYLON.Vector3.Zero();
  16327. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16328. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16329. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16330. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16331. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16332. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16333. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16334. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16335. this.particles = new Array();
  16336. this._vertexDeclaration = [3, 4, 4];
  16337. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16338. this._stockParticles = new Array();
  16339. this._newPartsExcess = 0;
  16340. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16341. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16342. this._scaledDirection = BABYLON.Vector3.Zero();
  16343. this._scaledGravity = BABYLON.Vector3.Zero();
  16344. this._currentRenderId = -1;
  16345. this._started = false;
  16346. this._stopped = false;
  16347. this._actualFrame = 0;
  16348. this.id = name;
  16349. this._capacity = capacity;
  16350. this._scene = scene;
  16351. this._customEffect = customEffect;
  16352. scene.particleSystems.push(this);
  16353. // VBO
  16354. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16355. var indices = [];
  16356. var index = 0;
  16357. for (var count = 0; count < capacity; count++) {
  16358. indices.push(index);
  16359. indices.push(index + 1);
  16360. indices.push(index + 2);
  16361. indices.push(index);
  16362. indices.push(index + 2);
  16363. indices.push(index + 3);
  16364. index += 4;
  16365. }
  16366. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16367. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16368. // Default behaviors
  16369. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16370. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16371. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16372. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16373. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16374. };
  16375. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16376. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16377. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16378. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16379. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16380. };
  16381. this.updateFunction = function (particles) {
  16382. for (var index = 0; index < particles.length; index++) {
  16383. var particle = particles[index];
  16384. particle.age += _this._scaledUpdateSpeed;
  16385. if (particle.age >= particle.lifeTime) {
  16386. _this.recycleParticle(particle);
  16387. index--;
  16388. continue;
  16389. }
  16390. else {
  16391. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16392. particle.color.addInPlace(_this._scaledColorStep);
  16393. if (particle.color.a < 0)
  16394. particle.color.a = 0;
  16395. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16396. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16397. particle.position.addInPlace(_this._scaledDirection);
  16398. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16399. particle.direction.addInPlace(_this._scaledGravity);
  16400. }
  16401. }
  16402. };
  16403. }
  16404. ParticleSystem.prototype.recycleParticle = function (particle) {
  16405. var lastParticle = this.particles.pop();
  16406. if (lastParticle !== particle) {
  16407. lastParticle.copyTo(particle);
  16408. this._stockParticles.push(lastParticle);
  16409. }
  16410. };
  16411. ParticleSystem.prototype.getCapacity = function () {
  16412. return this._capacity;
  16413. };
  16414. ParticleSystem.prototype.isAlive = function () {
  16415. return this._alive;
  16416. };
  16417. ParticleSystem.prototype.isStarted = function () {
  16418. return this._started;
  16419. };
  16420. ParticleSystem.prototype.start = function () {
  16421. this._started = true;
  16422. this._stopped = false;
  16423. this._actualFrame = 0;
  16424. };
  16425. ParticleSystem.prototype.stop = function () {
  16426. this._stopped = true;
  16427. };
  16428. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16429. var offset = index * 11;
  16430. this._vertices[offset] = particle.position.x;
  16431. this._vertices[offset + 1] = particle.position.y;
  16432. this._vertices[offset + 2] = particle.position.z;
  16433. this._vertices[offset + 3] = particle.color.r;
  16434. this._vertices[offset + 4] = particle.color.g;
  16435. this._vertices[offset + 5] = particle.color.b;
  16436. this._vertices[offset + 6] = particle.color.a;
  16437. this._vertices[offset + 7] = particle.angle;
  16438. this._vertices[offset + 8] = particle.size;
  16439. this._vertices[offset + 9] = offsetX;
  16440. this._vertices[offset + 10] = offsetY;
  16441. };
  16442. ParticleSystem.prototype._update = function (newParticles) {
  16443. // Update current
  16444. this._alive = this.particles.length > 0;
  16445. this.updateFunction(this.particles);
  16446. // Add new ones
  16447. var worldMatrix;
  16448. if (this.emitter.position) {
  16449. worldMatrix = this.emitter.getWorldMatrix();
  16450. }
  16451. else {
  16452. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16453. }
  16454. for (var index = 0; index < newParticles; index++) {
  16455. if (this.particles.length === this._capacity) {
  16456. break;
  16457. }
  16458. if (this._stockParticles.length !== 0) {
  16459. var particle = this._stockParticles.pop();
  16460. particle.age = 0;
  16461. }
  16462. else {
  16463. particle = new BABYLON.Particle();
  16464. }
  16465. this.particles.push(particle);
  16466. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16467. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16468. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16469. particle.size = randomNumber(this.minSize, this.maxSize);
  16470. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16471. this.startPositionFunction(worldMatrix, particle.position);
  16472. var step = randomNumber(0, 1.0);
  16473. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16474. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16475. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16476. }
  16477. };
  16478. ParticleSystem.prototype._getEffect = function () {
  16479. if (this._customEffect) {
  16480. return this._customEffect;
  16481. }
  16482. ;
  16483. var defines = [];
  16484. if (this._scene.clipPlane) {
  16485. defines.push("#define CLIPPLANE");
  16486. }
  16487. // Effect
  16488. var join = defines.join("\n");
  16489. if (this._cachedDefines !== join) {
  16490. this._cachedDefines = join;
  16491. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16492. }
  16493. return this._effect;
  16494. };
  16495. ParticleSystem.prototype.animate = function () {
  16496. if (!this._started)
  16497. return;
  16498. var effect = this._getEffect();
  16499. // Check
  16500. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16501. return;
  16502. if (this._currentRenderId === this._scene.getRenderId()) {
  16503. return;
  16504. }
  16505. this._currentRenderId = this._scene.getRenderId();
  16506. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16507. // determine the number of particles we need to create
  16508. var emitCout;
  16509. if (this.manualEmitCount > -1) {
  16510. emitCout = this.manualEmitCount;
  16511. this.manualEmitCount = 0;
  16512. }
  16513. else {
  16514. emitCout = this.emitRate;
  16515. }
  16516. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16517. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16518. if (this._newPartsExcess > 1.0) {
  16519. newParticles += this._newPartsExcess >> 0;
  16520. this._newPartsExcess -= this._newPartsExcess >> 0;
  16521. }
  16522. this._alive = false;
  16523. if (!this._stopped) {
  16524. this._actualFrame += this._scaledUpdateSpeed;
  16525. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16526. this.stop();
  16527. }
  16528. else {
  16529. newParticles = 0;
  16530. }
  16531. this._update(newParticles);
  16532. // Stopped?
  16533. if (this._stopped) {
  16534. if (!this._alive) {
  16535. this._started = false;
  16536. if (this.disposeOnStop) {
  16537. this._scene._toBeDisposed.push(this);
  16538. }
  16539. }
  16540. }
  16541. // Update VBO
  16542. var offset = 0;
  16543. for (var index = 0; index < this.particles.length; index++) {
  16544. var particle = this.particles[index];
  16545. this._appendParticleVertex(offset++, particle, 0, 0);
  16546. this._appendParticleVertex(offset++, particle, 1, 0);
  16547. this._appendParticleVertex(offset++, particle, 1, 1);
  16548. this._appendParticleVertex(offset++, particle, 0, 1);
  16549. }
  16550. var engine = this._scene.getEngine();
  16551. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16552. };
  16553. ParticleSystem.prototype.render = function () {
  16554. var effect = this._getEffect();
  16555. // Check
  16556. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16557. return 0;
  16558. var engine = this._scene.getEngine();
  16559. // Render
  16560. engine.enableEffect(effect);
  16561. engine.setState(false);
  16562. var viewMatrix = this._scene.getViewMatrix();
  16563. effect.setTexture("diffuseSampler", this.particleTexture);
  16564. effect.setMatrix("view", viewMatrix);
  16565. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16566. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16567. if (this._scene.clipPlane) {
  16568. var clipPlane = this._scene.clipPlane;
  16569. var invView = viewMatrix.clone();
  16570. invView.invert();
  16571. effect.setMatrix("invView", invView);
  16572. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16573. }
  16574. // VBOs
  16575. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16576. // Draw order
  16577. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16578. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16579. }
  16580. else {
  16581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16582. }
  16583. if (this.forceDepthWrite) {
  16584. engine.setDepthWrite(true);
  16585. }
  16586. engine.draw(true, 0, this.particles.length * 6);
  16587. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16588. return this.particles.length;
  16589. };
  16590. ParticleSystem.prototype.dispose = function () {
  16591. if (this._vertexBuffer) {
  16592. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16593. this._vertexBuffer = null;
  16594. }
  16595. if (this._indexBuffer) {
  16596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16597. this._indexBuffer = null;
  16598. }
  16599. if (this.particleTexture) {
  16600. this.particleTexture.dispose();
  16601. this.particleTexture = null;
  16602. }
  16603. // Remove from scene
  16604. var index = this._scene.particleSystems.indexOf(this);
  16605. this._scene.particleSystems.splice(index, 1);
  16606. // Callback
  16607. if (this.onDispose) {
  16608. this.onDispose();
  16609. }
  16610. };
  16611. // Clone
  16612. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16613. var result = new ParticleSystem(name, this._capacity, this._scene);
  16614. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16615. if (newEmitter === undefined) {
  16616. newEmitter = this.emitter;
  16617. }
  16618. result.emitter = newEmitter;
  16619. if (this.particleTexture) {
  16620. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16621. }
  16622. result.start();
  16623. return result;
  16624. };
  16625. // Statics
  16626. ParticleSystem.BLENDMODE_ONEONE = 0;
  16627. ParticleSystem.BLENDMODE_STANDARD = 1;
  16628. return ParticleSystem;
  16629. })();
  16630. BABYLON.ParticleSystem = ParticleSystem;
  16631. })(BABYLON || (BABYLON = {}));
  16632. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16633. (function (BABYLON) {
  16634. var Animation = (function () {
  16635. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16636. this.name = name;
  16637. this.targetProperty = targetProperty;
  16638. this.framePerSecond = framePerSecond;
  16639. this.dataType = dataType;
  16640. this.loopMode = loopMode;
  16641. this._offsetsCache = {};
  16642. this._highLimitsCache = {};
  16643. this._stopped = false;
  16644. this.targetPropertyPath = targetProperty.split(".");
  16645. this.dataType = dataType;
  16646. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16647. }
  16648. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16649. var dataType = undefined;
  16650. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16651. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16652. }
  16653. else if (from instanceof BABYLON.Quaternion) {
  16654. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16655. }
  16656. else if (from instanceof BABYLON.Vector3) {
  16657. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16658. }
  16659. else if (from instanceof BABYLON.Vector2) {
  16660. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16661. }
  16662. else if (from instanceof BABYLON.Color3) {
  16663. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16664. }
  16665. if (dataType == undefined) {
  16666. return null;
  16667. }
  16668. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16669. var keys = [];
  16670. keys.push({ frame: 0, value: from });
  16671. keys.push({ frame: totalFrame, value: to });
  16672. animation.setKeys(keys);
  16673. mesh.animations.push(animation);
  16674. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16675. };
  16676. // Methods
  16677. Animation.prototype.isStopped = function () {
  16678. return this._stopped;
  16679. };
  16680. Animation.prototype.getKeys = function () {
  16681. return this._keys;
  16682. };
  16683. Animation.prototype.getEasingFunction = function () {
  16684. return this._easingFunction;
  16685. };
  16686. Animation.prototype.setEasingFunction = function (easingFunction) {
  16687. this._easingFunction = easingFunction;
  16688. };
  16689. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16690. return startValue + (endValue - startValue) * gradient;
  16691. };
  16692. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16693. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16694. };
  16695. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16696. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16697. };
  16698. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16699. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16700. };
  16701. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16702. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16703. };
  16704. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16705. var startScale = new BABYLON.Vector3(0, 0, 0);
  16706. var startRotation = new BABYLON.Quaternion();
  16707. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16708. startValue.decompose(startScale, startRotation, startTranslation);
  16709. var endScale = new BABYLON.Vector3(0, 0, 0);
  16710. var endRotation = new BABYLON.Quaternion();
  16711. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16712. endValue.decompose(endScale, endRotation, endTranslation);
  16713. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16714. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16715. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16716. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16717. return result;
  16718. };
  16719. Animation.prototype.clone = function () {
  16720. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16721. clone.setKeys(this._keys);
  16722. return clone;
  16723. };
  16724. Animation.prototype.setKeys = function (values) {
  16725. this._keys = values.slice(0);
  16726. this._offsetsCache = {};
  16727. this._highLimitsCache = {};
  16728. };
  16729. Animation.prototype._getKeyValue = function (value) {
  16730. if (typeof value === "function") {
  16731. return value();
  16732. }
  16733. return value;
  16734. };
  16735. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16736. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16737. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16738. }
  16739. this.currentFrame = currentFrame;
  16740. // Try to get a hash to find the right key
  16741. 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));
  16742. if (this._keys[startKey].frame >= currentFrame) {
  16743. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16744. startKey--;
  16745. }
  16746. }
  16747. for (var key = startKey; key < this._keys.length; key++) {
  16748. if (this._keys[key + 1].frame >= currentFrame) {
  16749. var startValue = this._getKeyValue(this._keys[key].value);
  16750. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16751. // gradient : percent of currentFrame between the frame inf and the frame sup
  16752. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16753. // check for easingFunction and correction of gradient
  16754. if (this._easingFunction != null) {
  16755. gradient = this._easingFunction.ease(gradient);
  16756. }
  16757. switch (this.dataType) {
  16758. case Animation.ANIMATIONTYPE_FLOAT:
  16759. switch (loopMode) {
  16760. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16761. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16762. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16763. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16764. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16765. }
  16766. break;
  16767. case Animation.ANIMATIONTYPE_QUATERNION:
  16768. var quaternion = null;
  16769. switch (loopMode) {
  16770. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16771. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16772. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16773. break;
  16774. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16775. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16776. break;
  16777. }
  16778. return quaternion;
  16779. case Animation.ANIMATIONTYPE_VECTOR3:
  16780. switch (loopMode) {
  16781. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16782. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16783. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16784. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16785. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16786. }
  16787. case Animation.ANIMATIONTYPE_VECTOR2:
  16788. switch (loopMode) {
  16789. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16790. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16791. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16792. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16793. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16794. }
  16795. case Animation.ANIMATIONTYPE_COLOR3:
  16796. switch (loopMode) {
  16797. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16798. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16799. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16800. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16801. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16802. }
  16803. case Animation.ANIMATIONTYPE_MATRIX:
  16804. switch (loopMode) {
  16805. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16806. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16807. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16808. return startValue;
  16809. }
  16810. default:
  16811. break;
  16812. }
  16813. break;
  16814. }
  16815. }
  16816. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16817. };
  16818. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16819. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16820. this._stopped = true;
  16821. return false;
  16822. }
  16823. var returnValue = true;
  16824. // Adding a start key at frame 0 if missing
  16825. if (this._keys[0].frame !== 0) {
  16826. var newKey = { frame: 0, value: this._keys[0].value };
  16827. this._keys.splice(0, 0, newKey);
  16828. }
  16829. // Check limits
  16830. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16831. from = this._keys[0].frame;
  16832. }
  16833. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16834. to = this._keys[this._keys.length - 1].frame;
  16835. }
  16836. // Compute ratio
  16837. var range = to - from;
  16838. var offsetValue;
  16839. // ratio represents the frame delta between from and to
  16840. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16841. var highLimitValue = 0;
  16842. if (ratio > range && !loop) {
  16843. returnValue = false;
  16844. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16845. }
  16846. else {
  16847. // Get max value if required
  16848. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16849. var keyOffset = to.toString() + from.toString();
  16850. if (!this._offsetsCache[keyOffset]) {
  16851. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16852. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16853. switch (this.dataType) {
  16854. case Animation.ANIMATIONTYPE_FLOAT:
  16855. this._offsetsCache[keyOffset] = toValue - fromValue;
  16856. break;
  16857. case Animation.ANIMATIONTYPE_QUATERNION:
  16858. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16859. break;
  16860. case Animation.ANIMATIONTYPE_VECTOR3:
  16861. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16862. case Animation.ANIMATIONTYPE_VECTOR2:
  16863. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16864. case Animation.ANIMATIONTYPE_COLOR3:
  16865. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16866. default:
  16867. break;
  16868. }
  16869. this._highLimitsCache[keyOffset] = toValue;
  16870. }
  16871. highLimitValue = this._highLimitsCache[keyOffset];
  16872. offsetValue = this._offsetsCache[keyOffset];
  16873. }
  16874. }
  16875. if (offsetValue === undefined) {
  16876. switch (this.dataType) {
  16877. case Animation.ANIMATIONTYPE_FLOAT:
  16878. offsetValue = 0;
  16879. break;
  16880. case Animation.ANIMATIONTYPE_QUATERNION:
  16881. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16882. break;
  16883. case Animation.ANIMATIONTYPE_VECTOR3:
  16884. offsetValue = BABYLON.Vector3.Zero();
  16885. break;
  16886. case Animation.ANIMATIONTYPE_VECTOR2:
  16887. offsetValue = BABYLON.Vector2.Zero();
  16888. break;
  16889. case Animation.ANIMATIONTYPE_COLOR3:
  16890. offsetValue = BABYLON.Color3.Black();
  16891. }
  16892. }
  16893. // Compute value
  16894. var repeatCount = (ratio / range) >> 0;
  16895. var currentFrame = returnValue ? from + ratio % range : to;
  16896. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16897. // Set value
  16898. if (this.targetPropertyPath.length > 1) {
  16899. var property = this._target[this.targetPropertyPath[0]];
  16900. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16901. property = property[this.targetPropertyPath[index]];
  16902. }
  16903. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16904. }
  16905. else {
  16906. this._target[this.targetPropertyPath[0]] = currentValue;
  16907. }
  16908. if (this._target.markAsDirty) {
  16909. this._target.markAsDirty(this.targetProperty);
  16910. }
  16911. if (!returnValue) {
  16912. this._stopped = true;
  16913. }
  16914. return returnValue;
  16915. };
  16916. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16917. get: function () {
  16918. return Animation._ANIMATIONTYPE_FLOAT;
  16919. },
  16920. enumerable: true,
  16921. configurable: true
  16922. });
  16923. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16924. get: function () {
  16925. return Animation._ANIMATIONTYPE_VECTOR3;
  16926. },
  16927. enumerable: true,
  16928. configurable: true
  16929. });
  16930. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16931. get: function () {
  16932. return Animation._ANIMATIONTYPE_VECTOR2;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16938. get: function () {
  16939. return Animation._ANIMATIONTYPE_QUATERNION;
  16940. },
  16941. enumerable: true,
  16942. configurable: true
  16943. });
  16944. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16945. get: function () {
  16946. return Animation._ANIMATIONTYPE_MATRIX;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16952. get: function () {
  16953. return Animation._ANIMATIONTYPE_COLOR3;
  16954. },
  16955. enumerable: true,
  16956. configurable: true
  16957. });
  16958. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16959. get: function () {
  16960. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16966. get: function () {
  16967. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16973. get: function () {
  16974. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. // Statics
  16980. Animation._ANIMATIONTYPE_FLOAT = 0;
  16981. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16982. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16983. Animation._ANIMATIONTYPE_MATRIX = 3;
  16984. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16985. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16986. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16987. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16988. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16989. return Animation;
  16990. })();
  16991. BABYLON.Animation = Animation;
  16992. })(BABYLON || (BABYLON = {}));
  16993. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16994. (function (BABYLON) {
  16995. var Animatable = (function () {
  16996. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16997. if (fromFrame === void 0) { fromFrame = 0; }
  16998. if (toFrame === void 0) { toFrame = 100; }
  16999. if (loopAnimation === void 0) { loopAnimation = false; }
  17000. if (speedRatio === void 0) { speedRatio = 1.0; }
  17001. this.target = target;
  17002. this.fromFrame = fromFrame;
  17003. this.toFrame = toFrame;
  17004. this.loopAnimation = loopAnimation;
  17005. this.speedRatio = speedRatio;
  17006. this.onAnimationEnd = onAnimationEnd;
  17007. this._animations = new Array();
  17008. this._paused = false;
  17009. this.animationStarted = false;
  17010. if (animations) {
  17011. this.appendAnimations(target, animations);
  17012. }
  17013. this._scene = scene;
  17014. scene._activeAnimatables.push(this);
  17015. }
  17016. // Methods
  17017. Animatable.prototype.appendAnimations = function (target, animations) {
  17018. for (var index = 0; index < animations.length; index++) {
  17019. var animation = animations[index];
  17020. animation._target = target;
  17021. this._animations.push(animation);
  17022. }
  17023. };
  17024. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17025. var animations = this._animations;
  17026. for (var index = 0; index < animations.length; index++) {
  17027. if (animations[index].targetProperty === property) {
  17028. return animations[index];
  17029. }
  17030. }
  17031. return null;
  17032. };
  17033. Animatable.prototype.pause = function () {
  17034. if (this._paused) {
  17035. return;
  17036. }
  17037. this._paused = true;
  17038. };
  17039. Animatable.prototype.restart = function () {
  17040. this._paused = false;
  17041. };
  17042. Animatable.prototype.stop = function () {
  17043. var index = this._scene._activeAnimatables.indexOf(this);
  17044. if (index > -1) {
  17045. this._scene._activeAnimatables.splice(index, 1);
  17046. }
  17047. if (this.onAnimationEnd) {
  17048. this.onAnimationEnd();
  17049. }
  17050. };
  17051. Animatable.prototype._animate = function (delay) {
  17052. if (this._paused) {
  17053. if (!this._pausedDelay) {
  17054. this._pausedDelay = delay;
  17055. }
  17056. return true;
  17057. }
  17058. if (!this._localDelayOffset) {
  17059. this._localDelayOffset = delay;
  17060. }
  17061. else if (this._pausedDelay) {
  17062. this._localDelayOffset += delay - this._pausedDelay;
  17063. this._pausedDelay = null;
  17064. }
  17065. // Animating
  17066. var running = false;
  17067. var animations = this._animations;
  17068. for (var index = 0; index < animations.length; index++) {
  17069. var animation = animations[index];
  17070. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17071. running = running || isRunning;
  17072. }
  17073. if (!running) {
  17074. // Remove from active animatables
  17075. index = this._scene._activeAnimatables.indexOf(this);
  17076. this._scene._activeAnimatables.splice(index, 1);
  17077. }
  17078. if (!running && this.onAnimationEnd) {
  17079. this.onAnimationEnd();
  17080. }
  17081. return running;
  17082. };
  17083. return Animatable;
  17084. })();
  17085. BABYLON.Animatable = Animatable;
  17086. })(BABYLON || (BABYLON = {}));
  17087. //# sourceMappingURL=babylon.animatable.js.map
  17088. var BABYLON;
  17089. (function (BABYLON) {
  17090. var EasingFunction = (function () {
  17091. function EasingFunction() {
  17092. // Properties
  17093. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17094. }
  17095. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17096. get: function () {
  17097. return EasingFunction._EASINGMODE_EASEIN;
  17098. },
  17099. enumerable: true,
  17100. configurable: true
  17101. });
  17102. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17103. get: function () {
  17104. return EasingFunction._EASINGMODE_EASEOUT;
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17110. get: function () {
  17111. return EasingFunction._EASINGMODE_EASEINOUT;
  17112. },
  17113. enumerable: true,
  17114. configurable: true
  17115. });
  17116. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17117. var n = Math.min(Math.max(easingMode, 0), 2);
  17118. this._easingMode = n;
  17119. };
  17120. EasingFunction.prototype.getEasingMode = function () {
  17121. return this._easingMode;
  17122. };
  17123. EasingFunction.prototype.easeInCore = function (gradient) {
  17124. throw new Error('You must implement this method');
  17125. };
  17126. EasingFunction.prototype.ease = function (gradient) {
  17127. switch (this._easingMode) {
  17128. case EasingFunction.EASINGMODE_EASEIN:
  17129. return this.easeInCore(gradient);
  17130. case EasingFunction.EASINGMODE_EASEOUT:
  17131. return (1 - this.easeInCore(1 - gradient));
  17132. }
  17133. if (gradient >= 0.5) {
  17134. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17135. }
  17136. return (this.easeInCore(gradient * 2) * 0.5);
  17137. };
  17138. //Statics
  17139. EasingFunction._EASINGMODE_EASEIN = 0;
  17140. EasingFunction._EASINGMODE_EASEOUT = 1;
  17141. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17142. return EasingFunction;
  17143. })();
  17144. BABYLON.EasingFunction = EasingFunction;
  17145. var CircleEase = (function (_super) {
  17146. __extends(CircleEase, _super);
  17147. function CircleEase() {
  17148. _super.apply(this, arguments);
  17149. }
  17150. CircleEase.prototype.easeInCore = function (gradient) {
  17151. gradient = Math.max(0, Math.min(1, gradient));
  17152. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17153. };
  17154. return CircleEase;
  17155. })(EasingFunction);
  17156. BABYLON.CircleEase = CircleEase;
  17157. var BackEase = (function (_super) {
  17158. __extends(BackEase, _super);
  17159. function BackEase(amplitude) {
  17160. if (amplitude === void 0) { amplitude = 1; }
  17161. _super.call(this);
  17162. this.amplitude = amplitude;
  17163. }
  17164. BackEase.prototype.easeInCore = function (gradient) {
  17165. var num = Math.max(0, this.amplitude);
  17166. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17167. };
  17168. return BackEase;
  17169. })(EasingFunction);
  17170. BABYLON.BackEase = BackEase;
  17171. var BounceEase = (function (_super) {
  17172. __extends(BounceEase, _super);
  17173. function BounceEase(bounces, bounciness) {
  17174. if (bounces === void 0) { bounces = 3; }
  17175. if (bounciness === void 0) { bounciness = 2; }
  17176. _super.call(this);
  17177. this.bounces = bounces;
  17178. this.bounciness = bounciness;
  17179. }
  17180. BounceEase.prototype.easeInCore = function (gradient) {
  17181. var y = Math.max(0.0, this.bounces);
  17182. var bounciness = this.bounciness;
  17183. if (bounciness <= 1.0) {
  17184. bounciness = 1.001;
  17185. }
  17186. var num9 = Math.pow(bounciness, y);
  17187. var num5 = 1.0 - bounciness;
  17188. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17189. var num15 = gradient * num4;
  17190. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17191. var num3 = Math.floor(num65);
  17192. var num13 = num3 + 1.0;
  17193. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17194. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17195. var num7 = (num8 + num12) * 0.5;
  17196. var num6 = gradient - num7;
  17197. var num2 = num7 - num8;
  17198. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17199. };
  17200. return BounceEase;
  17201. })(EasingFunction);
  17202. BABYLON.BounceEase = BounceEase;
  17203. var CubicEase = (function (_super) {
  17204. __extends(CubicEase, _super);
  17205. function CubicEase() {
  17206. _super.apply(this, arguments);
  17207. }
  17208. CubicEase.prototype.easeInCore = function (gradient) {
  17209. return (gradient * gradient * gradient);
  17210. };
  17211. return CubicEase;
  17212. })(EasingFunction);
  17213. BABYLON.CubicEase = CubicEase;
  17214. var ElasticEase = (function (_super) {
  17215. __extends(ElasticEase, _super);
  17216. function ElasticEase(oscillations, springiness) {
  17217. if (oscillations === void 0) { oscillations = 3; }
  17218. if (springiness === void 0) { springiness = 3; }
  17219. _super.call(this);
  17220. this.oscillations = oscillations;
  17221. this.springiness = springiness;
  17222. }
  17223. ElasticEase.prototype.easeInCore = function (gradient) {
  17224. var num2;
  17225. var num3 = Math.max(0.0, this.oscillations);
  17226. var num = Math.max(0.0, this.springiness);
  17227. if (num == 0) {
  17228. num2 = gradient;
  17229. }
  17230. else {
  17231. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17232. }
  17233. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17234. };
  17235. return ElasticEase;
  17236. })(EasingFunction);
  17237. BABYLON.ElasticEase = ElasticEase;
  17238. var ExponentialEase = (function (_super) {
  17239. __extends(ExponentialEase, _super);
  17240. function ExponentialEase(exponent) {
  17241. if (exponent === void 0) { exponent = 2; }
  17242. _super.call(this);
  17243. this.exponent = exponent;
  17244. }
  17245. ExponentialEase.prototype.easeInCore = function (gradient) {
  17246. if (this.exponent <= 0) {
  17247. return gradient;
  17248. }
  17249. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17250. };
  17251. return ExponentialEase;
  17252. })(EasingFunction);
  17253. BABYLON.ExponentialEase = ExponentialEase;
  17254. var PowerEase = (function (_super) {
  17255. __extends(PowerEase, _super);
  17256. function PowerEase(power) {
  17257. if (power === void 0) { power = 2; }
  17258. _super.call(this);
  17259. this.power = power;
  17260. }
  17261. PowerEase.prototype.easeInCore = function (gradient) {
  17262. var y = Math.max(0.0, this.power);
  17263. return Math.pow(gradient, y);
  17264. };
  17265. return PowerEase;
  17266. })(EasingFunction);
  17267. BABYLON.PowerEase = PowerEase;
  17268. var QuadraticEase = (function (_super) {
  17269. __extends(QuadraticEase, _super);
  17270. function QuadraticEase() {
  17271. _super.apply(this, arguments);
  17272. }
  17273. QuadraticEase.prototype.easeInCore = function (gradient) {
  17274. return (gradient * gradient);
  17275. };
  17276. return QuadraticEase;
  17277. })(EasingFunction);
  17278. BABYLON.QuadraticEase = QuadraticEase;
  17279. var QuarticEase = (function (_super) {
  17280. __extends(QuarticEase, _super);
  17281. function QuarticEase() {
  17282. _super.apply(this, arguments);
  17283. }
  17284. QuarticEase.prototype.easeInCore = function (gradient) {
  17285. return (gradient * gradient * gradient * gradient);
  17286. };
  17287. return QuarticEase;
  17288. })(EasingFunction);
  17289. BABYLON.QuarticEase = QuarticEase;
  17290. var QuinticEase = (function (_super) {
  17291. __extends(QuinticEase, _super);
  17292. function QuinticEase() {
  17293. _super.apply(this, arguments);
  17294. }
  17295. QuinticEase.prototype.easeInCore = function (gradient) {
  17296. return (gradient * gradient * gradient * gradient * gradient);
  17297. };
  17298. return QuinticEase;
  17299. })(EasingFunction);
  17300. BABYLON.QuinticEase = QuinticEase;
  17301. var SineEase = (function (_super) {
  17302. __extends(SineEase, _super);
  17303. function SineEase() {
  17304. _super.apply(this, arguments);
  17305. }
  17306. SineEase.prototype.easeInCore = function (gradient) {
  17307. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17308. };
  17309. return SineEase;
  17310. })(EasingFunction);
  17311. BABYLON.SineEase = SineEase;
  17312. var BezierCurveEase = (function (_super) {
  17313. __extends(BezierCurveEase, _super);
  17314. function BezierCurveEase(x1, y1, x2, y2) {
  17315. if (x1 === void 0) { x1 = 0; }
  17316. if (y1 === void 0) { y1 = 0; }
  17317. if (x2 === void 0) { x2 = 1; }
  17318. if (y2 === void 0) { y2 = 1; }
  17319. _super.call(this);
  17320. this.x1 = x1;
  17321. this.y1 = y1;
  17322. this.x2 = x2;
  17323. this.y2 = y2;
  17324. }
  17325. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17326. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17327. };
  17328. return BezierCurveEase;
  17329. })(EasingFunction);
  17330. BABYLON.BezierCurveEase = BezierCurveEase;
  17331. })(BABYLON || (BABYLON = {}));
  17332. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17333. (function (BABYLON) {
  17334. var Octree = (function () {
  17335. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17336. if (maxDepth === void 0) { maxDepth = 2; }
  17337. this.maxDepth = maxDepth;
  17338. this.dynamicContent = new Array();
  17339. this._maxBlockCapacity = maxBlockCapacity || 64;
  17340. this._selectionContent = new BABYLON.SmartArray(1024);
  17341. this._creationFunc = creationFunc;
  17342. }
  17343. // Methods
  17344. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17345. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17346. };
  17347. Octree.prototype.addMesh = function (entry) {
  17348. for (var index = 0; index < this.blocks.length; index++) {
  17349. var block = this.blocks[index];
  17350. block.addEntry(entry);
  17351. }
  17352. };
  17353. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17354. this._selectionContent.reset();
  17355. for (var index = 0; index < this.blocks.length; index++) {
  17356. var block = this.blocks[index];
  17357. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17358. }
  17359. if (allowDuplicate) {
  17360. this._selectionContent.concat(this.dynamicContent);
  17361. }
  17362. else {
  17363. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17364. }
  17365. return this._selectionContent;
  17366. };
  17367. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17368. this._selectionContent.reset();
  17369. for (var index = 0; index < this.blocks.length; index++) {
  17370. var block = this.blocks[index];
  17371. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17372. }
  17373. if (allowDuplicate) {
  17374. this._selectionContent.concat(this.dynamicContent);
  17375. }
  17376. else {
  17377. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17378. }
  17379. return this._selectionContent;
  17380. };
  17381. Octree.prototype.intersectsRay = function (ray) {
  17382. this._selectionContent.reset();
  17383. for (var index = 0; index < this.blocks.length; index++) {
  17384. var block = this.blocks[index];
  17385. block.intersectsRay(ray, this._selectionContent);
  17386. }
  17387. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17388. return this._selectionContent;
  17389. };
  17390. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17391. target.blocks = new Array();
  17392. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17393. for (var x = 0; x < 2; x++) {
  17394. for (var y = 0; y < 2; y++) {
  17395. for (var z = 0; z < 2; z++) {
  17396. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17397. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17398. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17399. block.addEntries(entries);
  17400. target.blocks.push(block);
  17401. }
  17402. }
  17403. }
  17404. };
  17405. Octree.CreationFuncForMeshes = function (entry, block) {
  17406. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17407. block.entries.push(entry);
  17408. }
  17409. };
  17410. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17411. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17412. block.entries.push(entry);
  17413. }
  17414. };
  17415. return Octree;
  17416. })();
  17417. BABYLON.Octree = Octree;
  17418. })(BABYLON || (BABYLON = {}));
  17419. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17420. (function (BABYLON) {
  17421. var OctreeBlock = (function () {
  17422. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17423. this.entries = new Array();
  17424. this._boundingVectors = new Array();
  17425. this._capacity = capacity;
  17426. this._depth = depth;
  17427. this._maxDepth = maxDepth;
  17428. this._creationFunc = creationFunc;
  17429. this._minPoint = minPoint;
  17430. this._maxPoint = maxPoint;
  17431. this._boundingVectors.push(minPoint.clone());
  17432. this._boundingVectors.push(maxPoint.clone());
  17433. this._boundingVectors.push(minPoint.clone());
  17434. this._boundingVectors[2].x = maxPoint.x;
  17435. this._boundingVectors.push(minPoint.clone());
  17436. this._boundingVectors[3].y = maxPoint.y;
  17437. this._boundingVectors.push(minPoint.clone());
  17438. this._boundingVectors[4].z = maxPoint.z;
  17439. this._boundingVectors.push(maxPoint.clone());
  17440. this._boundingVectors[5].z = minPoint.z;
  17441. this._boundingVectors.push(maxPoint.clone());
  17442. this._boundingVectors[6].x = minPoint.x;
  17443. this._boundingVectors.push(maxPoint.clone());
  17444. this._boundingVectors[7].y = minPoint.y;
  17445. }
  17446. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17447. // Property
  17448. get: function () {
  17449. return this._capacity;
  17450. },
  17451. enumerable: true,
  17452. configurable: true
  17453. });
  17454. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17455. get: function () {
  17456. return this._minPoint;
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17462. get: function () {
  17463. return this._maxPoint;
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. // Methods
  17469. OctreeBlock.prototype.addEntry = function (entry) {
  17470. if (this.blocks) {
  17471. for (var index = 0; index < this.blocks.length; index++) {
  17472. var block = this.blocks[index];
  17473. block.addEntry(entry);
  17474. }
  17475. return;
  17476. }
  17477. this._creationFunc(entry, this);
  17478. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17479. this.createInnerBlocks();
  17480. }
  17481. };
  17482. OctreeBlock.prototype.addEntries = function (entries) {
  17483. for (var index = 0; index < entries.length; index++) {
  17484. var mesh = entries[index];
  17485. this.addEntry(mesh);
  17486. }
  17487. };
  17488. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17489. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17490. if (this.blocks) {
  17491. for (var index = 0; index < this.blocks.length; index++) {
  17492. var block = this.blocks[index];
  17493. block.select(frustumPlanes, selection, allowDuplicate);
  17494. }
  17495. return;
  17496. }
  17497. if (allowDuplicate) {
  17498. selection.concat(this.entries);
  17499. }
  17500. else {
  17501. selection.concatWithNoDuplicate(this.entries);
  17502. }
  17503. }
  17504. };
  17505. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17506. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17507. if (this.blocks) {
  17508. for (var index = 0; index < this.blocks.length; index++) {
  17509. var block = this.blocks[index];
  17510. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17511. }
  17512. return;
  17513. }
  17514. if (allowDuplicate) {
  17515. selection.concat(this.entries);
  17516. }
  17517. else {
  17518. selection.concatWithNoDuplicate(this.entries);
  17519. }
  17520. }
  17521. };
  17522. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17523. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17524. if (this.blocks) {
  17525. for (var index = 0; index < this.blocks.length; index++) {
  17526. var block = this.blocks[index];
  17527. block.intersectsRay(ray, selection);
  17528. }
  17529. return;
  17530. }
  17531. selection.concatWithNoDuplicate(this.entries);
  17532. }
  17533. };
  17534. OctreeBlock.prototype.createInnerBlocks = function () {
  17535. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17536. };
  17537. return OctreeBlock;
  17538. })();
  17539. BABYLON.OctreeBlock = OctreeBlock;
  17540. })(BABYLON || (BABYLON = {}));
  17541. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17542. (function (BABYLON) {
  17543. var Bone = (function () {
  17544. function Bone(name, skeleton, parentBone, matrix) {
  17545. this.name = name;
  17546. this.children = new Array();
  17547. this.animations = new Array();
  17548. this._worldTransform = new BABYLON.Matrix();
  17549. this._absoluteTransform = new BABYLON.Matrix();
  17550. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17551. this._skeleton = skeleton;
  17552. this._matrix = matrix;
  17553. this._baseMatrix = matrix;
  17554. skeleton.bones.push(this);
  17555. if (parentBone) {
  17556. this._parent = parentBone;
  17557. parentBone.children.push(this);
  17558. }
  17559. else {
  17560. this._parent = null;
  17561. }
  17562. this._updateDifferenceMatrix();
  17563. }
  17564. // Members
  17565. Bone.prototype.getParent = function () {
  17566. return this._parent;
  17567. };
  17568. Bone.prototype.getLocalMatrix = function () {
  17569. return this._matrix;
  17570. };
  17571. Bone.prototype.getBaseMatrix = function () {
  17572. return this._baseMatrix;
  17573. };
  17574. Bone.prototype.getWorldMatrix = function () {
  17575. return this._worldTransform;
  17576. };
  17577. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17578. return this._invertedAbsoluteTransform;
  17579. };
  17580. Bone.prototype.getAbsoluteMatrix = function () {
  17581. var matrix = this._matrix.clone();
  17582. var parent = this._parent;
  17583. while (parent) {
  17584. matrix = matrix.multiply(parent.getLocalMatrix());
  17585. parent = parent.getParent();
  17586. }
  17587. return matrix;
  17588. };
  17589. // Methods
  17590. Bone.prototype.updateMatrix = function (matrix) {
  17591. this._matrix = matrix;
  17592. this._skeleton._markAsDirty();
  17593. this._updateDifferenceMatrix();
  17594. };
  17595. Bone.prototype._updateDifferenceMatrix = function () {
  17596. if (this._parent) {
  17597. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17598. }
  17599. else {
  17600. this._absoluteTransform.copyFrom(this._matrix);
  17601. }
  17602. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17603. for (var index = 0; index < this.children.length; index++) {
  17604. this.children[index]._updateDifferenceMatrix();
  17605. }
  17606. };
  17607. Bone.prototype.markAsDirty = function () {
  17608. this._skeleton._markAsDirty();
  17609. };
  17610. return Bone;
  17611. })();
  17612. BABYLON.Bone = Bone;
  17613. })(BABYLON || (BABYLON = {}));
  17614. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17615. (function (BABYLON) {
  17616. var Skeleton = (function () {
  17617. function Skeleton(name, id, scene) {
  17618. this.name = name;
  17619. this.id = id;
  17620. this.bones = new Array();
  17621. this._isDirty = true;
  17622. this._identity = BABYLON.Matrix.Identity();
  17623. this.bones = [];
  17624. this._scene = scene;
  17625. scene.skeletons.push(this);
  17626. this.prepare();
  17627. //make sure it will recalculate the matrix next time prepare is called.
  17628. this._isDirty = true;
  17629. }
  17630. // Members
  17631. Skeleton.prototype.getTransformMatrices = function () {
  17632. return this._transformMatrices;
  17633. };
  17634. // Methods
  17635. Skeleton.prototype._markAsDirty = function () {
  17636. this._isDirty = true;
  17637. };
  17638. Skeleton.prototype.prepare = function () {
  17639. if (!this._isDirty) {
  17640. return;
  17641. }
  17642. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17643. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17644. }
  17645. for (var index = 0; index < this.bones.length; index++) {
  17646. var bone = this.bones[index];
  17647. var parentBone = bone.getParent();
  17648. if (parentBone) {
  17649. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17650. }
  17651. else {
  17652. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17653. }
  17654. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17655. }
  17656. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17657. this._isDirty = false;
  17658. this._scene._activeBones += this.bones.length;
  17659. };
  17660. Skeleton.prototype.getAnimatables = function () {
  17661. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17662. this._animatables = [];
  17663. for (var index = 0; index < this.bones.length; index++) {
  17664. this._animatables.push(this.bones[index]);
  17665. }
  17666. }
  17667. return this._animatables;
  17668. };
  17669. Skeleton.prototype.clone = function (name, id) {
  17670. var result = new Skeleton(name, id || name, this._scene);
  17671. for (var index = 0; index < this.bones.length; index++) {
  17672. var source = this.bones[index];
  17673. var parentBone = null;
  17674. if (source.getParent()) {
  17675. var parentIndex = this.bones.indexOf(source.getParent());
  17676. parentBone = result.bones[parentIndex];
  17677. }
  17678. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17679. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17680. }
  17681. return result;
  17682. };
  17683. return Skeleton;
  17684. })();
  17685. BABYLON.Skeleton = Skeleton;
  17686. })(BABYLON || (BABYLON = {}));
  17687. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17688. (function (BABYLON) {
  17689. var PostProcess = (function () {
  17690. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17692. this.name = name;
  17693. this.width = -1;
  17694. this.height = -1;
  17695. this._reusable = false;
  17696. this._textures = new BABYLON.SmartArray(2);
  17697. this._currentRenderTextureInd = 0;
  17698. if (camera != null) {
  17699. this._camera = camera;
  17700. this._scene = camera.getScene();
  17701. camera.attachPostProcess(this);
  17702. this._engine = this._scene.getEngine();
  17703. }
  17704. else {
  17705. this._engine = engine;
  17706. }
  17707. this._renderRatio = ratio;
  17708. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17709. this._reusable = reusable || false;
  17710. samplers = samplers || [];
  17711. samplers.push("textureSampler");
  17712. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17713. }
  17714. PostProcess.prototype.isReusable = function () {
  17715. return this._reusable;
  17716. };
  17717. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17718. camera = camera || this._camera;
  17719. var scene = camera.getScene();
  17720. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17721. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17722. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17723. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17724. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17725. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17726. if (this._textures.length > 0) {
  17727. for (var i = 0; i < this._textures.length; i++) {
  17728. this._engine._releaseTexture(this._textures.data[i]);
  17729. }
  17730. this._textures.reset();
  17731. }
  17732. this.width = desiredWidth;
  17733. this.height = desiredHeight;
  17734. 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 }));
  17735. if (this._reusable) {
  17736. 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 }));
  17737. }
  17738. if (this.onSizeChanged) {
  17739. this.onSizeChanged();
  17740. }
  17741. }
  17742. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17743. if (this.onActivate) {
  17744. this.onActivate(camera);
  17745. }
  17746. // Clear
  17747. if (this.clearColor) {
  17748. this._engine.clear(this.clearColor, true, true);
  17749. }
  17750. else {
  17751. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17752. }
  17753. if (this._reusable) {
  17754. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17755. }
  17756. };
  17757. PostProcess.prototype.apply = function () {
  17758. // Check
  17759. if (!this._effect.isReady())
  17760. return null;
  17761. // States
  17762. this._engine.enableEffect(this._effect);
  17763. this._engine.setState(false);
  17764. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17765. this._engine.setDepthBuffer(false);
  17766. this._engine.setDepthWrite(false);
  17767. // Texture
  17768. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17769. // Parameters
  17770. if (this.onApply) {
  17771. this.onApply(this._effect);
  17772. }
  17773. return this._effect;
  17774. };
  17775. PostProcess.prototype.dispose = function (camera) {
  17776. camera = camera || this._camera;
  17777. if (this._textures.length > 0) {
  17778. for (var i = 0; i < this._textures.length; i++) {
  17779. this._engine._releaseTexture(this._textures.data[i]);
  17780. }
  17781. this._textures.reset();
  17782. }
  17783. if (!camera) {
  17784. return;
  17785. }
  17786. camera.detachPostProcess(this);
  17787. var index = camera._postProcesses.indexOf(this);
  17788. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17789. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17790. }
  17791. };
  17792. return PostProcess;
  17793. })();
  17794. BABYLON.PostProcess = PostProcess;
  17795. })(BABYLON || (BABYLON = {}));
  17796. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17797. (function (BABYLON) {
  17798. var PostProcessManager = (function () {
  17799. function PostProcessManager(scene) {
  17800. this._vertexDeclaration = [2];
  17801. this._vertexStrideSize = 2 * 4;
  17802. this._scene = scene;
  17803. }
  17804. PostProcessManager.prototype._prepareBuffers = function () {
  17805. if (this._vertexBuffer) {
  17806. return;
  17807. }
  17808. // VBO
  17809. var vertices = [];
  17810. vertices.push(1, 1);
  17811. vertices.push(-1, 1);
  17812. vertices.push(-1, -1);
  17813. vertices.push(1, -1);
  17814. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17815. // Indices
  17816. var indices = [];
  17817. indices.push(0);
  17818. indices.push(1);
  17819. indices.push(2);
  17820. indices.push(0);
  17821. indices.push(2);
  17822. indices.push(3);
  17823. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17824. };
  17825. // Methods
  17826. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17827. var postProcesses = this._scene.activeCamera._postProcesses;
  17828. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17829. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17830. return false;
  17831. }
  17832. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17833. return true;
  17834. };
  17835. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17836. var engine = this._scene.getEngine();
  17837. for (var index = 0; index < postProcesses.length; index++) {
  17838. if (index < postProcesses.length - 1) {
  17839. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17840. }
  17841. else {
  17842. if (targetTexture) {
  17843. engine.bindFramebuffer(targetTexture);
  17844. }
  17845. else {
  17846. engine.restoreDefaultFramebuffer();
  17847. }
  17848. }
  17849. var pp = postProcesses[index];
  17850. var effect = pp.apply();
  17851. if (effect) {
  17852. if (pp.onBeforeRender) {
  17853. pp.onBeforeRender(effect);
  17854. }
  17855. // VBOs
  17856. this._prepareBuffers();
  17857. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17858. // Draw order
  17859. engine.draw(true, 0, 6);
  17860. }
  17861. }
  17862. // Restore depth buffer
  17863. engine.setDepthBuffer(true);
  17864. engine.setDepthWrite(true);
  17865. };
  17866. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17867. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17868. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17869. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17870. return;
  17871. }
  17872. var engine = this._scene.getEngine();
  17873. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17874. if (index < postProcessesTakenIndices.length - 1) {
  17875. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17876. }
  17877. else {
  17878. if (targetTexture) {
  17879. engine.bindFramebuffer(targetTexture);
  17880. }
  17881. else {
  17882. engine.restoreDefaultFramebuffer();
  17883. }
  17884. }
  17885. if (doNotPresent) {
  17886. break;
  17887. }
  17888. var pp = postProcesses[postProcessesTakenIndices[index]];
  17889. var effect = pp.apply();
  17890. if (effect) {
  17891. if (pp.onBeforeRender) {
  17892. pp.onBeforeRender(effect);
  17893. }
  17894. // VBOs
  17895. this._prepareBuffers();
  17896. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17897. // Draw order
  17898. engine.draw(true, 0, 6);
  17899. }
  17900. }
  17901. // Restore depth buffer
  17902. engine.setDepthBuffer(true);
  17903. engine.setDepthWrite(true);
  17904. };
  17905. PostProcessManager.prototype.dispose = function () {
  17906. if (this._vertexBuffer) {
  17907. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17908. this._vertexBuffer = null;
  17909. }
  17910. if (this._indexBuffer) {
  17911. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17912. this._indexBuffer = null;
  17913. }
  17914. };
  17915. return PostProcessManager;
  17916. })();
  17917. BABYLON.PostProcessManager = PostProcessManager;
  17918. })(BABYLON || (BABYLON = {}));
  17919. //# sourceMappingURL=babylon.postProcessManager.js.map
  17920. var BABYLON;
  17921. (function (BABYLON) {
  17922. var PassPostProcess = (function (_super) {
  17923. __extends(PassPostProcess, _super);
  17924. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17925. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17926. }
  17927. return PassPostProcess;
  17928. })(BABYLON.PostProcess);
  17929. BABYLON.PassPostProcess = PassPostProcess;
  17930. })(BABYLON || (BABYLON = {}));
  17931. //# sourceMappingURL=babylon.passPostProcess.js.map
  17932. var BABYLON;
  17933. (function (BABYLON) {
  17934. var BlurPostProcess = (function (_super) {
  17935. __extends(BlurPostProcess, _super);
  17936. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17937. var _this = this;
  17938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17939. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17940. this.direction = direction;
  17941. this.blurWidth = blurWidth;
  17942. this.onApply = function (effect) {
  17943. effect.setFloat2("screenSize", _this.width, _this.height);
  17944. effect.setVector2("direction", _this.direction);
  17945. effect.setFloat("blurWidth", _this.blurWidth);
  17946. };
  17947. }
  17948. return BlurPostProcess;
  17949. })(BABYLON.PostProcess);
  17950. BABYLON.BlurPostProcess = BlurPostProcess;
  17951. })(BABYLON || (BABYLON = {}));
  17952. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17953. var BABYLON;
  17954. (function (BABYLON) {
  17955. var FilterPostProcess = (function (_super) {
  17956. __extends(FilterPostProcess, _super);
  17957. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17958. var _this = this;
  17959. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17960. this.kernelMatrix = kernelMatrix;
  17961. this.onApply = function (effect) {
  17962. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17963. };
  17964. }
  17965. return FilterPostProcess;
  17966. })(BABYLON.PostProcess);
  17967. BABYLON.FilterPostProcess = FilterPostProcess;
  17968. })(BABYLON || (BABYLON = {}));
  17969. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17970. var BABYLON;
  17971. (function (BABYLON) {
  17972. var RefractionPostProcess = (function (_super) {
  17973. __extends(RefractionPostProcess, _super);
  17974. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17975. var _this = this;
  17976. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17977. this.color = color;
  17978. this.depth = depth;
  17979. this.colorLevel = colorLevel;
  17980. this.onActivate = function (cam) {
  17981. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17982. };
  17983. this.onApply = function (effect) {
  17984. effect.setColor3("baseColor", _this.color);
  17985. effect.setFloat("depth", _this.depth);
  17986. effect.setFloat("colorLevel", _this.colorLevel);
  17987. effect.setTexture("refractionSampler", _this._refRexture);
  17988. };
  17989. }
  17990. // Methods
  17991. RefractionPostProcess.prototype.dispose = function (camera) {
  17992. if (this._refRexture) {
  17993. this._refRexture.dispose();
  17994. }
  17995. _super.prototype.dispose.call(this, camera);
  17996. };
  17997. return RefractionPostProcess;
  17998. })(BABYLON.PostProcess);
  17999. BABYLON.RefractionPostProcess = RefractionPostProcess;
  18000. })(BABYLON || (BABYLON = {}));
  18001. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  18002. var BABYLON;
  18003. (function (BABYLON) {
  18004. var BlackAndWhitePostProcess = (function (_super) {
  18005. __extends(BlackAndWhitePostProcess, _super);
  18006. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18007. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  18008. }
  18009. return BlackAndWhitePostProcess;
  18010. })(BABYLON.PostProcess);
  18011. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  18012. })(BABYLON || (BABYLON = {}));
  18013. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  18014. var BABYLON;
  18015. (function (BABYLON) {
  18016. var ConvolutionPostProcess = (function (_super) {
  18017. __extends(ConvolutionPostProcess, _super);
  18018. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  18019. var _this = this;
  18020. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18021. this.kernel = kernel;
  18022. this.onApply = function (effect) {
  18023. effect.setFloat2("screenSize", _this.width, _this.height);
  18024. effect.setArray("kernel", _this.kernel);
  18025. };
  18026. }
  18027. // Statics
  18028. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18029. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18030. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18031. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18032. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18033. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18034. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18035. return ConvolutionPostProcess;
  18036. })(BABYLON.PostProcess);
  18037. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18038. })(BABYLON || (BABYLON = {}));
  18039. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18040. var BABYLON;
  18041. (function (BABYLON) {
  18042. var FxaaPostProcess = (function (_super) {
  18043. __extends(FxaaPostProcess, _super);
  18044. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18045. var _this = this;
  18046. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18047. this.onSizeChanged = function () {
  18048. _this.texelWidth = 1.0 / _this.width;
  18049. _this.texelHeight = 1.0 / _this.height;
  18050. };
  18051. this.onApply = function (effect) {
  18052. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18053. };
  18054. }
  18055. return FxaaPostProcess;
  18056. })(BABYLON.PostProcess);
  18057. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18058. })(BABYLON || (BABYLON = {}));
  18059. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18060. (function (BABYLON) {
  18061. var LensFlare = (function () {
  18062. function LensFlare(size, position, color, imgUrl, system) {
  18063. this.size = size;
  18064. this.position = position;
  18065. this.dispose = function () {
  18066. if (this.texture) {
  18067. this.texture.dispose();
  18068. }
  18069. // Remove from scene
  18070. var index = this._system.lensFlares.indexOf(this);
  18071. this._system.lensFlares.splice(index, 1);
  18072. };
  18073. this.color = color || new BABYLON.Color3(1, 1, 1);
  18074. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18075. this._system = system;
  18076. system.lensFlares.push(this);
  18077. }
  18078. return LensFlare;
  18079. })();
  18080. BABYLON.LensFlare = LensFlare;
  18081. })(BABYLON || (BABYLON = {}));
  18082. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18083. (function (BABYLON) {
  18084. var LensFlareSystem = (function () {
  18085. function LensFlareSystem(name, emitter, scene) {
  18086. this.name = name;
  18087. this.lensFlares = new Array();
  18088. this.borderLimit = 300;
  18089. this._vertexDeclaration = [2];
  18090. this._vertexStrideSize = 2 * 4;
  18091. this._isEnabled = true;
  18092. this._scene = scene;
  18093. this._emitter = emitter;
  18094. scene.lensFlareSystems.push(this);
  18095. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18096. // VBO
  18097. var vertices = [];
  18098. vertices.push(1, 1);
  18099. vertices.push(-1, 1);
  18100. vertices.push(-1, -1);
  18101. vertices.push(1, -1);
  18102. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18103. // Indices
  18104. var indices = [];
  18105. indices.push(0);
  18106. indices.push(1);
  18107. indices.push(2);
  18108. indices.push(0);
  18109. indices.push(2);
  18110. indices.push(3);
  18111. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18112. // Effects
  18113. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18114. }
  18115. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18116. get: function () {
  18117. return this._isEnabled;
  18118. },
  18119. set: function (value) {
  18120. this._isEnabled = value;
  18121. },
  18122. enumerable: true,
  18123. configurable: true
  18124. });
  18125. LensFlareSystem.prototype.getScene = function () {
  18126. return this._scene;
  18127. };
  18128. LensFlareSystem.prototype.getEmitter = function () {
  18129. return this._emitter;
  18130. };
  18131. LensFlareSystem.prototype.getEmitterPosition = function () {
  18132. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18133. };
  18134. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18135. var position = this.getEmitterPosition();
  18136. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18137. this._positionX = position.x;
  18138. this._positionY = position.y;
  18139. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18140. if (position.z > 0) {
  18141. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18142. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18143. return true;
  18144. }
  18145. }
  18146. return false;
  18147. };
  18148. LensFlareSystem.prototype._isVisible = function () {
  18149. if (!this._isEnabled) {
  18150. return false;
  18151. }
  18152. var emitterPosition = this.getEmitterPosition();
  18153. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18154. var distance = direction.length();
  18155. direction.normalize();
  18156. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18157. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18158. return !pickInfo.hit || pickInfo.distance > distance;
  18159. };
  18160. LensFlareSystem.prototype.render = function () {
  18161. if (!this._effect.isReady())
  18162. return false;
  18163. var engine = this._scene.getEngine();
  18164. var viewport = this._scene.activeCamera.viewport;
  18165. var globalViewport = viewport.toGlobal(engine);
  18166. // Position
  18167. if (!this.computeEffectivePosition(globalViewport)) {
  18168. return false;
  18169. }
  18170. // Visibility
  18171. if (!this._isVisible()) {
  18172. return false;
  18173. }
  18174. // Intensity
  18175. var awayX;
  18176. var awayY;
  18177. if (this._positionX < this.borderLimit + globalViewport.x) {
  18178. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18179. }
  18180. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18181. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18182. }
  18183. else {
  18184. awayX = 0;
  18185. }
  18186. if (this._positionY < this.borderLimit + globalViewport.y) {
  18187. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18188. }
  18189. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18190. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18191. }
  18192. else {
  18193. awayY = 0;
  18194. }
  18195. var away = (awayX > awayY) ? awayX : awayY;
  18196. if (away > this.borderLimit) {
  18197. away = this.borderLimit;
  18198. }
  18199. var intensity = 1.0 - (away / this.borderLimit);
  18200. if (intensity < 0) {
  18201. return false;
  18202. }
  18203. if (intensity > 1.0) {
  18204. intensity = 1.0;
  18205. }
  18206. // Position
  18207. var centerX = globalViewport.x + globalViewport.width / 2;
  18208. var centerY = globalViewport.y + globalViewport.height / 2;
  18209. var distX = centerX - this._positionX;
  18210. var distY = centerY - this._positionY;
  18211. // Effects
  18212. engine.enableEffect(this._effect);
  18213. engine.setState(false);
  18214. engine.setDepthBuffer(false);
  18215. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18216. // VBOs
  18217. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18218. for (var index = 0; index < this.lensFlares.length; index++) {
  18219. var flare = this.lensFlares[index];
  18220. var x = centerX - (distX * flare.position);
  18221. var y = centerY - (distY * flare.position);
  18222. var cw = flare.size;
  18223. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18224. var cx = 2 * (x / globalViewport.width) - 1.0;
  18225. var cy = 1.0 - 2 * (y / globalViewport.height);
  18226. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18227. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18228. // Texture
  18229. this._effect.setTexture("textureSampler", flare.texture);
  18230. // Color
  18231. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18232. // Draw order
  18233. engine.draw(true, 0, 6);
  18234. }
  18235. engine.setDepthBuffer(true);
  18236. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18237. return true;
  18238. };
  18239. LensFlareSystem.prototype.dispose = function () {
  18240. if (this._vertexBuffer) {
  18241. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18242. this._vertexBuffer = null;
  18243. }
  18244. if (this._indexBuffer) {
  18245. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18246. this._indexBuffer = null;
  18247. }
  18248. while (this.lensFlares.length) {
  18249. this.lensFlares[0].dispose();
  18250. }
  18251. // Remove from scene
  18252. var index = this._scene.lensFlareSystems.indexOf(this);
  18253. this._scene.lensFlareSystems.splice(index, 1);
  18254. };
  18255. return LensFlareSystem;
  18256. })();
  18257. BABYLON.LensFlareSystem = LensFlareSystem;
  18258. })(BABYLON || (BABYLON = {}));
  18259. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18260. (function (BABYLON) {
  18261. var IntersectionInfo = (function () {
  18262. function IntersectionInfo(bu, bv, distance) {
  18263. this.bu = bu;
  18264. this.bv = bv;
  18265. this.distance = distance;
  18266. this.faceId = 0;
  18267. this.subMeshId = 0;
  18268. }
  18269. return IntersectionInfo;
  18270. })();
  18271. BABYLON.IntersectionInfo = IntersectionInfo;
  18272. var PickingInfo = (function () {
  18273. function PickingInfo() {
  18274. this.hit = false;
  18275. this.distance = 0;
  18276. this.pickedPoint = null;
  18277. this.pickedMesh = null;
  18278. this.bu = 0;
  18279. this.bv = 0;
  18280. this.faceId = -1;
  18281. this.subMeshId = 0;
  18282. }
  18283. // Methods
  18284. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18285. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18286. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18287. return null;
  18288. }
  18289. var indices = this.pickedMesh.getIndices();
  18290. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18291. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18292. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18293. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18294. normal0 = normal0.scale(this.bu);
  18295. normal1 = normal1.scale(this.bv);
  18296. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18297. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18298. if (useWorldCoordinates) {
  18299. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18300. }
  18301. return result;
  18302. };
  18303. PickingInfo.prototype.getTextureCoordinates = function () {
  18304. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18305. return null;
  18306. }
  18307. var indices = this.pickedMesh.getIndices();
  18308. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18309. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18310. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18311. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18312. uv0 = uv0.scale(this.bu);
  18313. uv1 = uv1.scale(this.bv);
  18314. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18315. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18316. };
  18317. return PickingInfo;
  18318. })();
  18319. BABYLON.PickingInfo = PickingInfo;
  18320. })(BABYLON || (BABYLON = {}));
  18321. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18322. (function (BABYLON) {
  18323. var FilesInput = (function () {
  18324. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18325. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18326. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18327. this._engine = p_engine;
  18328. this._canvas = p_canvas;
  18329. this._currentScene = p_scene;
  18330. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18331. this._progressCallback = p_progressCallback;
  18332. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18333. this._textureLoadingCallback = p_textureLoadingCallback;
  18334. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18335. }
  18336. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18337. var _this = this;
  18338. if (p_elementToMonitor) {
  18339. this._elementToMonitor = p_elementToMonitor;
  18340. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18341. _this.drag(e);
  18342. }, false);
  18343. this._elementToMonitor.addEventListener("dragover", function (e) {
  18344. _this.drag(e);
  18345. }, false);
  18346. this._elementToMonitor.addEventListener("drop", function (e) {
  18347. _this.drop(e);
  18348. }, false);
  18349. }
  18350. };
  18351. FilesInput.prototype.renderFunction = function () {
  18352. if (this._additionnalRenderLoopLogicCallback) {
  18353. this._additionnalRenderLoopLogicCallback();
  18354. }
  18355. if (this._currentScene) {
  18356. if (this._textureLoadingCallback) {
  18357. var remaining = this._currentScene.getWaitingItemsCount();
  18358. if (remaining > 0) {
  18359. this._textureLoadingCallback(remaining);
  18360. }
  18361. }
  18362. this._currentScene.render();
  18363. }
  18364. };
  18365. FilesInput.prototype.drag = function (e) {
  18366. e.stopPropagation();
  18367. e.preventDefault();
  18368. };
  18369. FilesInput.prototype.drop = function (eventDrop) {
  18370. eventDrop.stopPropagation();
  18371. eventDrop.preventDefault();
  18372. this.loadFiles(eventDrop);
  18373. };
  18374. FilesInput.prototype.loadFiles = function (event) {
  18375. if (this._startingProcessingFilesCallback)
  18376. this._startingProcessingFilesCallback();
  18377. // Handling data transfer via drag'n'drop
  18378. if (event && event.dataTransfer && event.dataTransfer.files) {
  18379. this._filesToLoad = event.dataTransfer.files;
  18380. }
  18381. // Handling files from input files
  18382. if (event && event.target && event.target.files) {
  18383. this._filesToLoad = event.target.files;
  18384. }
  18385. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18386. for (var i = 0; i < this._filesToLoad.length; i++) {
  18387. switch (this._filesToLoad[i].type) {
  18388. case "image/jpeg":
  18389. case "image/png":
  18390. case "image/bmp":
  18391. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18392. break;
  18393. case "image/targa":
  18394. case "image/vnd.ms-dds":
  18395. case "audio/wav":
  18396. case "audio/x-wav":
  18397. case "audio/mp3":
  18398. case "audio/mpeg":
  18399. case "audio/mpeg3":
  18400. case "audio/x-mpeg-3":
  18401. case "audio/ogg":
  18402. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18403. break;
  18404. default:
  18405. 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) {
  18406. this._sceneFileToLoad = this._filesToLoad[i];
  18407. }
  18408. break;
  18409. }
  18410. }
  18411. this.reload();
  18412. }
  18413. };
  18414. FilesInput.prototype.reload = function () {
  18415. var _this = this;
  18416. var that = this;
  18417. // If a ".babylon" file has been provided
  18418. if (this._sceneFileToLoad) {
  18419. if (this._currentScene) {
  18420. this._engine.stopRenderLoop();
  18421. this._currentScene.dispose();
  18422. }
  18423. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18424. that._currentScene = newScene;
  18425. // Wait for textures and shaders to be ready
  18426. that._currentScene.executeWhenReady(function () {
  18427. // Attach camera to canvas inputs
  18428. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18429. that._currentScene.createDefaultCameraOrLight();
  18430. }
  18431. that._currentScene.activeCamera.attachControl(that._canvas);
  18432. if (that._sceneLoadedCallback) {
  18433. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18434. }
  18435. that._engine.runRenderLoop(function () {
  18436. that.renderFunction();
  18437. });
  18438. });
  18439. }, function (progress) {
  18440. if (_this._progressCallback) {
  18441. _this._progressCallback(progress);
  18442. }
  18443. });
  18444. }
  18445. else {
  18446. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18447. }
  18448. };
  18449. FilesInput.FilesTextures = new Array();
  18450. FilesInput.FilesToLoad = new Array();
  18451. return FilesInput;
  18452. })();
  18453. BABYLON.FilesInput = FilesInput;
  18454. })(BABYLON || (BABYLON = {}));
  18455. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18456. (function (BABYLON) {
  18457. var OimoJSPlugin = (function () {
  18458. function OimoJSPlugin() {
  18459. this._registeredMeshes = [];
  18460. /**
  18461. * Update the body position according to the mesh position
  18462. * @param mesh
  18463. */
  18464. this.updateBodyPosition = function (mesh) {
  18465. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18466. var registeredMesh = this._registeredMeshes[index];
  18467. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18468. var body = registeredMesh.body.body;
  18469. mesh.computeWorldMatrix(true);
  18470. var center = mesh.getBoundingInfo().boundingBox.center;
  18471. body.setPosition(center.x, center.y, center.z);
  18472. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18473. return;
  18474. }
  18475. // Case where the parent has been updated
  18476. if (registeredMesh.mesh.parent === mesh) {
  18477. mesh.computeWorldMatrix(true);
  18478. registeredMesh.mesh.computeWorldMatrix(true);
  18479. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18480. var absoluteRotation = mesh.rotation;
  18481. body = registeredMesh.body.body;
  18482. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18483. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18484. return;
  18485. }
  18486. }
  18487. };
  18488. }
  18489. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18490. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18491. };
  18492. OimoJSPlugin.prototype.initialize = function (iterations) {
  18493. this._world = new OIMO.World();
  18494. this._world.clear();
  18495. };
  18496. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18497. this._world.gravity = gravity;
  18498. };
  18499. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18500. var body = null;
  18501. this.unregisterMesh(mesh);
  18502. mesh.computeWorldMatrix(true);
  18503. var initialRotation = null;
  18504. if (mesh.rotationQuaternion) {
  18505. initialRotation = mesh.rotationQuaternion.clone();
  18506. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18507. mesh.computeWorldMatrix(true);
  18508. }
  18509. var bbox = mesh.getBoundingInfo().boundingBox;
  18510. // The delta between the mesh position and the mesh bounding box center
  18511. var deltaPosition = mesh.position.subtract(bbox.center);
  18512. // Transform delta position with the rotation
  18513. if (initialRotation) {
  18514. var m = new BABYLON.Matrix();
  18515. initialRotation.toRotationMatrix(m);
  18516. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18517. }
  18518. switch (impostor) {
  18519. case BABYLON.PhysicsEngine.SphereImpostor:
  18520. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18521. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18522. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18523. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18524. body = new OIMO.Body({
  18525. type: 'sphere',
  18526. size: [size],
  18527. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18528. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18529. move: options.mass != 0,
  18530. config: [options.mass, options.friction, options.restitution],
  18531. world: this._world
  18532. });
  18533. break;
  18534. case BABYLON.PhysicsEngine.PlaneImpostor:
  18535. case BABYLON.PhysicsEngine.CylinderImpostor:
  18536. case BABYLON.PhysicsEngine.BoxImpostor:
  18537. var min = bbox.minimumWorld;
  18538. var max = bbox.maximumWorld;
  18539. var box = max.subtract(min);
  18540. var sizeX = this._checkWithEpsilon(box.x);
  18541. var sizeY = this._checkWithEpsilon(box.y);
  18542. var sizeZ = this._checkWithEpsilon(box.z);
  18543. body = new OIMO.Body({
  18544. type: 'box',
  18545. size: [sizeX, sizeY, sizeZ],
  18546. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18547. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18548. move: options.mass != 0,
  18549. config: [options.mass, options.friction, options.restitution],
  18550. world: this._world
  18551. });
  18552. break;
  18553. }
  18554. //If quaternion was set as the rotation of the object
  18555. if (initialRotation) {
  18556. //We have to access the rigid body's properties to set the quaternion.
  18557. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18558. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18559. //update the internal rotation matrix
  18560. body.body.syncShapes();
  18561. }
  18562. this._registeredMeshes.push({
  18563. mesh: mesh,
  18564. body: body,
  18565. delta: deltaPosition
  18566. });
  18567. return body;
  18568. };
  18569. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18570. var types = [], sizes = [], positions = [], rotations = [];
  18571. var initialMesh = parts[0].mesh;
  18572. for (var index = 0; index < parts.length; index++) {
  18573. var part = parts[index];
  18574. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18575. types.push(bodyParameters.type);
  18576. sizes.push.apply(sizes, bodyParameters.size);
  18577. positions.push.apply(positions, bodyParameters.pos);
  18578. rotations.push.apply(rotations, bodyParameters.rot);
  18579. }
  18580. var body = new OIMO.Body({
  18581. type: types,
  18582. size: sizes,
  18583. pos: positions,
  18584. rot: rotations,
  18585. move: options.mass != 0,
  18586. config: [options.mass, options.friction, options.restitution],
  18587. world: this._world
  18588. });
  18589. this._registeredMeshes.push({
  18590. mesh: initialMesh,
  18591. body: body
  18592. });
  18593. return body;
  18594. };
  18595. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18596. var bodyParameters = null;
  18597. var mesh = part.mesh;
  18598. // We need the bounding box/sphere info to compute the physics body
  18599. mesh.computeWorldMatrix();
  18600. switch (part.impostor) {
  18601. case BABYLON.PhysicsEngine.SphereImpostor:
  18602. var bbox = mesh.getBoundingInfo().boundingBox;
  18603. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18604. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18605. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18606. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18607. bodyParameters = {
  18608. type: 'sphere',
  18609. /* bug with oimo : sphere needs 3 sizes in this case */
  18610. size: [size, -1, -1],
  18611. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18612. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18613. };
  18614. break;
  18615. case BABYLON.PhysicsEngine.PlaneImpostor:
  18616. case BABYLON.PhysicsEngine.BoxImpostor:
  18617. bbox = mesh.getBoundingInfo().boundingBox;
  18618. var min = bbox.minimumWorld;
  18619. var max = bbox.maximumWorld;
  18620. var box = max.subtract(min);
  18621. var sizeX = this._checkWithEpsilon(box.x);
  18622. var sizeY = this._checkWithEpsilon(box.y);
  18623. var sizeZ = this._checkWithEpsilon(box.z);
  18624. var relativePosition = mesh.position;
  18625. bodyParameters = {
  18626. type: 'box',
  18627. size: [sizeX, sizeY, sizeZ],
  18628. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18629. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18630. };
  18631. break;
  18632. }
  18633. return bodyParameters;
  18634. };
  18635. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18636. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18637. var registeredMesh = this._registeredMeshes[index];
  18638. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18639. if (registeredMesh.body) {
  18640. this._world.removeRigidBody(registeredMesh.body.body);
  18641. this._unbindBody(registeredMesh.body);
  18642. }
  18643. this._registeredMeshes.splice(index, 1);
  18644. return;
  18645. }
  18646. }
  18647. };
  18648. OimoJSPlugin.prototype._unbindBody = function (body) {
  18649. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18650. var registeredMesh = this._registeredMeshes[index];
  18651. if (registeredMesh.body === body) {
  18652. registeredMesh.body = null;
  18653. }
  18654. }
  18655. };
  18656. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18657. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18658. var registeredMesh = this._registeredMeshes[index];
  18659. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18660. // Get object mass to have a behaviour similar to cannon.js
  18661. var mass = registeredMesh.body.body.massInfo.mass;
  18662. // The force is scaled with the mass of object
  18663. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18664. return;
  18665. }
  18666. }
  18667. };
  18668. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18669. var body1 = null, body2 = null;
  18670. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18671. var registeredMesh = this._registeredMeshes[index];
  18672. if (registeredMesh.mesh === mesh1) {
  18673. body1 = registeredMesh.body.body;
  18674. }
  18675. else if (registeredMesh.mesh === mesh2) {
  18676. body2 = registeredMesh.body.body;
  18677. }
  18678. }
  18679. if (!body1 || !body2) {
  18680. return false;
  18681. }
  18682. if (!options) {
  18683. options = {};
  18684. }
  18685. new OIMO.Link({
  18686. type: options.type,
  18687. body1: body1,
  18688. body2: body2,
  18689. min: options.min,
  18690. max: options.max,
  18691. axe1: options.axe1,
  18692. axe2: options.axe2,
  18693. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18694. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18695. collision: options.collision,
  18696. spring: options.spring,
  18697. world: this._world
  18698. });
  18699. return true;
  18700. };
  18701. OimoJSPlugin.prototype.dispose = function () {
  18702. this._world.clear();
  18703. while (this._registeredMeshes.length) {
  18704. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18705. }
  18706. };
  18707. OimoJSPlugin.prototype.isSupported = function () {
  18708. return OIMO !== undefined;
  18709. };
  18710. OimoJSPlugin.prototype._getLastShape = function (body) {
  18711. var lastShape = body.shapes;
  18712. while (lastShape.next) {
  18713. lastShape = lastShape.next;
  18714. }
  18715. return lastShape;
  18716. };
  18717. OimoJSPlugin.prototype.runOneStep = function (time) {
  18718. this._world.step();
  18719. // Update the position of all registered meshes
  18720. var i = this._registeredMeshes.length;
  18721. var m;
  18722. while (i--) {
  18723. var body = this._registeredMeshes[i].body.body;
  18724. var mesh = this._registeredMeshes[i].mesh;
  18725. var delta = this._registeredMeshes[i].delta;
  18726. if (!body.sleeping) {
  18727. if (body.shapes.next) {
  18728. var parentShape = this._getLastShape(body);
  18729. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18730. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18731. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18732. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18733. if (!mesh.rotationQuaternion) {
  18734. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18735. }
  18736. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18737. mesh.computeWorldMatrix();
  18738. }
  18739. else {
  18740. m = body.getMatrix();
  18741. mtx = BABYLON.Matrix.FromArray(m);
  18742. // Body position
  18743. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18744. if (!delta) {
  18745. mesh.position.x = bodyX;
  18746. mesh.position.y = bodyY;
  18747. mesh.position.z = bodyZ;
  18748. }
  18749. else {
  18750. mesh.position.x = bodyX + delta.x;
  18751. mesh.position.y = bodyY + delta.y;
  18752. mesh.position.z = bodyZ + delta.z;
  18753. }
  18754. if (!mesh.rotationQuaternion) {
  18755. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18756. }
  18757. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18758. mesh.computeWorldMatrix();
  18759. }
  18760. }
  18761. }
  18762. };
  18763. return OimoJSPlugin;
  18764. })();
  18765. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18766. })(BABYLON || (BABYLON = {}));
  18767. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18768. (function (BABYLON) {
  18769. var PhysicsEngine = (function () {
  18770. function PhysicsEngine(plugin) {
  18771. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18772. }
  18773. PhysicsEngine.prototype._initialize = function (gravity) {
  18774. this._currentPlugin.initialize();
  18775. this._setGravity(gravity);
  18776. };
  18777. PhysicsEngine.prototype._runOneStep = function (delta) {
  18778. if (delta > 0.1) {
  18779. delta = 0.1;
  18780. }
  18781. else if (delta <= 0) {
  18782. delta = 1.0 / 60.0;
  18783. }
  18784. this._currentPlugin.runOneStep(delta);
  18785. };
  18786. PhysicsEngine.prototype._setGravity = function (gravity) {
  18787. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18788. this._currentPlugin.setGravity(this.gravity);
  18789. };
  18790. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18791. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18792. };
  18793. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18794. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18795. };
  18796. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18797. this._currentPlugin.unregisterMesh(mesh);
  18798. };
  18799. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18800. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18801. };
  18802. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18803. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18804. };
  18805. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18806. this._currentPlugin.updateBodyPosition(mesh);
  18807. };
  18808. PhysicsEngine.prototype.dispose = function () {
  18809. this._currentPlugin.dispose();
  18810. };
  18811. PhysicsEngine.prototype.isSupported = function () {
  18812. return this._currentPlugin.isSupported();
  18813. };
  18814. // Statics
  18815. PhysicsEngine.NoImpostor = 0;
  18816. PhysicsEngine.SphereImpostor = 1;
  18817. PhysicsEngine.BoxImpostor = 2;
  18818. PhysicsEngine.PlaneImpostor = 3;
  18819. PhysicsEngine.MeshImpostor = 4;
  18820. PhysicsEngine.CapsuleImpostor = 5;
  18821. PhysicsEngine.ConeImpostor = 6;
  18822. PhysicsEngine.CylinderImpostor = 7;
  18823. PhysicsEngine.ConvexHullImpostor = 8;
  18824. PhysicsEngine.Epsilon = 0.001;
  18825. return PhysicsEngine;
  18826. })();
  18827. BABYLON.PhysicsEngine = PhysicsEngine;
  18828. })(BABYLON || (BABYLON = {}));
  18829. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18830. (function (BABYLON) {
  18831. var serializeLight = function (light) {
  18832. var serializationObject = {};
  18833. serializationObject.name = light.name;
  18834. serializationObject.id = light.id;
  18835. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18836. if (light instanceof BABYLON.PointLight) {
  18837. serializationObject.type = 0;
  18838. serializationObject.position = light.position.asArray();
  18839. }
  18840. else if (light instanceof BABYLON.DirectionalLight) {
  18841. serializationObject.type = 1;
  18842. var directionalLight = light;
  18843. serializationObject.position = directionalLight.position.asArray();
  18844. serializationObject.direction = directionalLight.direction.asArray();
  18845. }
  18846. else if (light instanceof BABYLON.SpotLight) {
  18847. serializationObject.type = 2;
  18848. var spotLight = light;
  18849. serializationObject.position = spotLight.position.asArray();
  18850. serializationObject.direction = spotLight.position.asArray();
  18851. serializationObject.angle = spotLight.angle;
  18852. serializationObject.exponent = spotLight.exponent;
  18853. }
  18854. else if (light instanceof BABYLON.HemisphericLight) {
  18855. serializationObject.type = 3;
  18856. var hemisphericLight = light;
  18857. serializationObject.direction = hemisphericLight.direction.asArray();
  18858. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18859. }
  18860. if (light.intensity) {
  18861. serializationObject.intensity = light.intensity;
  18862. }
  18863. serializationObject.range = light.range;
  18864. serializationObject.diffuse = light.diffuse.asArray();
  18865. serializationObject.specular = light.specular.asArray();
  18866. return serializationObject;
  18867. };
  18868. var serializeFresnelParameter = function (fresnelParameter) {
  18869. var serializationObject = {};
  18870. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18871. serializationObject.leftColor = fresnelParameter.leftColor;
  18872. serializationObject.rightColor = fresnelParameter.rightColor;
  18873. serializationObject.bias = fresnelParameter.bias;
  18874. serializationObject.power = fresnelParameter.power;
  18875. return serializationObject;
  18876. };
  18877. var appendAnimations = function (source, destination) {
  18878. if (source.animations) {
  18879. destination.animations = [];
  18880. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18881. var animation = source.animations[animationIndex];
  18882. destination.animations.push(serializeAnimation(animation));
  18883. }
  18884. }
  18885. };
  18886. var serializeCamera = function (camera) {
  18887. var serializationObject = {};
  18888. serializationObject.name = camera.name;
  18889. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18890. serializationObject.id = camera.id;
  18891. serializationObject.position = camera.position.asArray();
  18892. // Parent
  18893. if (camera.parent) {
  18894. serializationObject.parentId = camera.parent.id;
  18895. }
  18896. serializationObject.fov = camera.fov;
  18897. serializationObject.minZ = camera.minZ;
  18898. serializationObject.maxZ = camera.maxZ;
  18899. serializationObject.inertia = camera.inertia;
  18900. //setting the type
  18901. if (camera instanceof BABYLON.FreeCamera) {
  18902. serializationObject.type = "FreeCamera";
  18903. }
  18904. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18905. serializationObject.type = "ArcRotateCamera";
  18906. }
  18907. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18908. serializationObject.type = "AnaglyphArcRotateCamera";
  18909. }
  18910. else if (camera instanceof BABYLON.GamepadCamera) {
  18911. serializationObject.type = "GamepadCamera";
  18912. }
  18913. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18914. serializationObject.type = "AnaglyphFreeCamera";
  18915. }
  18916. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18917. serializationObject.type = "DeviceOrientationCamera";
  18918. }
  18919. else if (camera instanceof BABYLON.FollowCamera) {
  18920. serializationObject.type = "FollowCamera";
  18921. }
  18922. else if (camera instanceof BABYLON.OculusCamera) {
  18923. serializationObject.type = "OculusCamera";
  18924. }
  18925. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18926. serializationObject.type = "OculusGamepadCamera";
  18927. }
  18928. else if (camera instanceof BABYLON.TouchCamera) {
  18929. serializationObject.type = "TouchCamera";
  18930. }
  18931. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18932. serializationObject.type = "VirtualJoysticksCamera";
  18933. }
  18934. else if (camera instanceof BABYLON.WebVRCamera) {
  18935. serializationObject.type = "WebVRCamera";
  18936. }
  18937. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18938. serializationObject.type = "VRDeviceOrientationCamera";
  18939. }
  18940. //special properties of specific cameras
  18941. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18942. var arcCamera = camera;
  18943. serializationObject.alpha = arcCamera.alpha;
  18944. serializationObject.beta = arcCamera.beta;
  18945. serializationObject.radius = arcCamera.radius;
  18946. if (arcCamera.target && arcCamera.target.id) {
  18947. serializationObject.lockedTargetId = arcCamera.target.id;
  18948. }
  18949. }
  18950. else if (camera instanceof BABYLON.FollowCamera) {
  18951. var followCam = camera;
  18952. serializationObject.radius = followCam.radius;
  18953. serializationObject.heightOffset = followCam.heightOffset;
  18954. serializationObject.rotationOffset = followCam.rotationOffset;
  18955. }
  18956. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18957. //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.
  18958. if (camera['_eyeSpace'] !== undefined) {
  18959. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18960. }
  18961. }
  18962. //general properties that not all cameras have. The [] is due to typescript's type safety
  18963. if (camera['speed'] !== undefined) {
  18964. serializationObject.speed = camera['speed'];
  18965. }
  18966. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18967. serializationObject.target = camera['target'].asArray();
  18968. }
  18969. // Target
  18970. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18971. serializationObject.rotation = camera['rotation'].asArray();
  18972. }
  18973. // Locked target
  18974. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18975. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18976. }
  18977. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18978. serializationObject.applyGravity = camera['applyGravity'] || false;
  18979. if (camera['ellipsoid']) {
  18980. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18981. }
  18982. // Animations
  18983. appendAnimations(camera, serializationObject);
  18984. // Layer mask
  18985. serializationObject.layerMask = camera.layerMask;
  18986. return serializationObject;
  18987. };
  18988. var serializeAnimation = function (animation) {
  18989. var serializationObject = {};
  18990. serializationObject.name = animation.name;
  18991. serializationObject.property = animation.targetProperty;
  18992. serializationObject.framePerSecond = animation.framePerSecond;
  18993. serializationObject.dataType = animation.dataType;
  18994. serializationObject.loopBehavior = animation.loopMode;
  18995. var dataType = animation.dataType;
  18996. serializationObject.keys = [];
  18997. var keys = animation.getKeys();
  18998. for (var index = 0; index < keys.length; index++) {
  18999. var animationKey = keys[index];
  19000. var key = {};
  19001. key.frame = animationKey.frame;
  19002. switch (dataType) {
  19003. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19004. key.values = [animationKey.value];
  19005. break;
  19006. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19007. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19008. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19009. key.values = animationKey.value.asArray();
  19010. break;
  19011. }
  19012. serializationObject.keys.push(key);
  19013. }
  19014. return serializationObject;
  19015. };
  19016. var serializeMultiMaterial = function (material) {
  19017. var serializationObject = {};
  19018. serializationObject.name = material.name;
  19019. serializationObject.id = material.id;
  19020. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19021. serializationObject.materials = [];
  19022. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19023. var subMat = material.subMaterials[matIndex];
  19024. if (subMat) {
  19025. serializationObject.materials.push(subMat.id);
  19026. }
  19027. else {
  19028. serializationObject.materials.push(null);
  19029. }
  19030. }
  19031. return serializationObject;
  19032. };
  19033. var serializeMaterial = function (material) {
  19034. var serializationObject = {};
  19035. serializationObject.name = material.name;
  19036. serializationObject.ambient = material.ambientColor.asArray();
  19037. serializationObject.diffuse = material.diffuseColor.asArray();
  19038. serializationObject.specular = material.specularColor.asArray();
  19039. serializationObject.specularPower = material.specularPower;
  19040. serializationObject.emissive = material.emissiveColor.asArray();
  19041. serializationObject.alpha = material.alpha;
  19042. serializationObject.id = material.id;
  19043. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19044. serializationObject.backFaceCulling = material.backFaceCulling;
  19045. if (material.diffuseTexture) {
  19046. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19047. }
  19048. if (material.diffuseFresnelParameters) {
  19049. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19050. }
  19051. if (material.ambientTexture) {
  19052. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19053. }
  19054. if (material.opacityTexture) {
  19055. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19056. }
  19057. if (material.opacityFresnelParameters) {
  19058. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19059. }
  19060. if (material.reflectionTexture) {
  19061. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19062. }
  19063. if (material.reflectionFresnelParameters) {
  19064. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19065. }
  19066. if (material.emissiveTexture) {
  19067. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19068. }
  19069. if (material.emissiveFresnelParameters) {
  19070. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19071. }
  19072. if (material.specularTexture) {
  19073. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19074. }
  19075. if (material.bumpTexture) {
  19076. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19077. }
  19078. return serializationObject;
  19079. };
  19080. var serializeTexture = function (texture) {
  19081. var serializationObject = {};
  19082. if (!texture.name) {
  19083. return null;
  19084. }
  19085. if (texture instanceof BABYLON.CubeTexture) {
  19086. serializationObject.name = texture.name;
  19087. serializationObject.hasAlpha = texture.hasAlpha;
  19088. serializationObject.level = texture.level;
  19089. serializationObject.coordinatesMode = texture.coordinatesMode;
  19090. return serializationObject;
  19091. }
  19092. if (texture instanceof BABYLON.MirrorTexture) {
  19093. var mirrorTexture = texture;
  19094. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19095. serializationObject.renderList = [];
  19096. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19097. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19098. }
  19099. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19100. }
  19101. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19102. var renderTargetTexture = texture;
  19103. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19104. serializationObject.renderList = [];
  19105. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19106. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19107. }
  19108. }
  19109. var regularTexture = texture;
  19110. serializationObject.name = texture.name;
  19111. serializationObject.hasAlpha = texture.hasAlpha;
  19112. serializationObject.level = texture.level;
  19113. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19114. serializationObject.coordinatesMode = texture.coordinatesMode;
  19115. serializationObject.uOffset = regularTexture.uOffset;
  19116. serializationObject.vOffset = regularTexture.vOffset;
  19117. serializationObject.uScale = regularTexture.uScale;
  19118. serializationObject.vScale = regularTexture.vScale;
  19119. serializationObject.uAng = regularTexture.uAng;
  19120. serializationObject.vAng = regularTexture.vAng;
  19121. serializationObject.wAng = regularTexture.wAng;
  19122. serializationObject.wrapU = texture.wrapU;
  19123. serializationObject.wrapV = texture.wrapV;
  19124. // Animations
  19125. appendAnimations(texture, serializationObject);
  19126. return serializationObject;
  19127. };
  19128. var serializeSkeleton = function (skeleton) {
  19129. var serializationObject = {};
  19130. serializationObject.name = skeleton.name;
  19131. serializationObject.id = skeleton.id;
  19132. serializationObject.bones = [];
  19133. for (var index = 0; index < skeleton.bones.length; index++) {
  19134. var bone = skeleton.bones[index];
  19135. var serializedBone = {
  19136. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19137. name: bone.name,
  19138. matrix: bone.getLocalMatrix().toArray()
  19139. };
  19140. serializationObject.bones.push(serializedBone);
  19141. if (bone.animations && bone.animations.length > 0) {
  19142. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19143. }
  19144. }
  19145. return serializationObject;
  19146. };
  19147. var serializeParticleSystem = function (particleSystem) {
  19148. var serializationObject = {};
  19149. serializationObject.emitterId = particleSystem.emitter.id;
  19150. serializationObject.capacity = particleSystem.getCapacity();
  19151. if (particleSystem.particleTexture) {
  19152. serializationObject.textureName = particleSystem.particleTexture.name;
  19153. }
  19154. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19155. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19156. serializationObject.minSize = particleSystem.minSize;
  19157. serializationObject.maxSize = particleSystem.maxSize;
  19158. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19159. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19160. serializationObject.emitRate = particleSystem.emitRate;
  19161. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19162. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19163. serializationObject.gravity = particleSystem.gravity.asArray();
  19164. serializationObject.direction1 = particleSystem.direction1.asArray();
  19165. serializationObject.direction2 = particleSystem.direction2.asArray();
  19166. serializationObject.color1 = particleSystem.color1.asArray();
  19167. serializationObject.color2 = particleSystem.color2.asArray();
  19168. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19169. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19170. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19171. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19172. serializationObject.blendMode = particleSystem.blendMode;
  19173. return serializationObject;
  19174. };
  19175. var serializeLensFlareSystem = function (lensFlareSystem) {
  19176. var serializationObject = {};
  19177. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19178. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19179. serializationObject.flares = [];
  19180. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19181. var flare = lensFlareSystem.lensFlares[index];
  19182. serializationObject.flares.push({
  19183. size: flare.size,
  19184. position: flare.position,
  19185. color: flare.color.asArray(),
  19186. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19187. });
  19188. }
  19189. return serializationObject;
  19190. };
  19191. var serializeShadowGenerator = function (light) {
  19192. var serializationObject = {};
  19193. var shadowGenerator = light.getShadowGenerator();
  19194. serializationObject.lightId = light.id;
  19195. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19196. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19197. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19198. serializationObject.renderList = [];
  19199. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19200. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19201. serializationObject.renderList.push(mesh.id);
  19202. }
  19203. return serializationObject;
  19204. };
  19205. var serializedGeometries = [];
  19206. var serializeGeometry = function (geometry, serializationGeometries) {
  19207. if (serializedGeometries[geometry.id]) {
  19208. return;
  19209. }
  19210. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19211. serializationGeometries.boxes.push(serializeBox(geometry));
  19212. }
  19213. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19214. serializationGeometries.spheres.push(serializeSphere(geometry));
  19215. }
  19216. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19217. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19218. }
  19219. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19220. serializationGeometries.toruses.push(serializeTorus(geometry));
  19221. }
  19222. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19223. serializationGeometries.grounds.push(serializeGround(geometry));
  19224. }
  19225. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19226. serializationGeometries.planes.push(serializePlane(geometry));
  19227. }
  19228. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19229. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19230. }
  19231. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19232. throw new Error("Unknow primitive type");
  19233. }
  19234. else {
  19235. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19236. }
  19237. serializedGeometries[geometry.id] = true;
  19238. };
  19239. var serializeGeometryBase = function (geometry) {
  19240. var serializationObject = {};
  19241. serializationObject.id = geometry.id;
  19242. if (BABYLON.Tags.HasTags(geometry)) {
  19243. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19244. }
  19245. return serializationObject;
  19246. };
  19247. var serializeVertexData = function (vertexData) {
  19248. var serializationObject = serializeGeometryBase(vertexData);
  19249. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19250. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19251. }
  19252. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19253. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19254. }
  19255. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19256. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19257. }
  19258. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19259. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19260. }
  19261. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19262. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19263. }
  19264. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19265. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19266. serializationObject.matricesIndices._isExpanded = true;
  19267. }
  19268. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19269. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19270. }
  19271. serializationObject.indices = vertexData.getIndices();
  19272. return serializationObject;
  19273. };
  19274. var serializePrimitive = function (primitive) {
  19275. var serializationObject = serializeGeometryBase(primitive);
  19276. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19277. return serializationObject;
  19278. };
  19279. var serializeBox = function (box) {
  19280. var serializationObject = serializePrimitive(box);
  19281. serializationObject.size = box.size;
  19282. return serializationObject;
  19283. };
  19284. var serializeSphere = function (sphere) {
  19285. var serializationObject = serializePrimitive(sphere);
  19286. serializationObject.segments = sphere.segments;
  19287. serializationObject.diameter = sphere.diameter;
  19288. return serializationObject;
  19289. };
  19290. var serializeCylinder = function (cylinder) {
  19291. var serializationObject = serializePrimitive(cylinder);
  19292. serializationObject.height = cylinder.height;
  19293. serializationObject.diameterTop = cylinder.diameterTop;
  19294. serializationObject.diameterBottom = cylinder.diameterBottom;
  19295. serializationObject.tessellation = cylinder.tessellation;
  19296. return serializationObject;
  19297. };
  19298. var serializeTorus = function (torus) {
  19299. var serializationObject = serializePrimitive(torus);
  19300. serializationObject.diameter = torus.diameter;
  19301. serializationObject.thickness = torus.thickness;
  19302. serializationObject.tessellation = torus.tessellation;
  19303. return serializationObject;
  19304. };
  19305. var serializeGround = function (ground) {
  19306. var serializationObject = serializePrimitive(ground);
  19307. serializationObject.width = ground.width;
  19308. serializationObject.height = ground.height;
  19309. serializationObject.subdivisions = ground.subdivisions;
  19310. return serializationObject;
  19311. };
  19312. var serializePlane = function (plane) {
  19313. var serializationObject = serializePrimitive(plane);
  19314. serializationObject.size = plane.size;
  19315. return serializationObject;
  19316. };
  19317. var serializeTorusKnot = function (torusKnot) {
  19318. var serializationObject = serializePrimitive(torusKnot);
  19319. serializationObject.radius = torusKnot.radius;
  19320. serializationObject.tube = torusKnot.tube;
  19321. serializationObject.radialSegments = torusKnot.radialSegments;
  19322. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19323. serializationObject.p = torusKnot.p;
  19324. serializationObject.q = torusKnot.q;
  19325. return serializationObject;
  19326. };
  19327. var serializeMesh = function (mesh, serializationScene) {
  19328. var serializationObject = {};
  19329. serializationObject.name = mesh.name;
  19330. serializationObject.id = mesh.id;
  19331. if (BABYLON.Tags.HasTags(mesh)) {
  19332. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19333. }
  19334. serializationObject.position = mesh.position.asArray();
  19335. if (mesh.rotationQuaternion) {
  19336. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19337. }
  19338. else if (mesh.rotation) {
  19339. serializationObject.rotation = mesh.rotation.asArray();
  19340. }
  19341. serializationObject.scaling = mesh.scaling.asArray();
  19342. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19343. serializationObject.isEnabled = mesh.isEnabled();
  19344. serializationObject.isVisible = mesh.isVisible;
  19345. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19346. serializationObject.pickable = mesh.isPickable;
  19347. serializationObject.receiveShadows = mesh.receiveShadows;
  19348. serializationObject.billboardMode = mesh.billboardMode;
  19349. serializationObject.visibility = mesh.visibility;
  19350. serializationObject.checkCollisions = mesh.checkCollisions;
  19351. // Parent
  19352. if (mesh.parent) {
  19353. serializationObject.parentId = mesh.parent.id;
  19354. }
  19355. // Geometry
  19356. var geometry = mesh._geometry;
  19357. if (geometry) {
  19358. var geometryId = geometry.id;
  19359. serializationObject.geometryId = geometryId;
  19360. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19361. // 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
  19362. serializeGeometry(geometry, serializationScene.geometries);
  19363. }
  19364. // SubMeshes
  19365. serializationObject.subMeshes = [];
  19366. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19367. var subMesh = mesh.subMeshes[subIndex];
  19368. serializationObject.subMeshes.push({
  19369. materialIndex: subMesh.materialIndex,
  19370. verticesStart: subMesh.verticesStart,
  19371. verticesCount: subMesh.verticesCount,
  19372. indexStart: subMesh.indexStart,
  19373. indexCount: subMesh.indexCount
  19374. });
  19375. }
  19376. }
  19377. // Material
  19378. if (mesh.material) {
  19379. serializationObject.materialId = mesh.material.id;
  19380. }
  19381. else {
  19382. mesh.material = null;
  19383. }
  19384. // Skeleton
  19385. if (mesh.skeleton) {
  19386. serializationObject.skeletonId = mesh.skeleton.id;
  19387. }
  19388. // Physics
  19389. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19390. serializationObject.physicsMass = mesh.getPhysicsMass();
  19391. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19392. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19393. switch (mesh.getPhysicsImpostor()) {
  19394. case BABYLON.PhysicsEngine.BoxImpostor:
  19395. serializationObject.physicsImpostor = 1;
  19396. break;
  19397. case BABYLON.PhysicsEngine.SphereImpostor:
  19398. serializationObject.physicsImpostor = 2;
  19399. break;
  19400. }
  19401. }
  19402. // Instances
  19403. serializationObject.instances = [];
  19404. for (var index = 0; index < mesh.instances.length; index++) {
  19405. var instance = mesh.instances[index];
  19406. var serializationInstance = {
  19407. name: instance.name,
  19408. position: instance.position,
  19409. rotation: instance.rotation,
  19410. rotationQuaternion: instance.rotationQuaternion,
  19411. scaling: instance.scaling
  19412. };
  19413. serializationObject.instances.push(serializationInstance);
  19414. // Animations
  19415. appendAnimations(instance, serializationInstance);
  19416. }
  19417. // Animations
  19418. appendAnimations(mesh, serializationObject);
  19419. // Layer mask
  19420. serializationObject.layerMask = mesh.layerMask;
  19421. return serializationObject;
  19422. };
  19423. var SceneSerializer = (function () {
  19424. function SceneSerializer() {
  19425. }
  19426. SceneSerializer.Serialize = function (scene) {
  19427. var serializationObject = {};
  19428. // Scene
  19429. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19430. serializationObject.autoClear = scene.autoClear;
  19431. serializationObject.clearColor = scene.clearColor.asArray();
  19432. serializationObject.ambientColor = scene.ambientColor.asArray();
  19433. serializationObject.gravity = scene.gravity.asArray();
  19434. // Fog
  19435. if (scene.fogMode && scene.fogMode !== 0) {
  19436. serializationObject.fogMode = scene.fogMode;
  19437. serializationObject.fogColor = scene.fogColor.asArray();
  19438. serializationObject.fogStart = scene.fogStart;
  19439. serializationObject.fogEnd = scene.fogEnd;
  19440. serializationObject.fogDensity = scene.fogDensity;
  19441. }
  19442. // Lights
  19443. serializationObject.lights = [];
  19444. for (var index = 0; index < scene.lights.length; index++) {
  19445. var light = scene.lights[index];
  19446. serializationObject.lights.push(serializeLight(light));
  19447. }
  19448. // Cameras
  19449. serializationObject.cameras = [];
  19450. for (index = 0; index < scene.cameras.length; index++) {
  19451. var camera = scene.cameras[index];
  19452. serializationObject.cameras.push(serializeCamera(camera));
  19453. }
  19454. if (scene.activeCamera) {
  19455. serializationObject.activeCameraID = scene.activeCamera.id;
  19456. }
  19457. // Materials
  19458. serializationObject.materials = [];
  19459. serializationObject.multiMaterials = [];
  19460. for (index = 0; index < scene.materials.length; index++) {
  19461. var material = scene.materials[index];
  19462. if (material instanceof BABYLON.StandardMaterial) {
  19463. serializationObject.materials.push(serializeMaterial(material));
  19464. }
  19465. else if (material instanceof BABYLON.MultiMaterial) {
  19466. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19467. }
  19468. }
  19469. // Skeletons
  19470. serializationObject.skeletons = [];
  19471. for (index = 0; index < scene.skeletons.length; index++) {
  19472. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19473. }
  19474. // Geometries
  19475. serializationObject.geometries = {};
  19476. serializationObject.geometries.boxes = [];
  19477. serializationObject.geometries.spheres = [];
  19478. serializationObject.geometries.cylinders = [];
  19479. serializationObject.geometries.toruses = [];
  19480. serializationObject.geometries.grounds = [];
  19481. serializationObject.geometries.planes = [];
  19482. serializationObject.geometries.torusKnots = [];
  19483. serializationObject.geometries.vertexData = [];
  19484. serializedGeometries = [];
  19485. var geometries = scene.getGeometries();
  19486. for (index = 0; index < geometries.length; index++) {
  19487. var geometry = geometries[index];
  19488. if (geometry.isReady()) {
  19489. serializeGeometry(geometry, serializationObject.geometries);
  19490. }
  19491. }
  19492. // Meshes
  19493. serializationObject.meshes = [];
  19494. for (index = 0; index < scene.meshes.length; index++) {
  19495. var abstractMesh = scene.meshes[index];
  19496. if (abstractMesh instanceof BABYLON.Mesh) {
  19497. var mesh = abstractMesh;
  19498. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19499. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19500. }
  19501. }
  19502. }
  19503. // Particles Systems
  19504. serializationObject.particleSystems = [];
  19505. for (index = 0; index < scene.particleSystems.length; index++) {
  19506. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19507. }
  19508. // Lens flares
  19509. serializationObject.lensFlareSystems = [];
  19510. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19511. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19512. }
  19513. // Shadows
  19514. serializationObject.shadowGenerators = [];
  19515. for (index = 0; index < scene.lights.length; index++) {
  19516. light = scene.lights[index];
  19517. if (light.getShadowGenerator()) {
  19518. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19519. }
  19520. }
  19521. return serializationObject;
  19522. };
  19523. return SceneSerializer;
  19524. })();
  19525. BABYLON.SceneSerializer = SceneSerializer;
  19526. })(BABYLON || (BABYLON = {}));
  19527. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19528. (function (BABYLON) {
  19529. var SceneLoader = (function () {
  19530. function SceneLoader() {
  19531. }
  19532. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19533. get: function () {
  19534. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19535. },
  19536. set: function (value) {
  19537. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19543. get: function () {
  19544. return SceneLoader._ShowLoadingScreen;
  19545. },
  19546. set: function (value) {
  19547. SceneLoader._ShowLoadingScreen = value;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19553. var dotPosition = sceneFilename.lastIndexOf(".");
  19554. var queryStringPosition = sceneFilename.indexOf("?");
  19555. if (queryStringPosition === -1) {
  19556. queryStringPosition = sceneFilename.length;
  19557. }
  19558. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19559. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19560. var plugin = this._registeredPlugins[index];
  19561. if (plugin.extensions.indexOf(extension) !== -1) {
  19562. return plugin;
  19563. }
  19564. }
  19565. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19566. };
  19567. // Public functions
  19568. SceneLoader.RegisterPlugin = function (plugin) {
  19569. plugin.extensions = plugin.extensions.toLowerCase();
  19570. SceneLoader._registeredPlugins.push(plugin);
  19571. };
  19572. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19573. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19574. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19575. return;
  19576. }
  19577. var manifestChecked = function (success) {
  19578. scene.database = database;
  19579. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19580. var importMeshFromData = function (data) {
  19581. var meshes = [];
  19582. var particleSystems = [];
  19583. var skeletons = [];
  19584. try {
  19585. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19586. if (onerror) {
  19587. onerror(scene, 'unable to load the scene');
  19588. }
  19589. return;
  19590. }
  19591. }
  19592. catch (e) {
  19593. if (onerror) {
  19594. onerror(scene, e);
  19595. }
  19596. return;
  19597. }
  19598. if (onsuccess) {
  19599. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19600. onsuccess(meshes, particleSystems, skeletons);
  19601. }
  19602. };
  19603. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19604. // Direct load
  19605. importMeshFromData(sceneFilename.substr(5));
  19606. return;
  19607. }
  19608. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19609. importMeshFromData(data);
  19610. }, progressCallBack, database);
  19611. };
  19612. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19613. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19614. };
  19615. /**
  19616. * Load a scene
  19617. * @param rootUrl a string that defines the root url for scene and resources
  19618. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19619. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19620. */
  19621. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19622. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19623. };
  19624. /**
  19625. * Append a scene
  19626. * @param rootUrl a string that defines the root url for scene and resources
  19627. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19628. * @param scene is the instance of BABYLON.Scene to append to
  19629. */
  19630. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19631. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19632. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19633. return;
  19634. }
  19635. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19636. var database;
  19637. if (SceneLoader.ShowLoadingScreen) {
  19638. scene.getEngine().displayLoadingUI();
  19639. }
  19640. var loadSceneFromData = function (data) {
  19641. scene.database = database;
  19642. if (!plugin.load(scene, data, rootUrl)) {
  19643. if (onerror) {
  19644. onerror(scene);
  19645. }
  19646. scene.getEngine().hideLoadingUI();
  19647. return;
  19648. }
  19649. if (onsuccess) {
  19650. onsuccess(scene);
  19651. }
  19652. if (SceneLoader.ShowLoadingScreen) {
  19653. scene.executeWhenReady(function () {
  19654. scene.getEngine().hideLoadingUI();
  19655. });
  19656. }
  19657. };
  19658. var manifestChecked = function (success) {
  19659. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19660. };
  19661. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19662. // Direct load
  19663. loadSceneFromData(sceneFilename.substr(5));
  19664. return;
  19665. }
  19666. if (rootUrl.indexOf("file:") === -1) {
  19667. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19668. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19669. }
  19670. else {
  19671. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19672. }
  19673. };
  19674. // Flags
  19675. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19676. SceneLoader._ShowLoadingScreen = true;
  19677. // Members
  19678. SceneLoader._registeredPlugins = new Array();
  19679. return SceneLoader;
  19680. })();
  19681. BABYLON.SceneLoader = SceneLoader;
  19682. ;
  19683. })(BABYLON || (BABYLON = {}));
  19684. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19685. (function (BABYLON) {
  19686. var Internals;
  19687. (function (Internals) {
  19688. var checkColors4 = function (colors, count) {
  19689. // Check if color3 was used
  19690. if (colors.length === count * 3) {
  19691. var colors4 = [];
  19692. for (var index = 0; index < colors.length; index += 3) {
  19693. var newIndex = (index / 3) * 4;
  19694. colors4[newIndex] = colors[index];
  19695. colors4[newIndex + 1] = colors[index + 1];
  19696. colors4[newIndex + 2] = colors[index + 2];
  19697. colors4[newIndex + 3] = 1.0;
  19698. }
  19699. return colors4;
  19700. }
  19701. return colors;
  19702. };
  19703. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19704. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19705. texture.name = parsedTexture.name;
  19706. texture.hasAlpha = parsedTexture.hasAlpha;
  19707. texture.level = parsedTexture.level;
  19708. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19709. return texture;
  19710. };
  19711. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19712. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19713. return null;
  19714. }
  19715. if (parsedTexture.isCube) {
  19716. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19717. }
  19718. var texture;
  19719. if (parsedTexture.mirrorPlane) {
  19720. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19721. texture._waitingRenderList = parsedTexture.renderList;
  19722. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19723. }
  19724. else if (parsedTexture.isRenderTarget) {
  19725. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19726. texture._waitingRenderList = parsedTexture.renderList;
  19727. }
  19728. else {
  19729. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19730. }
  19731. texture.name = parsedTexture.name;
  19732. texture.hasAlpha = parsedTexture.hasAlpha;
  19733. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19734. texture.level = parsedTexture.level;
  19735. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19736. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19737. texture.uOffset = parsedTexture.uOffset;
  19738. texture.vOffset = parsedTexture.vOffset;
  19739. texture.uScale = parsedTexture.uScale;
  19740. texture.vScale = parsedTexture.vScale;
  19741. texture.uAng = parsedTexture.uAng;
  19742. texture.vAng = parsedTexture.vAng;
  19743. texture.wAng = parsedTexture.wAng;
  19744. texture.wrapU = parsedTexture.wrapU;
  19745. texture.wrapV = parsedTexture.wrapV;
  19746. // Animations
  19747. if (parsedTexture.animations) {
  19748. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19749. var parsedAnimation = parsedTexture.animations[animationIndex];
  19750. texture.animations.push(parseAnimation(parsedAnimation));
  19751. }
  19752. }
  19753. return texture;
  19754. };
  19755. var parseSkeleton = function (parsedSkeleton, scene) {
  19756. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19757. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19758. var parsedBone = parsedSkeleton.bones[index];
  19759. var parentBone = null;
  19760. if (parsedBone.parentBoneIndex > -1) {
  19761. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19762. }
  19763. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19764. if (parsedBone.animation) {
  19765. bone.animations.push(parseAnimation(parsedBone.animation));
  19766. }
  19767. }
  19768. return skeleton;
  19769. };
  19770. var parseFresnelParameters = function (parsedFresnelParameters) {
  19771. var fresnelParameters = new BABYLON.FresnelParameters();
  19772. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19773. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19774. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19775. fresnelParameters.bias = parsedFresnelParameters.bias;
  19776. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19777. return fresnelParameters;
  19778. };
  19779. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19780. var material;
  19781. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19782. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19783. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19784. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19785. material.specularPower = parsedMaterial.specularPower;
  19786. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19787. material.alpha = parsedMaterial.alpha;
  19788. material.id = parsedMaterial.id;
  19789. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19790. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19791. material.wireframe = parsedMaterial.wireframe;
  19792. if (parsedMaterial.diffuseTexture) {
  19793. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19794. }
  19795. if (parsedMaterial.diffuseFresnelParameters) {
  19796. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19797. }
  19798. if (parsedMaterial.ambientTexture) {
  19799. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19800. }
  19801. if (parsedMaterial.opacityTexture) {
  19802. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19803. }
  19804. if (parsedMaterial.opacityFresnelParameters) {
  19805. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19806. }
  19807. if (parsedMaterial.reflectionTexture) {
  19808. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19809. }
  19810. if (parsedMaterial.reflectionFresnelParameters) {
  19811. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19812. }
  19813. if (parsedMaterial.emissiveTexture) {
  19814. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19815. }
  19816. if (parsedMaterial.emissiveFresnelParameters) {
  19817. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19818. }
  19819. if (parsedMaterial.specularTexture) {
  19820. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19821. }
  19822. if (parsedMaterial.bumpTexture) {
  19823. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19824. }
  19825. return material;
  19826. };
  19827. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19828. for (var index = 0; index < parsedData.materials.length; index++) {
  19829. var parsedMaterial = parsedData.materials[index];
  19830. if (parsedMaterial.id === id) {
  19831. return parseMaterial(parsedMaterial, scene, rootUrl);
  19832. }
  19833. }
  19834. return null;
  19835. };
  19836. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19837. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19838. multiMaterial.id = parsedMultiMaterial.id;
  19839. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19840. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19841. var subMatId = parsedMultiMaterial.materials[matIndex];
  19842. if (subMatId) {
  19843. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19844. }
  19845. else {
  19846. multiMaterial.subMaterials.push(null);
  19847. }
  19848. }
  19849. return multiMaterial;
  19850. };
  19851. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19852. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19853. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19854. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19855. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19856. var parsedFlare = parsedLensFlareSystem.flares[index];
  19857. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19858. }
  19859. return lensFlareSystem;
  19860. };
  19861. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19862. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19863. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19864. if (parsedParticleSystem.textureName) {
  19865. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19866. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19867. }
  19868. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19869. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19870. particleSystem.minSize = parsedParticleSystem.minSize;
  19871. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19872. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19873. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19874. particleSystem.emitter = emitter;
  19875. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19876. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19877. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19878. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19879. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19880. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19881. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19882. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19883. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19884. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19885. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19886. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19887. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19888. particleSystem.start();
  19889. return particleSystem;
  19890. };
  19891. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19892. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19893. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19894. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19895. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19896. shadowGenerator.getShadowMap().renderList.push(mesh);
  19897. }
  19898. if (parsedShadowGenerator.usePoissonSampling) {
  19899. shadowGenerator.usePoissonSampling = true;
  19900. }
  19901. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19902. shadowGenerator.useVarianceShadowMap = true;
  19903. }
  19904. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19905. shadowGenerator.useBlurVarianceShadowMap = true;
  19906. if (parsedShadowGenerator.blurScale) {
  19907. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19908. }
  19909. if (parsedShadowGenerator.blurBoxOffset) {
  19910. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19911. }
  19912. }
  19913. if (parsedShadowGenerator.bias !== undefined) {
  19914. shadowGenerator.bias = parsedShadowGenerator.bias;
  19915. }
  19916. return shadowGenerator;
  19917. };
  19918. var parseAnimation = function (parsedAnimation) {
  19919. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19920. var dataType = parsedAnimation.dataType;
  19921. var keys = [];
  19922. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19923. var key = parsedAnimation.keys[index];
  19924. var data;
  19925. switch (dataType) {
  19926. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19927. data = key.values[0];
  19928. break;
  19929. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19930. data = BABYLON.Quaternion.FromArray(key.values);
  19931. break;
  19932. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19933. data = BABYLON.Matrix.FromArray(key.values);
  19934. break;
  19935. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19936. default:
  19937. data = BABYLON.Vector3.FromArray(key.values);
  19938. break;
  19939. }
  19940. keys.push({
  19941. frame: key.frame,
  19942. value: data
  19943. });
  19944. }
  19945. animation.setKeys(keys);
  19946. return animation;
  19947. };
  19948. var parseLight = function (parsedLight, scene) {
  19949. var light;
  19950. switch (parsedLight.type) {
  19951. case 0:
  19952. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19953. break;
  19954. case 1:
  19955. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19956. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19957. break;
  19958. case 2:
  19959. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19960. break;
  19961. case 3:
  19962. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19963. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19964. break;
  19965. }
  19966. light.id = parsedLight.id;
  19967. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19968. if (parsedLight.intensity !== undefined) {
  19969. light.intensity = parsedLight.intensity;
  19970. }
  19971. if (parsedLight.range) {
  19972. light.range = parsedLight.range;
  19973. }
  19974. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19975. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19976. if (parsedLight.excludedMeshesIds) {
  19977. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19978. }
  19979. // Parent
  19980. if (parsedLight.parentId) {
  19981. light._waitingParentId = parsedLight.parentId;
  19982. }
  19983. if (parsedLight.includedOnlyMeshesIds) {
  19984. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19985. }
  19986. // Animations
  19987. if (parsedLight.animations) {
  19988. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19989. var parsedAnimation = parsedLight.animations[animationIndex];
  19990. light.animations.push(parseAnimation(parsedAnimation));
  19991. }
  19992. }
  19993. if (parsedLight.autoAnimate) {
  19994. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19995. }
  19996. };
  19997. var parseCamera = function (parsedCamera, scene) {
  19998. var camera;
  19999. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20000. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20001. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20002. var alpha = parsedCamera.alpha;
  20003. var beta = parsedCamera.beta;
  20004. var radius = parsedCamera.radius;
  20005. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20006. var eye_space = parsedCamera.eye_space;
  20007. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  20008. }
  20009. else {
  20010. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20011. }
  20012. }
  20013. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20014. eye_space = parsedCamera.eye_space;
  20015. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  20016. }
  20017. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20018. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20019. }
  20020. else if (parsedCamera.type === "FollowCamera") {
  20021. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20022. camera.heightOffset = parsedCamera.heightOffset;
  20023. camera.radius = parsedCamera.radius;
  20024. camera.rotationOffset = parsedCamera.rotationOffset;
  20025. if (lockedTargetMesh)
  20026. camera.target = lockedTargetMesh;
  20027. }
  20028. else if (parsedCamera.type === "GamepadCamera") {
  20029. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20030. }
  20031. else if (parsedCamera.type === "OculusCamera") {
  20032. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20033. }
  20034. else if (parsedCamera.type === "OculusGamepadCamera") {
  20035. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20036. }
  20037. else if (parsedCamera.type === "TouchCamera") {
  20038. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20039. }
  20040. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20041. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20042. }
  20043. else if (parsedCamera.type === "WebVRCamera") {
  20044. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20045. }
  20046. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20047. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20048. }
  20049. else {
  20050. // Free Camera is the default value
  20051. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20052. }
  20053. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20054. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20055. camera.lockedTarget = lockedTargetMesh;
  20056. }
  20057. camera.id = parsedCamera.id;
  20058. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20059. // Parent
  20060. if (parsedCamera.parentId) {
  20061. camera._waitingParentId = parsedCamera.parentId;
  20062. }
  20063. // Target
  20064. if (parsedCamera.target) {
  20065. if (camera.setTarget) {
  20066. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20067. }
  20068. else {
  20069. //For ArcRotate
  20070. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20071. }
  20072. }
  20073. else {
  20074. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20075. }
  20076. camera.fov = parsedCamera.fov;
  20077. camera.minZ = parsedCamera.minZ;
  20078. camera.maxZ = parsedCamera.maxZ;
  20079. camera.speed = parsedCamera.speed;
  20080. camera.inertia = parsedCamera.inertia;
  20081. camera.checkCollisions = parsedCamera.checkCollisions;
  20082. camera.applyGravity = parsedCamera.applyGravity;
  20083. if (parsedCamera.ellipsoid) {
  20084. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20085. }
  20086. // Animations
  20087. if (parsedCamera.animations) {
  20088. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20089. var parsedAnimation = parsedCamera.animations[animationIndex];
  20090. camera.animations.push(parseAnimation(parsedAnimation));
  20091. }
  20092. }
  20093. if (parsedCamera.autoAnimate) {
  20094. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20095. }
  20096. // Layer Mask
  20097. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20098. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20099. }
  20100. else {
  20101. camera.layerMask = 0xFFFFFFFF;
  20102. }
  20103. return camera;
  20104. };
  20105. var parseGeometry = function (parsedGeometry, scene) {
  20106. var id = parsedGeometry.id;
  20107. return scene.getGeometryByID(id);
  20108. };
  20109. var parseBox = function (parsedBox, scene) {
  20110. if (parseGeometry(parsedBox, scene)) {
  20111. return null; // null since geometry could be something else than a box...
  20112. }
  20113. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20114. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20115. scene.pushGeometry(box, true);
  20116. return box;
  20117. };
  20118. var parseSphere = function (parsedSphere, scene) {
  20119. if (parseGeometry(parsedSphere, scene)) {
  20120. return null; // null since geometry could be something else than a sphere...
  20121. }
  20122. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20123. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20124. scene.pushGeometry(sphere, true);
  20125. return sphere;
  20126. };
  20127. var parseCylinder = function (parsedCylinder, scene) {
  20128. if (parseGeometry(parsedCylinder, scene)) {
  20129. return null; // null since geometry could be something else than a cylinder...
  20130. }
  20131. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20132. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20133. scene.pushGeometry(cylinder, true);
  20134. return cylinder;
  20135. };
  20136. var parseTorus = function (parsedTorus, scene) {
  20137. if (parseGeometry(parsedTorus, scene)) {
  20138. return null; // null since geometry could be something else than a torus...
  20139. }
  20140. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20141. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20142. scene.pushGeometry(torus, true);
  20143. return torus;
  20144. };
  20145. var parseGround = function (parsedGround, scene) {
  20146. if (parseGeometry(parsedGround, scene)) {
  20147. return null; // null since geometry could be something else than a ground...
  20148. }
  20149. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20150. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20151. scene.pushGeometry(ground, true);
  20152. return ground;
  20153. };
  20154. var parsePlane = function (parsedPlane, scene) {
  20155. if (parseGeometry(parsedPlane, scene)) {
  20156. return null; // null since geometry could be something else than a plane...
  20157. }
  20158. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20159. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20160. scene.pushGeometry(plane, true);
  20161. return plane;
  20162. };
  20163. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20164. if (parseGeometry(parsedTorusKnot, scene)) {
  20165. return null; // null since geometry could be something else than a torusKnot...
  20166. }
  20167. 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);
  20168. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20169. scene.pushGeometry(torusKnot, true);
  20170. return torusKnot;
  20171. };
  20172. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20173. if (parseGeometry(parsedVertexData, scene)) {
  20174. return null; // null since geometry could be a primitive
  20175. }
  20176. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20177. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20178. if (parsedVertexData.delayLoadingFile) {
  20179. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20180. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20181. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20182. geometry._delayInfo = [];
  20183. if (parsedVertexData.hasUVs) {
  20184. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20185. }
  20186. if (parsedVertexData.hasUVs2) {
  20187. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20188. }
  20189. if (parsedVertexData.hasColors) {
  20190. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20191. }
  20192. if (parsedVertexData.hasMatricesIndices) {
  20193. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20194. }
  20195. if (parsedVertexData.hasMatricesWeights) {
  20196. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20197. }
  20198. geometry._delayLoadingFunction = importVertexData;
  20199. }
  20200. else {
  20201. importVertexData(parsedVertexData, geometry);
  20202. }
  20203. scene.pushGeometry(geometry, true);
  20204. return geometry;
  20205. };
  20206. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20207. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20208. mesh.id = parsedMesh.id;
  20209. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20210. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20211. if (parsedMesh.rotationQuaternion) {
  20212. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20213. }
  20214. else if (parsedMesh.rotation) {
  20215. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20216. }
  20217. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20218. if (parsedMesh.localMatrix) {
  20219. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20220. }
  20221. else if (parsedMesh.pivotMatrix) {
  20222. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20223. }
  20224. mesh.setEnabled(parsedMesh.isEnabled);
  20225. mesh.isVisible = parsedMesh.isVisible;
  20226. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20227. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20228. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20229. if (parsedMesh.applyFog !== undefined) {
  20230. mesh.applyFog = parsedMesh.applyFog;
  20231. }
  20232. if (parsedMesh.pickable !== undefined) {
  20233. mesh.isPickable = parsedMesh.pickable;
  20234. }
  20235. if (parsedMesh.alphaIndex !== undefined) {
  20236. mesh.alphaIndex = parsedMesh.alphaIndex;
  20237. }
  20238. mesh.receiveShadows = parsedMesh.receiveShadows;
  20239. mesh.billboardMode = parsedMesh.billboardMode;
  20240. if (parsedMesh.visibility !== undefined) {
  20241. mesh.visibility = parsedMesh.visibility;
  20242. }
  20243. mesh.checkCollisions = parsedMesh.checkCollisions;
  20244. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20245. // Parent
  20246. if (parsedMesh.parentId) {
  20247. mesh._waitingParentId = parsedMesh.parentId;
  20248. }
  20249. // Actions
  20250. if (parsedMesh.actions !== undefined) {
  20251. mesh._waitingActions = parsedMesh.actions;
  20252. }
  20253. // Geometry
  20254. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20255. if (parsedMesh.delayLoadingFile) {
  20256. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20257. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20258. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20259. if (parsedMesh._binaryInfo) {
  20260. mesh._binaryInfo = parsedMesh._binaryInfo;
  20261. }
  20262. mesh._delayInfo = [];
  20263. if (parsedMesh.hasUVs) {
  20264. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20265. }
  20266. if (parsedMesh.hasUVs2) {
  20267. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20268. }
  20269. if (parsedMesh.hasColors) {
  20270. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20271. }
  20272. if (parsedMesh.hasMatricesIndices) {
  20273. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20274. }
  20275. if (parsedMesh.hasMatricesWeights) {
  20276. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20277. }
  20278. mesh._delayLoadingFunction = importGeometry;
  20279. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20280. mesh._checkDelayState();
  20281. }
  20282. }
  20283. else {
  20284. importGeometry(parsedMesh, mesh);
  20285. }
  20286. // Material
  20287. if (parsedMesh.materialId) {
  20288. mesh.setMaterialByID(parsedMesh.materialId);
  20289. }
  20290. else {
  20291. mesh.material = null;
  20292. }
  20293. // Skeleton
  20294. if (parsedMesh.skeletonId > -1) {
  20295. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20296. }
  20297. // Physics
  20298. if (parsedMesh.physicsImpostor) {
  20299. if (!scene.isPhysicsEnabled()) {
  20300. scene.enablePhysics();
  20301. }
  20302. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20303. }
  20304. // Animations
  20305. if (parsedMesh.animations) {
  20306. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20307. var parsedAnimation = parsedMesh.animations[animationIndex];
  20308. mesh.animations.push(parseAnimation(parsedAnimation));
  20309. }
  20310. }
  20311. if (parsedMesh.autoAnimate) {
  20312. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20313. }
  20314. // Layer Mask
  20315. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20316. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20317. }
  20318. else {
  20319. mesh.layerMask = 0xFFFFFFFF;
  20320. }
  20321. // Instances
  20322. if (parsedMesh.instances) {
  20323. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20324. var parsedInstance = parsedMesh.instances[index];
  20325. var instance = mesh.createInstance(parsedInstance.name);
  20326. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20327. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20328. if (parsedInstance.rotationQuaternion) {
  20329. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20330. }
  20331. else if (parsedInstance.rotation) {
  20332. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20333. }
  20334. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20335. instance.checkCollisions = mesh.checkCollisions;
  20336. if (parsedMesh.animations) {
  20337. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20338. parsedAnimation = parsedMesh.animations[animationIndex];
  20339. instance.animations.push(parseAnimation(parsedAnimation));
  20340. }
  20341. }
  20342. }
  20343. }
  20344. return mesh;
  20345. };
  20346. var parseActions = function (parsedActions, object, scene) {
  20347. var actionManager = new BABYLON.ActionManager(scene);
  20348. if (object === null)
  20349. scene.actionManager = actionManager;
  20350. else
  20351. object.actionManager = actionManager;
  20352. // instanciate a new object
  20353. var instanciate = function (name, params) {
  20354. var newInstance = Object.create(BABYLON[name].prototype);
  20355. newInstance.constructor.apply(newInstance, params);
  20356. return newInstance;
  20357. };
  20358. var parseParameter = function (name, value, target, propertyPath) {
  20359. if (propertyPath === null) {
  20360. // String, boolean or float
  20361. var floatValue = parseFloat(value);
  20362. if (value === "true" || value === "false")
  20363. return value === "true";
  20364. else
  20365. return isNaN(floatValue) ? value : floatValue;
  20366. }
  20367. var effectiveTarget = propertyPath.split(".");
  20368. var values = value.split(",");
  20369. for (var i = 0; i < effectiveTarget.length; i++) {
  20370. target = target[effectiveTarget[i]];
  20371. }
  20372. // Return appropriate value with its type
  20373. if (typeof (target) === "boolean")
  20374. return values[0] === "true";
  20375. if (typeof (target) === "string")
  20376. return values[0];
  20377. // Parameters with multiple values such as Vector3 etc.
  20378. var split = new Array();
  20379. for (var i = 0; i < values.length; i++)
  20380. split.push(parseFloat(values[i]));
  20381. if (target instanceof BABYLON.Vector3)
  20382. return BABYLON.Vector3.FromArray(split);
  20383. if (target instanceof BABYLON.Vector4)
  20384. return BABYLON.Vector4.FromArray(split);
  20385. if (target instanceof BABYLON.Color3)
  20386. return BABYLON.Color3.FromArray(split);
  20387. if (target instanceof BABYLON.Color4)
  20388. return BABYLON.Color4.FromArray(split);
  20389. return parseFloat(values[0]);
  20390. };
  20391. // traverse graph per trigger
  20392. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20393. if (combineArray === void 0) { combineArray = null; }
  20394. if (parsedAction.detached)
  20395. return;
  20396. var parameters = new Array();
  20397. var target = null;
  20398. var propertyPath = null;
  20399. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20400. // Parameters
  20401. if (parsedAction.type === 2)
  20402. parameters.push(actionManager);
  20403. else
  20404. parameters.push(trigger);
  20405. if (combine) {
  20406. var actions = new Array();
  20407. for (var j = 0; j < parsedAction.combine.length; j++) {
  20408. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20409. }
  20410. parameters.push(actions);
  20411. }
  20412. else {
  20413. for (var i = 0; i < parsedAction.properties.length; i++) {
  20414. var value = parsedAction.properties[i].value;
  20415. var name = parsedAction.properties[i].name;
  20416. var targetType = parsedAction.properties[i].targetType;
  20417. if (name === "target")
  20418. if (targetType != null && targetType === "SceneProperties")
  20419. value = target = scene;
  20420. else
  20421. value = target = scene.getNodeByName(value);
  20422. else if (name === "parent")
  20423. value = scene.getNodeByName(value);
  20424. else if (name === "sound")
  20425. value = scene.getSoundByName(value);
  20426. else if (name !== "propertyPath") {
  20427. if (parsedAction.type === 2 && name === "operator")
  20428. value = BABYLON.ValueCondition[value];
  20429. else
  20430. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20431. }
  20432. else {
  20433. propertyPath = value;
  20434. }
  20435. parameters.push(value);
  20436. }
  20437. }
  20438. if (combineArray === null) {
  20439. parameters.push(condition);
  20440. }
  20441. else {
  20442. parameters.push(null);
  20443. }
  20444. // If interpolate value action
  20445. if (parsedAction.name === "InterpolateValueAction") {
  20446. var param = parameters[parameters.length - 2];
  20447. parameters[parameters.length - 1] = param;
  20448. parameters[parameters.length - 2] = condition;
  20449. }
  20450. // Action or condition(s) and not CombineAction
  20451. var newAction = instanciate(parsedAction.name, parameters);
  20452. if (combineArray === null) {
  20453. if (newAction instanceof BABYLON.Condition) {
  20454. condition = newAction;
  20455. newAction = action;
  20456. }
  20457. else {
  20458. condition = null;
  20459. if (action)
  20460. action.then(newAction);
  20461. else
  20462. actionManager.registerAction(newAction);
  20463. }
  20464. }
  20465. else {
  20466. combineArray.push(newAction);
  20467. }
  20468. for (var i = 0; i < parsedAction.children.length; i++)
  20469. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20470. };
  20471. for (var i = 0; i < parsedActions.children.length; i++) {
  20472. var triggerParams;
  20473. var trigger = parsedActions.children[i];
  20474. if (trigger.properties.length > 0) {
  20475. var param = trigger.properties[0].value;
  20476. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20477. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20478. }
  20479. else
  20480. triggerParams = BABYLON.ActionManager[trigger.name];
  20481. for (var j = 0; j < trigger.children.length; j++) {
  20482. if (!trigger.detached)
  20483. traverse(trigger.children[j], triggerParams, null, null);
  20484. }
  20485. }
  20486. };
  20487. var parseSound = function (parsedSound, scene, rootUrl) {
  20488. var soundName = parsedSound.name;
  20489. var soundUrl = rootUrl + soundName;
  20490. var options = {
  20491. autoplay: parsedSound.autoplay,
  20492. loop: parsedSound.loop,
  20493. volume: parsedSound.volume,
  20494. spatialSound: parsedSound.spatialSound,
  20495. maxDistance: parsedSound.maxDistance,
  20496. rolloffFactor: parsedSound.rolloffFactor,
  20497. refDistance: parsedSound.refDistance,
  20498. distanceModel: parsedSound.distanceModel,
  20499. playbackRate: parsedSound.playbackRate
  20500. };
  20501. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20502. scene._removePendingData(newSound);
  20503. }, options);
  20504. scene._addPendingData(newSound);
  20505. if (parsedSound.position) {
  20506. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20507. newSound.setPosition(soundPosition);
  20508. }
  20509. if (parsedSound.isDirectional) {
  20510. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20511. if (parsedSound.localDirectionToMesh) {
  20512. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20513. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20514. }
  20515. }
  20516. if (parsedSound.connectedMeshId) {
  20517. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20518. if (connectedMesh) {
  20519. newSound.attachToMesh(connectedMesh);
  20520. }
  20521. }
  20522. };
  20523. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20524. names = (names instanceof Array) ? names : [names];
  20525. for (var i in names) {
  20526. if (mesh.name === names[i]) {
  20527. hierarchyIds.push(mesh.id);
  20528. return true;
  20529. }
  20530. }
  20531. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20532. hierarchyIds.push(mesh.id);
  20533. return true;
  20534. }
  20535. return false;
  20536. };
  20537. var importVertexData = function (parsedVertexData, geometry) {
  20538. var vertexData = new BABYLON.VertexData();
  20539. // positions
  20540. var positions = parsedVertexData.positions;
  20541. if (positions) {
  20542. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20543. }
  20544. // normals
  20545. var normals = parsedVertexData.normals;
  20546. if (normals) {
  20547. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20548. }
  20549. // uvs
  20550. var uvs = parsedVertexData.uvs;
  20551. if (uvs) {
  20552. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20553. }
  20554. // uv2s
  20555. var uv2s = parsedVertexData.uv2s;
  20556. if (uv2s) {
  20557. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20558. }
  20559. // colors
  20560. var colors = parsedVertexData.colors;
  20561. if (colors) {
  20562. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20563. }
  20564. // matricesIndices
  20565. var matricesIndices = parsedVertexData.matricesIndices;
  20566. if (matricesIndices) {
  20567. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20568. }
  20569. // matricesWeights
  20570. var matricesWeights = parsedVertexData.matricesWeights;
  20571. if (matricesWeights) {
  20572. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20573. }
  20574. // indices
  20575. var indices = parsedVertexData.indices;
  20576. if (indices) {
  20577. vertexData.indices = indices;
  20578. }
  20579. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20580. };
  20581. var importGeometry = function (parsedGeometry, mesh) {
  20582. var scene = mesh.getScene();
  20583. // Geometry
  20584. var geometryId = parsedGeometry.geometryId;
  20585. if (geometryId) {
  20586. var geometry = scene.getGeometryByID(geometryId);
  20587. if (geometry) {
  20588. geometry.applyToMesh(mesh);
  20589. }
  20590. }
  20591. else if (parsedGeometry instanceof ArrayBuffer) {
  20592. var binaryInfo = mesh._binaryInfo;
  20593. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20594. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20595. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20596. }
  20597. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20598. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20599. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20600. }
  20601. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20602. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20603. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20604. }
  20605. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20606. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20607. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20608. }
  20609. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20610. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20611. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20612. }
  20613. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20614. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20615. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20616. }
  20617. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20618. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20619. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20620. }
  20621. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20622. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20623. mesh.setIndices(indicesData);
  20624. }
  20625. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20626. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20627. mesh.subMeshes = [];
  20628. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20629. var materialIndex = subMeshesData[(i * 5) + 0];
  20630. var verticesStart = subMeshesData[(i * 5) + 1];
  20631. var verticesCount = subMeshesData[(i * 5) + 2];
  20632. var indexStart = subMeshesData[(i * 5) + 3];
  20633. var indexCount = subMeshesData[(i * 5) + 4];
  20634. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20635. }
  20636. }
  20637. }
  20638. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20639. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20640. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20641. if (parsedGeometry.uvs) {
  20642. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20643. }
  20644. if (parsedGeometry.uvs2) {
  20645. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20646. }
  20647. if (parsedGeometry.colors) {
  20648. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20649. }
  20650. if (parsedGeometry.matricesIndices) {
  20651. if (!parsedGeometry.matricesIndices._isExpanded) {
  20652. var floatIndices = [];
  20653. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20654. var matricesIndex = parsedGeometry.matricesIndices[i];
  20655. floatIndices.push(matricesIndex & 0x000000FF);
  20656. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20657. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20658. floatIndices.push(matricesIndex >> 24);
  20659. }
  20660. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20661. }
  20662. else {
  20663. delete parsedGeometry.matricesIndices._isExpanded;
  20664. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20665. }
  20666. }
  20667. if (parsedGeometry.matricesWeights) {
  20668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20669. }
  20670. mesh.setIndices(parsedGeometry.indices);
  20671. // SubMeshes
  20672. if (parsedGeometry.subMeshes) {
  20673. mesh.subMeshes = [];
  20674. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20675. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20676. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20677. }
  20678. }
  20679. }
  20680. // Flat shading
  20681. if (mesh._shouldGenerateFlatShading) {
  20682. mesh.convertToFlatShadedMesh();
  20683. delete mesh._shouldGenerateFlatShading;
  20684. }
  20685. // Update
  20686. mesh.computeWorldMatrix(true);
  20687. // Octree
  20688. if (scene._selectionOctree) {
  20689. scene._selectionOctree.addMesh(mesh);
  20690. }
  20691. };
  20692. BABYLON.SceneLoader.RegisterPlugin({
  20693. extensions: ".babylon",
  20694. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20695. var parsedData = JSON.parse(data);
  20696. var loadedSkeletonsIds = [];
  20697. var loadedMaterialsIds = [];
  20698. var hierarchyIds = [];
  20699. for (var index = 0; index < parsedData.meshes.length; index++) {
  20700. var parsedMesh = parsedData.meshes[index];
  20701. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20702. if (meshesNames instanceof Array) {
  20703. // Remove found mesh name from list.
  20704. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20705. }
  20706. // Material ?
  20707. if (parsedMesh.materialId) {
  20708. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20709. if (!materialFound) {
  20710. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20711. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20712. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20713. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20714. var subMatId = parsedMultiMaterial.materials[matIndex];
  20715. loadedMaterialsIds.push(subMatId);
  20716. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20717. }
  20718. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20719. parseMultiMaterial(parsedMultiMaterial, scene);
  20720. materialFound = true;
  20721. break;
  20722. }
  20723. }
  20724. }
  20725. if (!materialFound) {
  20726. loadedMaterialsIds.push(parsedMesh.materialId);
  20727. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20728. }
  20729. }
  20730. // Skeleton ?
  20731. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20732. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20733. if (!skeletonAlreadyLoaded) {
  20734. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20735. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20736. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20737. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20738. loadedSkeletonsIds.push(parsedSkeleton.id);
  20739. }
  20740. }
  20741. }
  20742. }
  20743. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20744. meshes.push(mesh);
  20745. }
  20746. }
  20747. for (index = 0; index < scene.meshes.length; index++) {
  20748. var currentMesh = scene.meshes[index];
  20749. if (currentMesh._waitingParentId) {
  20750. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20751. currentMesh._waitingParentId = undefined;
  20752. }
  20753. }
  20754. // Particles
  20755. if (parsedData.particleSystems) {
  20756. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20757. var parsedParticleSystem = parsedData.particleSystems[index];
  20758. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20759. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20760. }
  20761. }
  20762. }
  20763. return true;
  20764. },
  20765. load: function (scene, data, rootUrl) {
  20766. var parsedData = JSON.parse(data);
  20767. // Scene
  20768. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20769. scene.autoClear = parsedData.autoClear;
  20770. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20771. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20772. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20773. // Fog
  20774. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20775. scene.fogMode = parsedData.fogMode;
  20776. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20777. scene.fogStart = parsedData.fogStart;
  20778. scene.fogEnd = parsedData.fogEnd;
  20779. scene.fogDensity = parsedData.fogDensity;
  20780. }
  20781. for (var index = 0; index < parsedData.lights.length; index++) {
  20782. var parsedLight = parsedData.lights[index];
  20783. parseLight(parsedLight, scene);
  20784. }
  20785. // Materials
  20786. if (parsedData.materials) {
  20787. for (index = 0; index < parsedData.materials.length; index++) {
  20788. var parsedMaterial = parsedData.materials[index];
  20789. parseMaterial(parsedMaterial, scene, rootUrl);
  20790. }
  20791. }
  20792. if (parsedData.multiMaterials) {
  20793. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20794. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20795. parseMultiMaterial(parsedMultiMaterial, scene);
  20796. }
  20797. }
  20798. // Skeletons
  20799. if (parsedData.skeletons) {
  20800. for (index = 0; index < parsedData.skeletons.length; index++) {
  20801. var parsedSkeleton = parsedData.skeletons[index];
  20802. parseSkeleton(parsedSkeleton, scene);
  20803. }
  20804. }
  20805. // Geometries
  20806. var geometries = parsedData.geometries;
  20807. if (geometries) {
  20808. // Boxes
  20809. var boxes = geometries.boxes;
  20810. if (boxes) {
  20811. for (index = 0; index < boxes.length; index++) {
  20812. var parsedBox = boxes[index];
  20813. parseBox(parsedBox, scene);
  20814. }
  20815. }
  20816. // Spheres
  20817. var spheres = geometries.spheres;
  20818. if (spheres) {
  20819. for (index = 0; index < spheres.length; index++) {
  20820. var parsedSphere = spheres[index];
  20821. parseSphere(parsedSphere, scene);
  20822. }
  20823. }
  20824. // Cylinders
  20825. var cylinders = geometries.cylinders;
  20826. if (cylinders) {
  20827. for (index = 0; index < cylinders.length; index++) {
  20828. var parsedCylinder = cylinders[index];
  20829. parseCylinder(parsedCylinder, scene);
  20830. }
  20831. }
  20832. // Toruses
  20833. var toruses = geometries.toruses;
  20834. if (toruses) {
  20835. for (index = 0; index < toruses.length; index++) {
  20836. var parsedTorus = toruses[index];
  20837. parseTorus(parsedTorus, scene);
  20838. }
  20839. }
  20840. // Grounds
  20841. var grounds = geometries.grounds;
  20842. if (grounds) {
  20843. for (index = 0; index < grounds.length; index++) {
  20844. var parsedGround = grounds[index];
  20845. parseGround(parsedGround, scene);
  20846. }
  20847. }
  20848. // Planes
  20849. var planes = geometries.planes;
  20850. if (planes) {
  20851. for (index = 0; index < planes.length; index++) {
  20852. var parsedPlane = planes[index];
  20853. parsePlane(parsedPlane, scene);
  20854. }
  20855. }
  20856. // TorusKnots
  20857. var torusKnots = geometries.torusKnots;
  20858. if (torusKnots) {
  20859. for (index = 0; index < torusKnots.length; index++) {
  20860. var parsedTorusKnot = torusKnots[index];
  20861. parseTorusKnot(parsedTorusKnot, scene);
  20862. }
  20863. }
  20864. // VertexData
  20865. var vertexData = geometries.vertexData;
  20866. if (vertexData) {
  20867. for (index = 0; index < vertexData.length; index++) {
  20868. var parsedVertexData = vertexData[index];
  20869. parseVertexData(parsedVertexData, scene, rootUrl);
  20870. }
  20871. }
  20872. }
  20873. for (index = 0; index < parsedData.meshes.length; index++) {
  20874. var parsedMesh = parsedData.meshes[index];
  20875. parseMesh(parsedMesh, scene, rootUrl);
  20876. }
  20877. for (index = 0; index < parsedData.cameras.length; index++) {
  20878. var parsedCamera = parsedData.cameras[index];
  20879. parseCamera(parsedCamera, scene);
  20880. }
  20881. if (parsedData.activeCameraID) {
  20882. scene.setActiveCameraByID(parsedData.activeCameraID);
  20883. }
  20884. for (index = 0; index < scene.cameras.length; index++) {
  20885. var camera = scene.cameras[index];
  20886. if (camera._waitingParentId) {
  20887. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20888. camera._waitingParentId = undefined;
  20889. }
  20890. }
  20891. for (index = 0; index < scene.lights.length; index++) {
  20892. var light = scene.lights[index];
  20893. if (light._waitingParentId) {
  20894. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20895. light._waitingParentId = undefined;
  20896. }
  20897. }
  20898. // Sounds
  20899. if (parsedData.sounds) {
  20900. for (index = 0; index < parsedData.sounds.length; index++) {
  20901. var parsedSound = parsedData.sounds[index];
  20902. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20903. parseSound(parsedSound, scene, rootUrl);
  20904. }
  20905. else {
  20906. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20907. }
  20908. }
  20909. }
  20910. for (index = 0; index < scene.meshes.length; index++) {
  20911. var mesh = scene.meshes[index];
  20912. if (mesh._waitingParentId) {
  20913. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20914. mesh._waitingParentId = undefined;
  20915. }
  20916. if (mesh._waitingActions) {
  20917. parseActions(mesh._waitingActions, mesh, scene);
  20918. mesh._waitingActions = undefined;
  20919. }
  20920. }
  20921. // Particles Systems
  20922. if (parsedData.particleSystems) {
  20923. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20924. var parsedParticleSystem = parsedData.particleSystems[index];
  20925. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20926. }
  20927. }
  20928. // Lens flares
  20929. if (parsedData.lensFlareSystems) {
  20930. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20931. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20932. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20933. }
  20934. }
  20935. // Shadows
  20936. if (parsedData.shadowGenerators) {
  20937. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20938. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20939. parseShadowGenerator(parsedShadowGenerator, scene);
  20940. }
  20941. }
  20942. // Actions (scene)
  20943. if (parsedData.actions) {
  20944. parseActions(parsedData.actions, null, scene);
  20945. }
  20946. // Finish
  20947. return true;
  20948. }
  20949. });
  20950. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20951. })(BABYLON || (BABYLON = {}));
  20952. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20953. (function (BABYLON) {
  20954. // Unique ID when we import meshes from Babylon to CSG
  20955. var currentCSGMeshId = 0;
  20956. // # class Vertex
  20957. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20958. // one to provide additional features like texture coordinates and vertex
  20959. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20960. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20961. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20962. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20963. // is not used anywhere else.
  20964. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20965. var Vertex = (function () {
  20966. function Vertex(pos, normal, uv) {
  20967. this.pos = pos;
  20968. this.normal = normal;
  20969. this.uv = uv;
  20970. }
  20971. Vertex.prototype.clone = function () {
  20972. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20973. };
  20974. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20975. // orientation of a polygon is flipped.
  20976. Vertex.prototype.flip = function () {
  20977. this.normal = this.normal.scale(-1);
  20978. };
  20979. // Create a new vertex between this vertex and `other` by linearly
  20980. // interpolating all properties using a parameter of `t`. Subclasses should
  20981. // override this to interpolate additional properties.
  20982. Vertex.prototype.interpolate = function (other, t) {
  20983. 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));
  20984. };
  20985. return Vertex;
  20986. })();
  20987. // # class Plane
  20988. // Represents a plane in 3D space.
  20989. var Plane = (function () {
  20990. function Plane(normal, w) {
  20991. this.normal = normal;
  20992. this.w = w;
  20993. }
  20994. Plane.FromPoints = function (a, b, c) {
  20995. var v0 = c.subtract(a);
  20996. var v1 = b.subtract(a);
  20997. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20998. return null;
  20999. }
  21000. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  21001. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  21002. };
  21003. Plane.prototype.clone = function () {
  21004. return new Plane(this.normal.clone(), this.w);
  21005. };
  21006. Plane.prototype.flip = function () {
  21007. this.normal.scaleInPlace(-1);
  21008. this.w = -this.w;
  21009. };
  21010. // Split `polygon` by this plane if needed, then put the polygon or polygon
  21011. // fragments in the appropriate lists. Coplanar polygons go into either
  21012. // `coplanarFront` or `coplanarBack` depending on their orientation with
  21013. // respect to this plane. Polygons in front or in back of this plane go into
  21014. // either `front` or `back`.
  21015. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  21016. var COPLANAR = 0;
  21017. var FRONT = 1;
  21018. var BACK = 2;
  21019. var SPANNING = 3;
  21020. // Classify each point as well as the entire polygon into one of the above
  21021. // four classes.
  21022. var polygonType = 0;
  21023. var types = [];
  21024. for (var i = 0; i < polygon.vertices.length; i++) {
  21025. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  21026. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  21027. polygonType |= type;
  21028. types.push(type);
  21029. }
  21030. switch (polygonType) {
  21031. case COPLANAR:
  21032. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21033. break;
  21034. case FRONT:
  21035. front.push(polygon);
  21036. break;
  21037. case BACK:
  21038. back.push(polygon);
  21039. break;
  21040. case SPANNING:
  21041. var f = [], b = [];
  21042. for (i = 0; i < polygon.vertices.length; i++) {
  21043. var j = (i + 1) % polygon.vertices.length;
  21044. var ti = types[i], tj = types[j];
  21045. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21046. if (ti != BACK)
  21047. f.push(vi);
  21048. if (ti != FRONT)
  21049. b.push(ti != BACK ? vi.clone() : vi);
  21050. if ((ti | tj) == SPANNING) {
  21051. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21052. var v = vi.interpolate(vj, t);
  21053. f.push(v);
  21054. b.push(v.clone());
  21055. }
  21056. }
  21057. if (f.length >= 3) {
  21058. var poly = new Polygon(f, polygon.shared);
  21059. if (poly.plane)
  21060. front.push(poly);
  21061. }
  21062. if (b.length >= 3) {
  21063. poly = new Polygon(b, polygon.shared);
  21064. if (poly.plane)
  21065. back.push(poly);
  21066. }
  21067. break;
  21068. }
  21069. };
  21070. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21071. // point is on the plane.
  21072. Plane.EPSILON = 1e-5;
  21073. return Plane;
  21074. })();
  21075. // # class Polygon
  21076. // Represents a convex polygon. The vertices used to initialize a polygon must
  21077. // be coplanar and form a convex loop.
  21078. //
  21079. // Each convex polygon has a `shared` property, which is shared between all
  21080. // polygons that are clones of each other or were split from the same polygon.
  21081. // This can be used to define per-polygon properties (such as surface color).
  21082. var Polygon = (function () {
  21083. function Polygon(vertices, shared) {
  21084. this.vertices = vertices;
  21085. this.shared = shared;
  21086. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21087. }
  21088. Polygon.prototype.clone = function () {
  21089. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21090. return new Polygon(vertices, this.shared);
  21091. };
  21092. Polygon.prototype.flip = function () {
  21093. this.vertices.reverse().map(function (v) {
  21094. v.flip();
  21095. });
  21096. this.plane.flip();
  21097. };
  21098. return Polygon;
  21099. })();
  21100. // # class Node
  21101. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21102. // by picking a polygon to split along. That polygon (and all other coplanar
  21103. // polygons) are added directly to that node and the other polygons are added to
  21104. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21105. // no distinction between internal and leaf nodes.
  21106. var Node = (function () {
  21107. function Node(polygons) {
  21108. this.plane = null;
  21109. this.front = null;
  21110. this.back = null;
  21111. this.polygons = [];
  21112. if (polygons) {
  21113. this.build(polygons);
  21114. }
  21115. }
  21116. Node.prototype.clone = function () {
  21117. var node = new Node();
  21118. node.plane = this.plane && this.plane.clone();
  21119. node.front = this.front && this.front.clone();
  21120. node.back = this.back && this.back.clone();
  21121. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21122. return node;
  21123. };
  21124. // Convert solid space to empty space and empty space to solid space.
  21125. Node.prototype.invert = function () {
  21126. for (var i = 0; i < this.polygons.length; i++) {
  21127. this.polygons[i].flip();
  21128. }
  21129. if (this.plane) {
  21130. this.plane.flip();
  21131. }
  21132. if (this.front) {
  21133. this.front.invert();
  21134. }
  21135. if (this.back) {
  21136. this.back.invert();
  21137. }
  21138. var temp = this.front;
  21139. this.front = this.back;
  21140. this.back = temp;
  21141. };
  21142. // Recursively remove all polygons in `polygons` that are inside this BSP
  21143. // tree.
  21144. Node.prototype.clipPolygons = function (polygons) {
  21145. if (!this.plane)
  21146. return polygons.slice();
  21147. var front = [], back = [];
  21148. for (var i = 0; i < polygons.length; i++) {
  21149. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21150. }
  21151. if (this.front) {
  21152. front = this.front.clipPolygons(front);
  21153. }
  21154. if (this.back) {
  21155. back = this.back.clipPolygons(back);
  21156. }
  21157. else {
  21158. back = [];
  21159. }
  21160. return front.concat(back);
  21161. };
  21162. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21163. // `bsp`.
  21164. Node.prototype.clipTo = function (bsp) {
  21165. this.polygons = bsp.clipPolygons(this.polygons);
  21166. if (this.front)
  21167. this.front.clipTo(bsp);
  21168. if (this.back)
  21169. this.back.clipTo(bsp);
  21170. };
  21171. // Return a list of all polygons in this BSP tree.
  21172. Node.prototype.allPolygons = function () {
  21173. var polygons = this.polygons.slice();
  21174. if (this.front)
  21175. polygons = polygons.concat(this.front.allPolygons());
  21176. if (this.back)
  21177. polygons = polygons.concat(this.back.allPolygons());
  21178. return polygons;
  21179. };
  21180. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21181. // new polygons are filtered down to the bottom of the tree and become new
  21182. // nodes there. Each set of polygons is partitioned using the first polygon
  21183. // (no heuristic is used to pick a good split).
  21184. Node.prototype.build = function (polygons) {
  21185. if (!polygons.length)
  21186. return;
  21187. if (!this.plane)
  21188. this.plane = polygons[0].plane.clone();
  21189. var front = [], back = [];
  21190. for (var i = 0; i < polygons.length; i++) {
  21191. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21192. }
  21193. if (front.length) {
  21194. if (!this.front)
  21195. this.front = new Node();
  21196. this.front.build(front);
  21197. }
  21198. if (back.length) {
  21199. if (!this.back)
  21200. this.back = new Node();
  21201. this.back.build(back);
  21202. }
  21203. };
  21204. return Node;
  21205. })();
  21206. var CSG = (function () {
  21207. function CSG() {
  21208. this.polygons = new Array();
  21209. }
  21210. // Convert BABYLON.Mesh to BABYLON.CSG
  21211. CSG.FromMesh = function (mesh) {
  21212. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21213. if (mesh instanceof BABYLON.Mesh) {
  21214. mesh.computeWorldMatrix(true);
  21215. var matrix = mesh.getWorldMatrix();
  21216. var meshPosition = mesh.position.clone();
  21217. var meshRotation = mesh.rotation.clone();
  21218. var meshScaling = mesh.scaling.clone();
  21219. }
  21220. else {
  21221. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21222. }
  21223. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21224. var subMeshes = mesh.subMeshes;
  21225. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21226. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21227. vertices = [];
  21228. for (var j = 0; j < 3; j++) {
  21229. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21230. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21231. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21232. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21233. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21234. vertex = new Vertex(position, normal, uv);
  21235. vertices.push(vertex);
  21236. }
  21237. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21238. // To handle the case of degenerated triangle
  21239. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21240. if (polygon.plane)
  21241. polygons.push(polygon);
  21242. }
  21243. }
  21244. var csg = CSG.FromPolygons(polygons);
  21245. csg.matrix = matrix;
  21246. csg.position = meshPosition;
  21247. csg.rotation = meshRotation;
  21248. csg.scaling = meshScaling;
  21249. currentCSGMeshId++;
  21250. return csg;
  21251. };
  21252. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21253. CSG.FromPolygons = function (polygons) {
  21254. var csg = new BABYLON.CSG();
  21255. csg.polygons = polygons;
  21256. return csg;
  21257. };
  21258. CSG.prototype.clone = function () {
  21259. var csg = new BABYLON.CSG();
  21260. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21261. csg.copyTransformAttributes(this);
  21262. return csg;
  21263. };
  21264. CSG.prototype.toPolygons = function () {
  21265. return this.polygons;
  21266. };
  21267. CSG.prototype.union = function (csg) {
  21268. var a = new Node(this.clone().polygons);
  21269. var b = new Node(csg.clone().polygons);
  21270. a.clipTo(b);
  21271. b.clipTo(a);
  21272. b.invert();
  21273. b.clipTo(a);
  21274. b.invert();
  21275. a.build(b.allPolygons());
  21276. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21277. };
  21278. CSG.prototype.unionInPlace = function (csg) {
  21279. var a = new Node(this.polygons);
  21280. var b = new Node(csg.polygons);
  21281. a.clipTo(b);
  21282. b.clipTo(a);
  21283. b.invert();
  21284. b.clipTo(a);
  21285. b.invert();
  21286. a.build(b.allPolygons());
  21287. this.polygons = a.allPolygons();
  21288. };
  21289. CSG.prototype.subtract = function (csg) {
  21290. var a = new Node(this.clone().polygons);
  21291. var b = new Node(csg.clone().polygons);
  21292. a.invert();
  21293. a.clipTo(b);
  21294. b.clipTo(a);
  21295. b.invert();
  21296. b.clipTo(a);
  21297. b.invert();
  21298. a.build(b.allPolygons());
  21299. a.invert();
  21300. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21301. };
  21302. CSG.prototype.subtractInPlace = function (csg) {
  21303. var a = new Node(this.polygons);
  21304. var b = new Node(csg.polygons);
  21305. a.invert();
  21306. a.clipTo(b);
  21307. b.clipTo(a);
  21308. b.invert();
  21309. b.clipTo(a);
  21310. b.invert();
  21311. a.build(b.allPolygons());
  21312. a.invert();
  21313. this.polygons = a.allPolygons();
  21314. };
  21315. CSG.prototype.intersect = function (csg) {
  21316. var a = new Node(this.clone().polygons);
  21317. var b = new Node(csg.clone().polygons);
  21318. a.invert();
  21319. b.clipTo(a);
  21320. b.invert();
  21321. a.clipTo(b);
  21322. b.clipTo(a);
  21323. a.build(b.allPolygons());
  21324. a.invert();
  21325. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21326. };
  21327. CSG.prototype.intersectInPlace = function (csg) {
  21328. var a = new Node(this.polygons);
  21329. var b = new Node(csg.polygons);
  21330. a.invert();
  21331. b.clipTo(a);
  21332. b.invert();
  21333. a.clipTo(b);
  21334. b.clipTo(a);
  21335. a.build(b.allPolygons());
  21336. a.invert();
  21337. this.polygons = a.allPolygons();
  21338. };
  21339. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21340. // not modified.
  21341. CSG.prototype.inverse = function () {
  21342. var csg = this.clone();
  21343. csg.inverseInPlace();
  21344. return csg;
  21345. };
  21346. CSG.prototype.inverseInPlace = function () {
  21347. this.polygons.map(function (p) {
  21348. p.flip();
  21349. });
  21350. };
  21351. // This is used to keep meshes transformations so they can be restored
  21352. // when we build back a Babylon Mesh
  21353. // NB : All CSG operations are performed in world coordinates
  21354. CSG.prototype.copyTransformAttributes = function (csg) {
  21355. this.matrix = csg.matrix;
  21356. this.position = csg.position;
  21357. this.rotation = csg.rotation;
  21358. this.scaling = csg.scaling;
  21359. return this;
  21360. };
  21361. // Build Raw mesh from CSG
  21362. // Coordinates here are in world space
  21363. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21364. var matrix = this.matrix.clone();
  21365. matrix.invert();
  21366. 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;
  21367. if (keepSubMeshes) {
  21368. // Sort Polygons, since subMeshes are indices range
  21369. polygons.sort(function (a, b) {
  21370. if (a.shared.meshId === b.shared.meshId) {
  21371. return a.shared.subMeshId - b.shared.subMeshId;
  21372. }
  21373. else {
  21374. return a.shared.meshId - b.shared.meshId;
  21375. }
  21376. });
  21377. }
  21378. for (var i = 0, il = polygons.length; i < il; i++) {
  21379. polygon = polygons[i];
  21380. // Building SubMeshes
  21381. if (!subMesh_dict[polygon.shared.meshId]) {
  21382. subMesh_dict[polygon.shared.meshId] = {};
  21383. }
  21384. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21385. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21386. indexStart: +Infinity,
  21387. indexEnd: -Infinity,
  21388. materialIndex: polygon.shared.materialIndex
  21389. };
  21390. }
  21391. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21392. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21393. polygonIndices[0] = 0;
  21394. polygonIndices[1] = j - 1;
  21395. polygonIndices[2] = j;
  21396. for (var k = 0; k < 3; k++) {
  21397. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21398. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21399. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21400. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21401. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21402. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21403. // Check if 2 points can be merged
  21404. 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)) {
  21405. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21406. uvs.push(uv.x, uv.y);
  21407. normals.push(normal.x, normal.y, normal.z);
  21408. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21409. }
  21410. indices.push(vertex_idx);
  21411. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21412. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21413. currentIndex++;
  21414. }
  21415. }
  21416. }
  21417. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21418. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21419. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21420. mesh.setIndices(indices);
  21421. if (keepSubMeshes) {
  21422. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21423. var materialIndexOffset = 0, materialMaxIndex;
  21424. mesh.subMeshes.length = 0;
  21425. for (var m in subMesh_dict) {
  21426. materialMaxIndex = -1;
  21427. for (var sm in subMesh_dict[m]) {
  21428. subMesh_obj = subMesh_dict[m][sm];
  21429. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21430. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21431. }
  21432. materialIndexOffset += ++materialMaxIndex;
  21433. }
  21434. }
  21435. return mesh;
  21436. };
  21437. // Build Mesh from CSG taking material and transforms into account
  21438. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21439. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21440. mesh.material = material;
  21441. mesh.position.copyFrom(this.position);
  21442. mesh.rotation.copyFrom(this.rotation);
  21443. mesh.scaling.copyFrom(this.scaling);
  21444. mesh.computeWorldMatrix(true);
  21445. return mesh;
  21446. };
  21447. return CSG;
  21448. })();
  21449. BABYLON.CSG = CSG;
  21450. })(BABYLON || (BABYLON = {}));
  21451. //# sourceMappingURL=babylon.csg.js.map
  21452. var BABYLON;
  21453. (function (BABYLON) {
  21454. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21455. __extends(OculusDistortionCorrectionPostProcess, _super);
  21456. //ANY
  21457. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21458. var _this = this;
  21459. _super.call(this, name, "oculusDistortionCorrection", [
  21460. 'LensCenter',
  21461. 'Scale',
  21462. 'ScaleIn',
  21463. 'HmdWarpParam'
  21464. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21465. this._isRightEye = isRightEye;
  21466. this._distortionFactors = cameraSettings.DistortionK;
  21467. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21468. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21469. this.onSizeChanged = function () {
  21470. _this.aspectRatio = _this.width * .5 / _this.height;
  21471. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21472. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21473. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21474. };
  21475. this.onApply = function (effect) {
  21476. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21477. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21478. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21479. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21480. };
  21481. }
  21482. return OculusDistortionCorrectionPostProcess;
  21483. })(BABYLON.PostProcess);
  21484. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21485. })(BABYLON || (BABYLON = {}));
  21486. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21487. // 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
  21488. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21489. var BABYLON;
  21490. (function (BABYLON) {
  21491. (function (JoystickAxis) {
  21492. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21493. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21494. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21495. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21496. var JoystickAxis = BABYLON.JoystickAxis;
  21497. var VirtualJoystick = (function () {
  21498. function VirtualJoystick(leftJoystick) {
  21499. var _this = this;
  21500. if (leftJoystick) {
  21501. this._leftJoystick = true;
  21502. }
  21503. else {
  21504. this._leftJoystick = false;
  21505. }
  21506. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21507. VirtualJoystick._globalJoystickIndex++;
  21508. // By default left & right arrow keys are moving the X
  21509. // and up & down keys are moving the Y
  21510. this._axisTargetedByLeftAndRight = 0 /* X */;
  21511. this._axisTargetedByUpAndDown = 1 /* Y */;
  21512. this.reverseLeftRight = false;
  21513. this.reverseUpDown = false;
  21514. // collections of pointers
  21515. this._touches = new BABYLON.SmartCollection();
  21516. this.deltaPosition = BABYLON.Vector3.Zero();
  21517. this._joystickSensibility = 25;
  21518. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21519. this._rotationSpeed = 25;
  21520. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21521. this._rotateOnAxisRelativeToMesh = false;
  21522. // injecting a canvas element on top of the canvas 3D game
  21523. if (!VirtualJoystick.vjCanvas) {
  21524. window.addEventListener("resize", function () {
  21525. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21526. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21527. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21528. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21529. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21530. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21531. }, false);
  21532. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21533. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21534. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21535. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21536. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21537. VirtualJoystick.vjCanvas.style.width = "100%";
  21538. VirtualJoystick.vjCanvas.style.height = "100%";
  21539. VirtualJoystick.vjCanvas.style.position = "absolute";
  21540. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21541. VirtualJoystick.vjCanvas.style.top = "0px";
  21542. VirtualJoystick.vjCanvas.style.left = "0px";
  21543. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21544. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21545. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21546. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21547. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21548. document.body.appendChild(VirtualJoystick.vjCanvas);
  21549. }
  21550. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21551. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21552. this.pressed = false;
  21553. // default joystick color
  21554. this._joystickColor = "cyan";
  21555. this._joystickPointerID = -1;
  21556. // current joystick position
  21557. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21558. // origin joystick position
  21559. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21560. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21561. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21562. _this._onPointerDown(evt);
  21563. }, false);
  21564. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21565. _this._onPointerMove(evt);
  21566. }, false);
  21567. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21568. _this._onPointerUp(evt);
  21569. }, false);
  21570. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21571. _this._onPointerUp(evt);
  21572. }, false);
  21573. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21574. evt.preventDefault(); // Disables system menu
  21575. }, false);
  21576. requestAnimationFrame(function () {
  21577. _this._drawVirtualJoystick();
  21578. });
  21579. }
  21580. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21581. this._joystickSensibility = newJoystickSensibility;
  21582. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21583. };
  21584. VirtualJoystick.prototype._onPointerDown = function (e) {
  21585. var positionOnScreenCondition;
  21586. e.preventDefault();
  21587. if (this._leftJoystick === true) {
  21588. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21589. }
  21590. else {
  21591. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21592. }
  21593. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21594. // First contact will be dedicated to the virtual joystick
  21595. this._joystickPointerID = e.pointerId;
  21596. this._joystickPointerStartPos.x = e.clientX;
  21597. this._joystickPointerStartPos.y = e.clientY;
  21598. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21599. this._deltaJoystickVector.x = 0;
  21600. this._deltaJoystickVector.y = 0;
  21601. this.pressed = true;
  21602. this._touches.add(e.pointerId.toString(), e);
  21603. }
  21604. else {
  21605. // You can only trigger the action buttons with a joystick declared
  21606. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21607. this._action();
  21608. this._touches.add(e.pointerId.toString(), e);
  21609. }
  21610. }
  21611. };
  21612. VirtualJoystick.prototype._onPointerMove = function (e) {
  21613. // If the current pointer is the one associated to the joystick (first touch contact)
  21614. if (this._joystickPointerID == e.pointerId) {
  21615. this._joystickPointerPos.x = e.clientX;
  21616. this._joystickPointerPos.y = e.clientY;
  21617. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21618. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21619. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21620. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21621. switch (this._axisTargetedByLeftAndRight) {
  21622. case 0 /* X */:
  21623. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21624. break;
  21625. case 1 /* Y */:
  21626. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21627. break;
  21628. case 2 /* Z */:
  21629. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21630. break;
  21631. }
  21632. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21633. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21634. switch (this._axisTargetedByUpAndDown) {
  21635. case 0 /* X */:
  21636. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21637. break;
  21638. case 1 /* Y */:
  21639. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21640. break;
  21641. case 2 /* Z */:
  21642. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21643. break;
  21644. }
  21645. }
  21646. else {
  21647. if (this._touches.item(e.pointerId.toString())) {
  21648. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21649. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21650. }
  21651. }
  21652. };
  21653. VirtualJoystick.prototype._onPointerUp = function (e) {
  21654. this._clearCanvas();
  21655. if (this._joystickPointerID == e.pointerId) {
  21656. this._joystickPointerID = -1;
  21657. this.pressed = false;
  21658. }
  21659. this._deltaJoystickVector.x = 0;
  21660. this._deltaJoystickVector.y = 0;
  21661. this._touches.remove(e.pointerId.toString());
  21662. };
  21663. /**
  21664. * Change the color of the virtual joystick
  21665. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21666. */
  21667. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21668. this._joystickColor = newColor;
  21669. };
  21670. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21671. this._action = action;
  21672. };
  21673. // Define which axis you'd like to control for left & right
  21674. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21675. switch (axis) {
  21676. case 0 /* X */:
  21677. case 1 /* Y */:
  21678. case 2 /* Z */:
  21679. this._axisTargetedByLeftAndRight = axis;
  21680. break;
  21681. default:
  21682. this._axisTargetedByLeftAndRight = 0 /* X */;
  21683. break;
  21684. }
  21685. };
  21686. // Define which axis you'd like to control for up & down
  21687. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21688. switch (axis) {
  21689. case 0 /* X */:
  21690. case 1 /* Y */:
  21691. case 2 /* Z */:
  21692. this._axisTargetedByUpAndDown = axis;
  21693. break;
  21694. default:
  21695. this._axisTargetedByUpAndDown = 1 /* Y */;
  21696. break;
  21697. }
  21698. };
  21699. VirtualJoystick.prototype._clearCanvas = function () {
  21700. if (this._leftJoystick) {
  21701. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21702. }
  21703. else {
  21704. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21705. }
  21706. };
  21707. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21708. var _this = this;
  21709. if (this.pressed) {
  21710. this._clearCanvas();
  21711. this._touches.forEach(function (touch) {
  21712. if (touch.pointerId === _this._joystickPointerID) {
  21713. VirtualJoystick.vjCanvasContext.beginPath();
  21714. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21715. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21716. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21717. VirtualJoystick.vjCanvasContext.stroke();
  21718. VirtualJoystick.vjCanvasContext.beginPath();
  21719. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21720. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21721. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21722. VirtualJoystick.vjCanvasContext.stroke();
  21723. VirtualJoystick.vjCanvasContext.beginPath();
  21724. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21725. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21726. VirtualJoystick.vjCanvasContext.stroke();
  21727. }
  21728. else {
  21729. VirtualJoystick.vjCanvasContext.beginPath();
  21730. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21731. VirtualJoystick.vjCanvasContext.beginPath();
  21732. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21733. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21734. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21735. VirtualJoystick.vjCanvasContext.stroke();
  21736. }
  21737. ;
  21738. });
  21739. }
  21740. requestAnimationFrame(function () {
  21741. _this._drawVirtualJoystick();
  21742. });
  21743. };
  21744. VirtualJoystick.prototype.releaseCanvas = function () {
  21745. if (VirtualJoystick.vjCanvas) {
  21746. document.body.removeChild(VirtualJoystick.vjCanvas);
  21747. VirtualJoystick.vjCanvas = null;
  21748. }
  21749. };
  21750. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21751. VirtualJoystick._globalJoystickIndex = 0;
  21752. return VirtualJoystick;
  21753. })();
  21754. BABYLON.VirtualJoystick = VirtualJoystick;
  21755. })(BABYLON || (BABYLON = {}));
  21756. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21757. var BABYLON;
  21758. (function (BABYLON) {
  21759. var OculusRiftDevKit2013_Metric = {
  21760. HResolution: 1280,
  21761. VResolution: 800,
  21762. HScreenSize: 0.149759993,
  21763. VScreenSize: 0.0935999975,
  21764. VScreenCenter: 0.0467999987,
  21765. EyeToScreenDistance: 0.0410000011,
  21766. LensSeparationDistance: 0.0635000020,
  21767. InterpupillaryDistance: 0.0640000030,
  21768. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21769. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21770. PostProcessScaleFactor: 1.714605507808412,
  21771. LensCenterOffset: 0.151976421
  21772. };
  21773. var _OculusInnerCamera = (function (_super) {
  21774. __extends(_OculusInnerCamera, _super);
  21775. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21776. _super.call(this, name, position, scene);
  21777. this._workMatrix = new BABYLON.Matrix();
  21778. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21779. // Constants
  21780. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21781. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21782. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21783. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21784. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21785. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21786. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21787. // Postprocess
  21788. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21789. }
  21790. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21791. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21792. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21793. return this._projectionMatrix;
  21794. };
  21795. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21796. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21797. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21798. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21799. // Computing target and final matrix
  21800. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21801. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21802. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21803. return this._viewMatrix;
  21804. };
  21805. return _OculusInnerCamera;
  21806. })(BABYLON.FreeCamera);
  21807. var OculusCamera = (function (_super) {
  21808. __extends(OculusCamera, _super);
  21809. function OculusCamera(name, position, scene) {
  21810. _super.call(this, name, position, scene);
  21811. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21812. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21813. this.subCameras.push(this._leftCamera);
  21814. this.subCameras.push(this._rightCamera);
  21815. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21816. }
  21817. OculusCamera.prototype._update = function () {
  21818. this._leftCamera.position.copyFrom(this.position);
  21819. this._rightCamera.position.copyFrom(this.position);
  21820. this._updateCamera(this._leftCamera);
  21821. this._updateCamera(this._rightCamera);
  21822. _super.prototype._update.call(this);
  21823. };
  21824. OculusCamera.prototype._updateCamera = function (camera) {
  21825. camera.minZ = this.minZ;
  21826. camera.maxZ = this.maxZ;
  21827. camera.rotation.x = this.rotation.x;
  21828. camera.rotation.y = this.rotation.y;
  21829. camera.rotation.z = this.rotation.z;
  21830. };
  21831. // Oculus events
  21832. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21833. var yaw = evt.alpha / 180 * Math.PI;
  21834. var pitch = evt.beta / 180 * Math.PI;
  21835. var roll = evt.gamma / 180 * Math.PI;
  21836. if (!this._offsetOrientation) {
  21837. this._offsetOrientation = {
  21838. yaw: yaw,
  21839. pitch: pitch,
  21840. roll: roll
  21841. };
  21842. return;
  21843. }
  21844. else {
  21845. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21846. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21847. this.rotation.z += this._offsetOrientation.roll - roll;
  21848. this._offsetOrientation.yaw = yaw;
  21849. this._offsetOrientation.pitch = pitch;
  21850. this._offsetOrientation.roll = roll;
  21851. }
  21852. };
  21853. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21854. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21855. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21856. };
  21857. OculusCamera.prototype.detachControl = function (element) {
  21858. _super.prototype.detachControl.call(this, element);
  21859. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21860. };
  21861. return OculusCamera;
  21862. })(BABYLON.FreeCamera);
  21863. BABYLON.OculusCamera = OculusCamera;
  21864. })(BABYLON || (BABYLON = {}));
  21865. //# sourceMappingURL=babylon.oculusCamera.js.map
  21866. var BABYLON;
  21867. (function (BABYLON) {
  21868. var OculusRiftDevKit2013_Metric = {
  21869. HResolution: 1280,
  21870. VResolution: 800,
  21871. HScreenSize: 0.149759993,
  21872. VScreenSize: 0.0935999975,
  21873. VScreenCenter: 0.0467999987,
  21874. EyeToScreenDistance: 0.0410000011,
  21875. LensSeparationDistance: 0.0635000020,
  21876. InterpupillaryDistance: 0.0640000030,
  21877. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21878. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21879. PostProcessScaleFactor: 1.714605507808412,
  21880. LensCenterOffset: 0.151976421
  21881. };
  21882. var _OculusInnerGamepadCamera = (function (_super) {
  21883. __extends(_OculusInnerGamepadCamera, _super);
  21884. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21885. _super.call(this, name, position, scene);
  21886. this._workMatrix = new BABYLON.Matrix();
  21887. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21888. // Constants
  21889. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21890. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21891. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21892. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21893. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21894. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21895. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21896. // Postprocess
  21897. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21898. }
  21899. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21900. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21901. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21902. return this._projectionMatrix;
  21903. };
  21904. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21905. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21906. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21907. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21908. // Computing target and final matrix
  21909. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21910. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21911. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21912. return this._viewMatrix;
  21913. };
  21914. return _OculusInnerGamepadCamera;
  21915. })(BABYLON.FreeCamera);
  21916. var OculusGamepadCamera = (function (_super) {
  21917. __extends(OculusGamepadCamera, _super);
  21918. function OculusGamepadCamera(name, position, scene) {
  21919. var _this = this;
  21920. _super.call(this, name, position, scene);
  21921. this.angularSensibility = 200;
  21922. this.moveSensibility = 75;
  21923. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21924. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21925. this.subCameras.push(this._leftCamera);
  21926. this.subCameras.push(this._rightCamera);
  21927. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21928. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21929. _this._onNewGameConnected(gamepad);
  21930. });
  21931. }
  21932. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21933. // Only the first gamepad can control the camera
  21934. if (gamepad.index === 0) {
  21935. this._gamepad = gamepad;
  21936. }
  21937. };
  21938. OculusGamepadCamera.prototype._update = function () {
  21939. this._leftCamera.position.copyFrom(this.position);
  21940. this._rightCamera.position.copyFrom(this.position);
  21941. this._updateCamera(this._leftCamera);
  21942. this._updateCamera(this._rightCamera);
  21943. _super.prototype._update.call(this);
  21944. };
  21945. OculusGamepadCamera.prototype._checkInputs = function () {
  21946. if (!this._gamepad) {
  21947. return;
  21948. }
  21949. var LSValues = this._gamepad.leftStick;
  21950. var normalizedLX = LSValues.x / this.moveSensibility;
  21951. var normalizedLY = LSValues.y / this.moveSensibility;
  21952. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21953. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21954. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21955. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21956. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21957. };
  21958. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21959. camera.minZ = this.minZ;
  21960. camera.maxZ = this.maxZ;
  21961. camera.rotation.x = this.rotation.x;
  21962. camera.rotation.y = this.rotation.y;
  21963. camera.rotation.z = this.rotation.z;
  21964. };
  21965. // Oculus events
  21966. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21967. var yaw = evt.alpha / 180 * Math.PI;
  21968. var pitch = evt.beta / 180 * Math.PI;
  21969. var roll = evt.gamma / 180 * Math.PI;
  21970. if (!this._offsetOrientation) {
  21971. this._offsetOrientation = {
  21972. yaw: yaw,
  21973. pitch: pitch,
  21974. roll: roll
  21975. };
  21976. return;
  21977. }
  21978. else {
  21979. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21980. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21981. this.rotation.z += this._offsetOrientation.roll - roll;
  21982. this._offsetOrientation.yaw = yaw;
  21983. this._offsetOrientation.pitch = pitch;
  21984. this._offsetOrientation.roll = roll;
  21985. }
  21986. };
  21987. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21988. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21989. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21990. };
  21991. OculusGamepadCamera.prototype.detachControl = function (element) {
  21992. _super.prototype.detachControl.call(this, element);
  21993. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21994. };
  21995. OculusGamepadCamera.prototype.dispose = function () {
  21996. this._gamepads.dispose();
  21997. _super.prototype.dispose.call(this);
  21998. };
  21999. return OculusGamepadCamera;
  22000. })(BABYLON.FreeCamera);
  22001. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  22002. })(BABYLON || (BABYLON = {}));
  22003. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  22004. var BABYLON;
  22005. (function (BABYLON) {
  22006. // We're mainly based on the logic defined into the FreeCamera code
  22007. var VirtualJoysticksCamera = (function (_super) {
  22008. __extends(VirtualJoysticksCamera, _super);
  22009. function VirtualJoysticksCamera(name, position, scene) {
  22010. _super.call(this, name, position, scene);
  22011. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  22012. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  22013. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  22014. this._leftjoystick.setJoystickSensibility(0.15);
  22015. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  22016. this._rightjoystick.setAxisForUpDown(0 /* X */);
  22017. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  22018. this._rightjoystick.reverseUpDown = true;
  22019. this._rightjoystick.setJoystickSensibility(0.05);
  22020. this._rightjoystick.setJoystickColor("yellow");
  22021. }
  22022. VirtualJoysticksCamera.prototype._checkInputs = function () {
  22023. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22024. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  22025. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22026. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  22027. if (!this._leftjoystick.pressed) {
  22028. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22029. }
  22030. if (!this._rightjoystick.pressed) {
  22031. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22032. }
  22033. };
  22034. VirtualJoysticksCamera.prototype.dispose = function () {
  22035. this._leftjoystick.releaseCanvas();
  22036. _super.prototype.dispose.call(this);
  22037. };
  22038. return VirtualJoysticksCamera;
  22039. })(BABYLON.FreeCamera);
  22040. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22041. })(BABYLON || (BABYLON = {}));
  22042. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22043. var BABYLON;
  22044. (function (BABYLON) {
  22045. var ShaderMaterial = (function (_super) {
  22046. __extends(ShaderMaterial, _super);
  22047. function ShaderMaterial(name, scene, shaderPath, options) {
  22048. _super.call(this, name, scene);
  22049. this._textures = new Array();
  22050. this._floats = new Array();
  22051. this._floatsArrays = {};
  22052. this._colors3 = new Array();
  22053. this._colors4 = new Array();
  22054. this._vectors2 = new Array();
  22055. this._vectors3 = new Array();
  22056. this._matrices = new Array();
  22057. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22058. this._shaderPath = shaderPath;
  22059. options.needAlphaBlending = options.needAlphaBlending || false;
  22060. options.needAlphaTesting = options.needAlphaTesting || false;
  22061. options.attributes = options.attributes || ["position", "normal", "uv"];
  22062. options.uniforms = options.uniforms || ["worldViewProjection"];
  22063. options.samplers = options.samplers || [];
  22064. this._options = options;
  22065. }
  22066. ShaderMaterial.prototype.needAlphaBlending = function () {
  22067. return this._options.needAlphaBlending;
  22068. };
  22069. ShaderMaterial.prototype.needAlphaTesting = function () {
  22070. return this._options.needAlphaTesting;
  22071. };
  22072. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22073. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22074. this._options.uniforms.push(uniformName);
  22075. }
  22076. };
  22077. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22078. if (this._options.samplers.indexOf(name) === -1) {
  22079. this._options.samplers.push(name);
  22080. }
  22081. this._textures[name] = texture;
  22082. return this;
  22083. };
  22084. ShaderMaterial.prototype.setFloat = function (name, value) {
  22085. this._checkUniform(name);
  22086. this._floats[name] = value;
  22087. return this;
  22088. };
  22089. ShaderMaterial.prototype.setFloats = function (name, value) {
  22090. this._checkUniform(name);
  22091. this._floatsArrays[name] = value;
  22092. return this;
  22093. };
  22094. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22095. this._checkUniform(name);
  22096. this._colors3[name] = value;
  22097. return this;
  22098. };
  22099. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22100. this._checkUniform(name);
  22101. this._colors4[name] = value;
  22102. return this;
  22103. };
  22104. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22105. this._checkUniform(name);
  22106. this._vectors2[name] = value;
  22107. return this;
  22108. };
  22109. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22110. this._checkUniform(name);
  22111. this._vectors3[name] = value;
  22112. return this;
  22113. };
  22114. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22115. this._checkUniform(name);
  22116. this._matrices[name] = value;
  22117. return this;
  22118. };
  22119. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22120. var scene = this.getScene();
  22121. var engine = scene.getEngine();
  22122. if (!this.checkReadyOnEveryCall) {
  22123. if (this._renderId === scene.getRenderId()) {
  22124. return true;
  22125. }
  22126. }
  22127. // Instances
  22128. var defines = [];
  22129. var fallbacks = new BABYLON.EffectFallbacks();
  22130. if (useInstances) {
  22131. defines.push("#define INSTANCES");
  22132. }
  22133. // Bones
  22134. if (mesh && mesh.useBones) {
  22135. defines.push("#define BONES");
  22136. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22137. defines.push("#define BONES4");
  22138. fallbacks.addFallback(0, "BONES4");
  22139. }
  22140. // Alpha test
  22141. if (engine.getAlphaTesting()) {
  22142. defines.push("#define ALPHATEST");
  22143. }
  22144. var previousEffect = this._effect;
  22145. var join = defines.join("\n");
  22146. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22147. if (!this._effect.isReady()) {
  22148. return false;
  22149. }
  22150. if (previousEffect !== this._effect) {
  22151. scene.resetCachedMaterial();
  22152. }
  22153. this._renderId = scene.getRenderId();
  22154. return true;
  22155. };
  22156. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22157. var scene = this.getScene();
  22158. if (this._options.uniforms.indexOf("world") !== -1) {
  22159. this._effect.setMatrix("world", world);
  22160. }
  22161. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22162. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22163. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22164. }
  22165. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22166. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22167. }
  22168. };
  22169. ShaderMaterial.prototype.bind = function (world, mesh) {
  22170. // Std values
  22171. this.bindOnlyWorldMatrix(world);
  22172. if (this.getScene().getCachedMaterial() !== this) {
  22173. if (this._options.uniforms.indexOf("view") !== -1) {
  22174. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22175. }
  22176. if (this._options.uniforms.indexOf("projection") !== -1) {
  22177. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22178. }
  22179. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22180. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22181. }
  22182. // Bones
  22183. if (mesh && mesh.useBones) {
  22184. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22185. }
  22186. for (var name in this._textures) {
  22187. this._effect.setTexture(name, this._textures[name]);
  22188. }
  22189. for (name in this._floats) {
  22190. this._effect.setFloat(name, this._floats[name]);
  22191. }
  22192. for (name in this._floatsArrays) {
  22193. this._effect.setArray(name, this._floatsArrays[name]);
  22194. }
  22195. for (name in this._colors3) {
  22196. this._effect.setColor3(name, this._colors3[name]);
  22197. }
  22198. for (name in this._colors4) {
  22199. var color = this._colors4[name];
  22200. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22201. }
  22202. for (name in this._vectors2) {
  22203. this._effect.setVector2(name, this._vectors2[name]);
  22204. }
  22205. for (name in this._vectors3) {
  22206. this._effect.setVector3(name, this._vectors3[name]);
  22207. }
  22208. for (name in this._matrices) {
  22209. this._effect.setMatrix(name, this._matrices[name]);
  22210. }
  22211. }
  22212. _super.prototype.bind.call(this, world, mesh);
  22213. };
  22214. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22215. for (var name in this._textures) {
  22216. this._textures[name].dispose();
  22217. }
  22218. this._textures = [];
  22219. _super.prototype.dispose.call(this, forceDisposeEffect);
  22220. };
  22221. return ShaderMaterial;
  22222. })(BABYLON.Material);
  22223. BABYLON.ShaderMaterial = ShaderMaterial;
  22224. })(BABYLON || (BABYLON = {}));
  22225. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22226. (function (BABYLON) {
  22227. var VertexData = (function () {
  22228. function VertexData() {
  22229. }
  22230. VertexData.prototype.set = function (data, kind) {
  22231. switch (kind) {
  22232. case BABYLON.VertexBuffer.PositionKind:
  22233. this.positions = data;
  22234. break;
  22235. case BABYLON.VertexBuffer.NormalKind:
  22236. this.normals = data;
  22237. break;
  22238. case BABYLON.VertexBuffer.UVKind:
  22239. this.uvs = data;
  22240. break;
  22241. case BABYLON.VertexBuffer.UV2Kind:
  22242. this.uv2s = data;
  22243. break;
  22244. case BABYLON.VertexBuffer.ColorKind:
  22245. this.colors = data;
  22246. break;
  22247. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22248. this.matricesIndices = data;
  22249. break;
  22250. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22251. this.matricesWeights = data;
  22252. break;
  22253. }
  22254. };
  22255. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22256. this._applyTo(mesh, updatable);
  22257. };
  22258. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22259. this._applyTo(geometry, updatable);
  22260. };
  22261. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22262. this._update(mesh);
  22263. };
  22264. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22265. this._update(geometry);
  22266. };
  22267. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22268. if (this.positions) {
  22269. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22270. }
  22271. if (this.normals) {
  22272. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22273. }
  22274. if (this.uvs) {
  22275. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22276. }
  22277. if (this.uv2s) {
  22278. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22279. }
  22280. if (this.colors) {
  22281. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22282. }
  22283. if (this.matricesIndices) {
  22284. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22285. }
  22286. if (this.matricesWeights) {
  22287. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22288. }
  22289. if (this.indices) {
  22290. meshOrGeometry.setIndices(this.indices);
  22291. }
  22292. };
  22293. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22294. if (this.positions) {
  22295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22296. }
  22297. if (this.normals) {
  22298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22299. }
  22300. if (this.uvs) {
  22301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22302. }
  22303. if (this.uv2s) {
  22304. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22305. }
  22306. if (this.colors) {
  22307. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22308. }
  22309. if (this.matricesIndices) {
  22310. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22311. }
  22312. if (this.matricesWeights) {
  22313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22314. }
  22315. if (this.indices) {
  22316. meshOrGeometry.setIndices(this.indices);
  22317. }
  22318. };
  22319. VertexData.prototype.transform = function (matrix) {
  22320. var transformed = BABYLON.Vector3.Zero();
  22321. if (this.positions) {
  22322. var position = BABYLON.Vector3.Zero();
  22323. for (var index = 0; index < this.positions.length; index += 3) {
  22324. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22325. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22326. this.positions[index] = transformed.x;
  22327. this.positions[index + 1] = transformed.y;
  22328. this.positions[index + 2] = transformed.z;
  22329. }
  22330. }
  22331. if (this.normals) {
  22332. var normal = BABYLON.Vector3.Zero();
  22333. for (index = 0; index < this.normals.length; index += 3) {
  22334. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22335. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22336. this.normals[index] = transformed.x;
  22337. this.normals[index + 1] = transformed.y;
  22338. this.normals[index + 2] = transformed.z;
  22339. }
  22340. }
  22341. };
  22342. VertexData.prototype.merge = function (other) {
  22343. if (other.indices) {
  22344. if (!this.indices) {
  22345. this.indices = [];
  22346. }
  22347. var offset = this.positions ? this.positions.length / 3 : 0;
  22348. for (var index = 0; index < other.indices.length; index++) {
  22349. this.indices.push(other.indices[index] + offset);
  22350. }
  22351. }
  22352. if (other.positions) {
  22353. if (!this.positions) {
  22354. this.positions = [];
  22355. }
  22356. for (index = 0; index < other.positions.length; index++) {
  22357. this.positions.push(other.positions[index]);
  22358. }
  22359. }
  22360. if (other.normals) {
  22361. if (!this.normals) {
  22362. this.normals = [];
  22363. }
  22364. for (index = 0; index < other.normals.length; index++) {
  22365. this.normals.push(other.normals[index]);
  22366. }
  22367. }
  22368. if (other.uvs) {
  22369. if (!this.uvs) {
  22370. this.uvs = [];
  22371. }
  22372. for (index = 0; index < other.uvs.length; index++) {
  22373. this.uvs.push(other.uvs[index]);
  22374. }
  22375. }
  22376. if (other.uv2s) {
  22377. if (!this.uv2s) {
  22378. this.uv2s = [];
  22379. }
  22380. for (index = 0; index < other.uv2s.length; index++) {
  22381. this.uv2s.push(other.uv2s[index]);
  22382. }
  22383. }
  22384. if (other.matricesIndices) {
  22385. if (!this.matricesIndices) {
  22386. this.matricesIndices = [];
  22387. }
  22388. for (index = 0; index < other.matricesIndices.length; index++) {
  22389. this.matricesIndices.push(other.matricesIndices[index]);
  22390. }
  22391. }
  22392. if (other.matricesWeights) {
  22393. if (!this.matricesWeights) {
  22394. this.matricesWeights = [];
  22395. }
  22396. for (index = 0; index < other.matricesWeights.length; index++) {
  22397. this.matricesWeights.push(other.matricesWeights[index]);
  22398. }
  22399. }
  22400. if (other.colors) {
  22401. if (!this.colors) {
  22402. this.colors = [];
  22403. }
  22404. for (index = 0; index < other.colors.length; index++) {
  22405. this.colors.push(other.colors[index]);
  22406. }
  22407. }
  22408. };
  22409. // Statics
  22410. VertexData.ExtractFromMesh = function (mesh) {
  22411. return VertexData._ExtractFrom(mesh);
  22412. };
  22413. VertexData.ExtractFromGeometry = function (geometry) {
  22414. return VertexData._ExtractFrom(geometry);
  22415. };
  22416. VertexData._ExtractFrom = function (meshOrGeometry) {
  22417. var result = new VertexData();
  22418. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22419. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22420. }
  22421. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22422. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22423. }
  22424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22425. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22426. }
  22427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22428. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22429. }
  22430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22431. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22432. }
  22433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22434. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22435. }
  22436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22437. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22438. }
  22439. result.indices = meshOrGeometry.getIndices();
  22440. return result;
  22441. };
  22442. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22443. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22444. closeArray = closeArray || false;
  22445. closePath = closePath || false;
  22446. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22447. offset = offset || defaultOffset;
  22448. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22449. var positions = [];
  22450. var indices = [];
  22451. var normals = [];
  22452. var uvs = [];
  22453. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22454. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22455. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22456. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22457. var minlg; // minimal length among all paths from pathArray
  22458. var lg = []; // array of path lengths : nb of vertex per path
  22459. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22460. var p; // path iterator
  22461. var i; // point iterator
  22462. var j; // point iterator
  22463. // if single path in pathArray
  22464. if (pathArray.length < 2) {
  22465. var ar1 = [];
  22466. var ar2 = [];
  22467. for (i = 0; i < pathArray[0].length - offset; i++) {
  22468. ar1.push(pathArray[0][i]);
  22469. ar2.push(pathArray[0][i + offset]);
  22470. }
  22471. pathArray = [ar1, ar2];
  22472. }
  22473. // positions and horizontal distances (u)
  22474. var idc = 0;
  22475. minlg = pathArray[0].length;
  22476. for (p = 0; p < pathArray.length; p++) {
  22477. uTotalDistance[p] = 0;
  22478. us[p] = [0];
  22479. var path = pathArray[p];
  22480. var l = path.length;
  22481. minlg = (minlg < l) ? minlg : l;
  22482. lg[p] = l;
  22483. idx[p] = idc;
  22484. j = 0;
  22485. while (j < l) {
  22486. positions.push(path[j].x, path[j].y, path[j].z);
  22487. if (j > 0) {
  22488. var vectlg = path[j].subtract(path[j - 1]).length();
  22489. var dist = vectlg + uTotalDistance[p];
  22490. us[p].push(dist);
  22491. uTotalDistance[p] = dist;
  22492. }
  22493. j++;
  22494. }
  22495. if (closePath) {
  22496. vectlg = path[0].subtract(path[j - 1]).length();
  22497. dist = vectlg + uTotalDistance[p];
  22498. uTotalDistance[p] = dist;
  22499. }
  22500. idc += l;
  22501. }
  22502. for (i = 0; i < minlg; i++) {
  22503. vTotalDistance[i] = 0;
  22504. vs[i] = [0];
  22505. var path1;
  22506. var path2;
  22507. for (p = 0; p < pathArray.length - 1; p++) {
  22508. path1 = pathArray[p];
  22509. path2 = pathArray[p + 1];
  22510. vectlg = path2[i].subtract(path1[i]).length();
  22511. dist = vectlg + vTotalDistance[i];
  22512. vs[i].push(dist);
  22513. vTotalDistance[i] = dist;
  22514. }
  22515. if (closeArray) {
  22516. path1 = pathArray[p];
  22517. path2 = pathArray[0];
  22518. vectlg = path2[i].subtract(path1[i]).length();
  22519. dist = vectlg + vTotalDistance[i];
  22520. vTotalDistance[i] = dist;
  22521. }
  22522. }
  22523. // uvs
  22524. var u;
  22525. var v;
  22526. for (p = 0; p < pathArray.length; p++) {
  22527. for (i = 0; i < minlg; i++) {
  22528. u = us[p][i] / uTotalDistance[p];
  22529. v = vs[i][p] / vTotalDistance[i];
  22530. uvs.push(u, v);
  22531. }
  22532. }
  22533. // indices
  22534. p = 0; // path index
  22535. var pi = 0; // positions array index
  22536. var l1 = lg[p] - 1; // path1 length
  22537. var l2 = lg[p + 1] - 1; // path2 length
  22538. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22539. var shft = idx[1] - idx[0]; // shift
  22540. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22541. var t1; // two consecutive triangles, so 4 points : point1
  22542. var t2; // point2
  22543. var t3; // point3
  22544. var t4; // point4
  22545. while (pi <= min && p < path1nb) {
  22546. // 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
  22547. t1 = pi;
  22548. t2 = pi + shft;
  22549. t3 = pi + 1;
  22550. t4 = pi + shft + 1;
  22551. indices.push(pi, pi + shft, pi + 1);
  22552. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22553. pi += 1;
  22554. if (pi === min) {
  22555. if (closePath) {
  22556. indices.push(pi, pi + shft, idx[p]);
  22557. indices.push(idx[p] + shft, idx[p], pi + shft);
  22558. t3 = idx[p];
  22559. t4 = idx[p] + shft;
  22560. }
  22561. p++;
  22562. if (p === lg.length - 1) {
  22563. shft = idx[0] - idx[p];
  22564. l1 = lg[p] - 1;
  22565. l2 = lg[0] - 1;
  22566. }
  22567. else {
  22568. shft = idx[p + 1] - idx[p];
  22569. l1 = lg[p] - 1;
  22570. l2 = lg[p + 1] - 1;
  22571. }
  22572. pi = idx[p];
  22573. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22574. }
  22575. }
  22576. // normals
  22577. VertexData.ComputeNormals(positions, indices, normals);
  22578. // sides
  22579. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22580. // Result
  22581. var vertexData = new VertexData();
  22582. vertexData.indices = indices;
  22583. vertexData.positions = positions;
  22584. vertexData.normals = normals;
  22585. vertexData.uvs = uvs;
  22586. return vertexData;
  22587. };
  22588. VertexData.CreateBox = function (size, sideOrientation) {
  22589. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22590. var normalsSource = [
  22591. new BABYLON.Vector3(0, 0, 1),
  22592. new BABYLON.Vector3(0, 0, -1),
  22593. new BABYLON.Vector3(1, 0, 0),
  22594. new BABYLON.Vector3(-1, 0, 0),
  22595. new BABYLON.Vector3(0, 1, 0),
  22596. new BABYLON.Vector3(0, -1, 0)
  22597. ];
  22598. var indices = [];
  22599. var positions = [];
  22600. var normals = [];
  22601. var uvs = [];
  22602. size = size || 1;
  22603. for (var index = 0; index < normalsSource.length; index++) {
  22604. var normal = normalsSource[index];
  22605. // Get two vectors perpendicular to the face normal and to each other.
  22606. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22607. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22608. // Six indices (two triangles) per face.
  22609. var verticesLength = positions.length / 3;
  22610. indices.push(verticesLength);
  22611. indices.push(verticesLength + 1);
  22612. indices.push(verticesLength + 2);
  22613. indices.push(verticesLength);
  22614. indices.push(verticesLength + 2);
  22615. indices.push(verticesLength + 3);
  22616. // Four vertices per face.
  22617. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22618. positions.push(vertex.x, vertex.y, vertex.z);
  22619. normals.push(normal.x, normal.y, normal.z);
  22620. uvs.push(1.0, 1.0);
  22621. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22622. positions.push(vertex.x, vertex.y, vertex.z);
  22623. normals.push(normal.x, normal.y, normal.z);
  22624. uvs.push(0.0, 1.0);
  22625. vertex = normal.add(side1).add(side2).scale(size / 2);
  22626. positions.push(vertex.x, vertex.y, vertex.z);
  22627. normals.push(normal.x, normal.y, normal.z);
  22628. uvs.push(0.0, 0.0);
  22629. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22630. positions.push(vertex.x, vertex.y, vertex.z);
  22631. normals.push(normal.x, normal.y, normal.z);
  22632. uvs.push(1.0, 0.0);
  22633. }
  22634. // sides
  22635. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22636. // Result
  22637. var vertexData = new VertexData();
  22638. vertexData.indices = indices;
  22639. vertexData.positions = positions;
  22640. vertexData.normals = normals;
  22641. vertexData.uvs = uvs;
  22642. return vertexData;
  22643. };
  22644. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22645. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22646. segments = segments || 32;
  22647. diameter = diameter || 1;
  22648. var radius = diameter / 2;
  22649. var totalZRotationSteps = 2 + segments;
  22650. var totalYRotationSteps = 2 * totalZRotationSteps;
  22651. var indices = [];
  22652. var positions = [];
  22653. var normals = [];
  22654. var uvs = [];
  22655. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22656. var normalizedZ = zRotationStep / totalZRotationSteps;
  22657. var angleZ = (normalizedZ * Math.PI);
  22658. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22659. var normalizedY = yRotationStep / totalYRotationSteps;
  22660. var angleY = normalizedY * Math.PI * 2;
  22661. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22662. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22663. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22664. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22665. var vertex = complete.scale(radius);
  22666. var normal = BABYLON.Vector3.Normalize(vertex);
  22667. positions.push(vertex.x, vertex.y, vertex.z);
  22668. normals.push(normal.x, normal.y, normal.z);
  22669. uvs.push(normalizedZ, normalizedY);
  22670. }
  22671. if (zRotationStep > 0) {
  22672. var verticesCount = positions.length / 3;
  22673. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22674. indices.push((firstIndex));
  22675. indices.push((firstIndex + 1));
  22676. indices.push(firstIndex + totalYRotationSteps + 1);
  22677. indices.push((firstIndex + totalYRotationSteps + 1));
  22678. indices.push((firstIndex + 1));
  22679. indices.push((firstIndex + totalYRotationSteps + 2));
  22680. }
  22681. }
  22682. }
  22683. // Sides
  22684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22685. // Result
  22686. var vertexData = new VertexData();
  22687. vertexData.indices = indices;
  22688. vertexData.positions = positions;
  22689. vertexData.normals = normals;
  22690. vertexData.uvs = uvs;
  22691. return vertexData;
  22692. };
  22693. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22694. if (subdivisions === void 0) { subdivisions = 1; }
  22695. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22696. var radiusTop = diameterTop / 2;
  22697. var radiusBottom = diameterBottom / 2;
  22698. var indices = [];
  22699. var positions = [];
  22700. var normals = [];
  22701. var uvs = [];
  22702. height = height || 1;
  22703. diameterTop = diameterTop || 0.5;
  22704. diameterBottom = diameterBottom || 1;
  22705. tessellation = tessellation || 16;
  22706. subdivisions = subdivisions || 1;
  22707. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22708. var getCircleVector = function (i) {
  22709. var angle = (i * 2.0 * Math.PI / tessellation);
  22710. var dx = Math.cos(angle);
  22711. var dz = Math.sin(angle);
  22712. return new BABYLON.Vector3(dx, 0, dz);
  22713. };
  22714. var createCylinderCap = function (isTop) {
  22715. var radius = isTop ? radiusTop : radiusBottom;
  22716. if (radius === 0) {
  22717. return;
  22718. }
  22719. var vbase = positions.length / 3;
  22720. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22721. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22722. if (!isTop) {
  22723. offset.scaleInPlace(-1);
  22724. textureScale.x = -textureScale.x;
  22725. }
  22726. for (var i = 0; i < tessellation; i++) {
  22727. var circleVector = getCircleVector(i);
  22728. var position = circleVector.scale(radius).add(offset);
  22729. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22730. positions.push(position.x, position.y, position.z);
  22731. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22732. }
  22733. for (i = 0; i < tessellation - 2; i++) {
  22734. if (!isTop) {
  22735. indices.push(vbase);
  22736. indices.push(vbase + (i + 2) % tessellation);
  22737. indices.push(vbase + (i + 1) % tessellation);
  22738. }
  22739. else {
  22740. indices.push(vbase);
  22741. indices.push(vbase + (i + 1) % tessellation);
  22742. indices.push(vbase + (i + 2) % tessellation);
  22743. }
  22744. }
  22745. };
  22746. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22747. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22748. var stride = tessellation + 1;
  22749. for (var i = 0; i <= tessellation; i++) {
  22750. var circleVector = getCircleVector(i);
  22751. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22752. var position, radius = radiusBottom;
  22753. for (var s = 0; s <= subdivisions; s++) {
  22754. // Update variables
  22755. position = circleVector.scale(radius);
  22756. position.addInPlace(base.add(offset.scale(s)));
  22757. textureCoordinate.y += 1 / subdivisions;
  22758. radius += (radiusTop - radiusBottom) / subdivisions;
  22759. // Push in arrays
  22760. positions.push(position.x, position.y, position.z);
  22761. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22762. }
  22763. }
  22764. subdivisions += 1;
  22765. for (s = 0; s < subdivisions - 1; s++) {
  22766. for (i = 0; i <= tessellation; i++) {
  22767. indices.push(i * subdivisions + s);
  22768. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22769. indices.push(i * subdivisions + (s + 1));
  22770. indices.push(i * subdivisions + (s + 1));
  22771. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22772. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22773. }
  22774. }
  22775. // Create flat triangle fan caps to seal the top and bottom.
  22776. createCylinderCap(true);
  22777. createCylinderCap(false);
  22778. // Normals
  22779. VertexData.ComputeNormals(positions, indices, normals);
  22780. // Sides
  22781. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22782. // Result
  22783. var vertexData = new VertexData();
  22784. vertexData.indices = indices;
  22785. vertexData.positions = positions;
  22786. vertexData.normals = normals;
  22787. vertexData.uvs = uvs;
  22788. return vertexData;
  22789. };
  22790. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22791. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22792. var indices = [];
  22793. var positions = [];
  22794. var normals = [];
  22795. var uvs = [];
  22796. diameter = diameter || 1;
  22797. thickness = thickness || 0.5;
  22798. tessellation = tessellation || 16;
  22799. var stride = tessellation + 1;
  22800. for (var i = 0; i <= tessellation; i++) {
  22801. var u = i / tessellation;
  22802. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22803. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22804. for (var j = 0; j <= tessellation; j++) {
  22805. var v = 1 - j / tessellation;
  22806. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22807. var dx = Math.cos(innerAngle);
  22808. var dy = Math.sin(innerAngle);
  22809. // Create a vertex.
  22810. var normal = new BABYLON.Vector3(dx, dy, 0);
  22811. var position = normal.scale(thickness / 2);
  22812. var textureCoordinate = new BABYLON.Vector2(u, v);
  22813. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22814. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22815. positions.push(position.x, position.y, position.z);
  22816. normals.push(normal.x, normal.y, normal.z);
  22817. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22818. // And create indices for two triangles.
  22819. var nextI = (i + 1) % stride;
  22820. var nextJ = (j + 1) % stride;
  22821. indices.push(i * stride + j);
  22822. indices.push(i * stride + nextJ);
  22823. indices.push(nextI * stride + j);
  22824. indices.push(i * stride + nextJ);
  22825. indices.push(nextI * stride + nextJ);
  22826. indices.push(nextI * stride + j);
  22827. }
  22828. }
  22829. // Sides
  22830. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22831. // Result
  22832. var vertexData = new VertexData();
  22833. vertexData.indices = indices;
  22834. vertexData.positions = positions;
  22835. vertexData.normals = normals;
  22836. vertexData.uvs = uvs;
  22837. return vertexData;
  22838. };
  22839. VertexData.CreateLines = function (points) {
  22840. var indices = [];
  22841. var positions = [];
  22842. for (var index = 0; index < points.length; index++) {
  22843. positions.push(points[index].x, points[index].y, points[index].z);
  22844. if (index > 0) {
  22845. indices.push(index - 1);
  22846. indices.push(index);
  22847. }
  22848. }
  22849. // Result
  22850. var vertexData = new VertexData();
  22851. vertexData.indices = indices;
  22852. vertexData.positions = positions;
  22853. return vertexData;
  22854. };
  22855. VertexData.CreateGround = function (width, height, subdivisions) {
  22856. var indices = [];
  22857. var positions = [];
  22858. var normals = [];
  22859. var uvs = [];
  22860. var row, col;
  22861. width = width || 1;
  22862. height = height || 1;
  22863. subdivisions = subdivisions || 1;
  22864. for (row = 0; row <= subdivisions; row++) {
  22865. for (col = 0; col <= subdivisions; col++) {
  22866. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22867. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22868. positions.push(position.x, position.y, position.z);
  22869. normals.push(normal.x, normal.y, normal.z);
  22870. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22871. }
  22872. }
  22873. for (row = 0; row < subdivisions; row++) {
  22874. for (col = 0; col < subdivisions; col++) {
  22875. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22876. indices.push(col + 1 + row * (subdivisions + 1));
  22877. indices.push(col + row * (subdivisions + 1));
  22878. indices.push(col + (row + 1) * (subdivisions + 1));
  22879. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22880. indices.push(col + row * (subdivisions + 1));
  22881. }
  22882. }
  22883. // Result
  22884. var vertexData = new VertexData();
  22885. vertexData.indices = indices;
  22886. vertexData.positions = positions;
  22887. vertexData.normals = normals;
  22888. vertexData.uvs = uvs;
  22889. return vertexData;
  22890. };
  22891. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22892. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22893. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22894. var indices = [];
  22895. var positions = [];
  22896. var normals = [];
  22897. var uvs = [];
  22898. var row, col, tileRow, tileCol;
  22899. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22900. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22901. precision.w = (precision.w < 1) ? 1 : precision.w;
  22902. precision.h = (precision.h < 1) ? 1 : precision.h;
  22903. var tileSize = {
  22904. 'w': (xmax - xmin) / subdivisions.w,
  22905. 'h': (zmax - zmin) / subdivisions.h
  22906. };
  22907. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22908. // Indices
  22909. var base = positions.length / 3;
  22910. var rowLength = precision.w + 1;
  22911. for (row = 0; row < precision.h; row++) {
  22912. for (col = 0; col < precision.w; col++) {
  22913. var square = [
  22914. base + col + row * rowLength,
  22915. base + (col + 1) + row * rowLength,
  22916. base + (col + 1) + (row + 1) * rowLength,
  22917. base + col + (row + 1) * rowLength
  22918. ];
  22919. indices.push(square[1]);
  22920. indices.push(square[2]);
  22921. indices.push(square[3]);
  22922. indices.push(square[0]);
  22923. indices.push(square[1]);
  22924. indices.push(square[3]);
  22925. }
  22926. }
  22927. // Position, normals and uvs
  22928. var position = BABYLON.Vector3.Zero();
  22929. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22930. for (row = 0; row <= precision.h; row++) {
  22931. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22932. for (col = 0; col <= precision.w; col++) {
  22933. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22934. position.y = 0;
  22935. positions.push(position.x, position.y, position.z);
  22936. normals.push(normal.x, normal.y, normal.z);
  22937. uvs.push(col / precision.w, row / precision.h);
  22938. }
  22939. }
  22940. }
  22941. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22942. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22943. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22944. }
  22945. }
  22946. // Result
  22947. var vertexData = new VertexData();
  22948. vertexData.indices = indices;
  22949. vertexData.positions = positions;
  22950. vertexData.normals = normals;
  22951. vertexData.uvs = uvs;
  22952. return vertexData;
  22953. };
  22954. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22955. var indices = [];
  22956. var positions = [];
  22957. var normals = [];
  22958. var uvs = [];
  22959. var row, col;
  22960. for (row = 0; row <= subdivisions; row++) {
  22961. for (col = 0; col <= subdivisions; col++) {
  22962. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22963. // Compute height
  22964. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22965. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22966. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22967. var r = buffer[pos] / 255.0;
  22968. var g = buffer[pos + 1] / 255.0;
  22969. var b = buffer[pos + 2] / 255.0;
  22970. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22971. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22972. // Add vertex
  22973. positions.push(position.x, position.y, position.z);
  22974. normals.push(0, 0, 0);
  22975. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22976. }
  22977. }
  22978. for (row = 0; row < subdivisions; row++) {
  22979. for (col = 0; col < subdivisions; col++) {
  22980. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22981. indices.push(col + 1 + row * (subdivisions + 1));
  22982. indices.push(col + row * (subdivisions + 1));
  22983. indices.push(col + (row + 1) * (subdivisions + 1));
  22984. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22985. indices.push(col + row * (subdivisions + 1));
  22986. }
  22987. }
  22988. // Normals
  22989. VertexData.ComputeNormals(positions, indices, normals);
  22990. // Result
  22991. var vertexData = new VertexData();
  22992. vertexData.indices = indices;
  22993. vertexData.positions = positions;
  22994. vertexData.normals = normals;
  22995. vertexData.uvs = uvs;
  22996. return vertexData;
  22997. };
  22998. VertexData.CreatePlane = function (size, sideOrientation) {
  22999. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23000. var indices = [];
  23001. var positions = [];
  23002. var normals = [];
  23003. var uvs = [];
  23004. size = size || 1;
  23005. // Vertices
  23006. var halfSize = size / 2.0;
  23007. positions.push(-halfSize, -halfSize, 0);
  23008. normals.push(0, 0, -1.0);
  23009. uvs.push(0.0, 0.0);
  23010. positions.push(halfSize, -halfSize, 0);
  23011. normals.push(0, 0, -1.0);
  23012. uvs.push(1.0, 0.0);
  23013. positions.push(halfSize, halfSize, 0);
  23014. normals.push(0, 0, -1.0);
  23015. uvs.push(1.0, 1.0);
  23016. positions.push(-halfSize, halfSize, 0);
  23017. normals.push(0, 0, -1.0);
  23018. uvs.push(0.0, 1.0);
  23019. // Indices
  23020. indices.push(0);
  23021. indices.push(1);
  23022. indices.push(2);
  23023. indices.push(0);
  23024. indices.push(2);
  23025. indices.push(3);
  23026. // Sides
  23027. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23028. // Result
  23029. var vertexData = new VertexData();
  23030. vertexData.indices = indices;
  23031. vertexData.positions = positions;
  23032. vertexData.normals = normals;
  23033. vertexData.uvs = uvs;
  23034. return vertexData;
  23035. };
  23036. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  23037. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23038. var positions = [];
  23039. var indices = [];
  23040. var normals = [];
  23041. var uvs = [];
  23042. // positions and uvs
  23043. positions.push(0, 0, 0); // disc center first
  23044. uvs.push(0.5, 0.5);
  23045. var step = Math.PI * 2 / tessellation;
  23046. for (var a = 0; a < Math.PI * 2; a += step) {
  23047. var x = Math.cos(a);
  23048. var y = Math.sin(a);
  23049. var u = (x + 1) / 2;
  23050. var v = (1 - y) / 2;
  23051. positions.push(radius * x, radius * y, 0);
  23052. uvs.push(u, v);
  23053. }
  23054. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23055. uvs.push(uvs[2], uvs[3]);
  23056. //indices
  23057. var vertexNb = positions.length / 3;
  23058. for (var i = 1; i < vertexNb - 1; i++) {
  23059. indices.push(i + 1, 0, i);
  23060. }
  23061. // result
  23062. VertexData.ComputeNormals(positions, indices, normals);
  23063. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23064. var vertexData = new VertexData();
  23065. vertexData.indices = indices;
  23066. vertexData.positions = positions;
  23067. vertexData.normals = normals;
  23068. vertexData.uvs = uvs;
  23069. return vertexData;
  23070. };
  23071. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23072. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23073. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23074. var indices = [];
  23075. var positions = [];
  23076. var normals = [];
  23077. var uvs = [];
  23078. radius = radius || 2;
  23079. tube = tube || 0.5;
  23080. radialSegments = radialSegments || 32;
  23081. tubularSegments = tubularSegments || 32;
  23082. p = p || 2;
  23083. q = q || 3;
  23084. // Helper
  23085. var getPos = function (angle) {
  23086. var cu = Math.cos(angle);
  23087. var su = Math.sin(angle);
  23088. var quOverP = q / p * angle;
  23089. var cs = Math.cos(quOverP);
  23090. var tx = radius * (2 + cs) * 0.5 * cu;
  23091. var ty = radius * (2 + cs) * su * 0.5;
  23092. var tz = radius * Math.sin(quOverP) * 0.5;
  23093. return new BABYLON.Vector3(tx, ty, tz);
  23094. };
  23095. for (var i = 0; i <= radialSegments; i++) {
  23096. var modI = i % radialSegments;
  23097. var u = modI / radialSegments * 2 * p * Math.PI;
  23098. var p1 = getPos(u);
  23099. var p2 = getPos(u + 0.01);
  23100. var tang = p2.subtract(p1);
  23101. var n = p2.add(p1);
  23102. var bitan = BABYLON.Vector3.Cross(tang, n);
  23103. n = BABYLON.Vector3.Cross(bitan, tang);
  23104. bitan.normalize();
  23105. n.normalize();
  23106. for (var j = 0; j < tubularSegments; j++) {
  23107. var modJ = j % tubularSegments;
  23108. var v = modJ / tubularSegments * 2 * Math.PI;
  23109. var cx = -tube * Math.cos(v);
  23110. var cy = tube * Math.sin(v);
  23111. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23112. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23113. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23114. uvs.push(i / radialSegments);
  23115. uvs.push(j / tubularSegments);
  23116. }
  23117. }
  23118. for (i = 0; i < radialSegments; i++) {
  23119. for (j = 0; j < tubularSegments; j++) {
  23120. var jNext = (j + 1) % tubularSegments;
  23121. var a = i * tubularSegments + j;
  23122. var b = (i + 1) * tubularSegments + j;
  23123. var c = (i + 1) * tubularSegments + jNext;
  23124. var d = i * tubularSegments + jNext;
  23125. indices.push(d);
  23126. indices.push(b);
  23127. indices.push(a);
  23128. indices.push(d);
  23129. indices.push(c);
  23130. indices.push(b);
  23131. }
  23132. }
  23133. // Normals
  23134. VertexData.ComputeNormals(positions, indices, normals);
  23135. // Sides
  23136. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23137. // Result
  23138. var vertexData = new VertexData();
  23139. vertexData.indices = indices;
  23140. vertexData.positions = positions;
  23141. vertexData.normals = normals;
  23142. vertexData.uvs = uvs;
  23143. return vertexData;
  23144. };
  23145. // Tools
  23146. /**
  23147. * @param {any} - positions (number[] or Float32Array)
  23148. * @param {any} - indices (number[] or Uint16Array)
  23149. * @param {any} - normals (number[] or Float32Array)
  23150. */
  23151. VertexData.ComputeNormals = function (positions, indices, normals) {
  23152. var positionVectors = [];
  23153. var facesOfVertices = [];
  23154. var index;
  23155. for (index = 0; index < positions.length; index += 3) {
  23156. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23157. positionVectors.push(vector3);
  23158. facesOfVertices.push([]);
  23159. }
  23160. // Compute normals
  23161. var facesNormals = [];
  23162. for (index = 0; index < indices.length / 3; index++) {
  23163. var i1 = indices[index * 3];
  23164. var i2 = indices[index * 3 + 1];
  23165. var i3 = indices[index * 3 + 2];
  23166. var p1 = positionVectors[i1];
  23167. var p2 = positionVectors[i2];
  23168. var p3 = positionVectors[i3];
  23169. var p1p2 = p1.subtract(p2);
  23170. var p3p2 = p3.subtract(p2);
  23171. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23172. facesOfVertices[i1].push(index);
  23173. facesOfVertices[i2].push(index);
  23174. facesOfVertices[i3].push(index);
  23175. }
  23176. for (index = 0; index < positionVectors.length; index++) {
  23177. var faces = facesOfVertices[index];
  23178. var normal = BABYLON.Vector3.Zero();
  23179. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23180. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23181. }
  23182. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23183. normals[index * 3] = normal.x;
  23184. normals[index * 3 + 1] = normal.y;
  23185. normals[index * 3 + 2] = normal.z;
  23186. }
  23187. };
  23188. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23189. var li = indices.length;
  23190. var ln = normals.length;
  23191. var i;
  23192. var n;
  23193. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23194. switch (sideOrientation) {
  23195. case BABYLON.Mesh.FRONTSIDE:
  23196. break;
  23197. case BABYLON.Mesh.BACKSIDE:
  23198. var tmp;
  23199. for (i = 0; i < li; i += 3) {
  23200. tmp = indices[i];
  23201. indices[i] = indices[i + 2];
  23202. indices[i + 2] = tmp;
  23203. }
  23204. for (n = 0; n < ln; n++) {
  23205. normals[n] = -normals[n];
  23206. }
  23207. break;
  23208. case BABYLON.Mesh.DOUBLESIDE:
  23209. // positions
  23210. var lp = positions.length;
  23211. var l = lp / 3;
  23212. for (var p = 0; p < lp; p++) {
  23213. positions[lp + p] = positions[p];
  23214. }
  23215. for (i = 0; i < li; i += 3) {
  23216. indices[i + li] = indices[i + 2] + l;
  23217. indices[i + 1 + li] = indices[i + 1] + l;
  23218. indices[i + 2 + li] = indices[i] + l;
  23219. }
  23220. for (n = 0; n < ln; n++) {
  23221. normals[ln + n] = -normals[n];
  23222. }
  23223. // uvs
  23224. var lu = uvs.length;
  23225. for (var u = 0; u < lu; u++) {
  23226. uvs[u + lu] = uvs[u];
  23227. }
  23228. break;
  23229. }
  23230. };
  23231. return VertexData;
  23232. })();
  23233. BABYLON.VertexData = VertexData;
  23234. })(BABYLON || (BABYLON = {}));
  23235. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23236. var BABYLON;
  23237. (function (BABYLON) {
  23238. var buildCamera = function (that, name) {
  23239. that._leftCamera.isIntermediate = true;
  23240. that.subCameras.push(that._leftCamera);
  23241. that.subCameras.push(that._rightCamera);
  23242. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23243. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23244. that._anaglyphPostProcess.onApply = function (effect) {
  23245. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23246. };
  23247. that._update();
  23248. };
  23249. var AnaglyphArcRotateCamera = (function (_super) {
  23250. __extends(AnaglyphArcRotateCamera, _super);
  23251. // ANY
  23252. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23253. _super.call(this, name, alpha, beta, radius, target, scene);
  23254. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23255. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23256. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23257. buildCamera(this, name);
  23258. }
  23259. AnaglyphArcRotateCamera.prototype._update = function () {
  23260. this._updateCamera(this._leftCamera);
  23261. this._updateCamera(this._rightCamera);
  23262. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23263. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23264. _super.prototype._update.call(this);
  23265. };
  23266. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23267. camera.beta = this.beta;
  23268. camera.radius = this.radius;
  23269. camera.minZ = this.minZ;
  23270. camera.maxZ = this.maxZ;
  23271. camera.fov = this.fov;
  23272. camera.target = this.target;
  23273. };
  23274. return AnaglyphArcRotateCamera;
  23275. })(BABYLON.ArcRotateCamera);
  23276. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23277. var AnaglyphFreeCamera = (function (_super) {
  23278. __extends(AnaglyphFreeCamera, _super);
  23279. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23280. _super.call(this, name, position, scene);
  23281. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23282. this._transformMatrix = new BABYLON.Matrix();
  23283. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23284. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23285. buildCamera(this, name);
  23286. }
  23287. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23288. var target = this.getTarget();
  23289. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23290. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23291. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23292. };
  23293. AnaglyphFreeCamera.prototype._update = function () {
  23294. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23295. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23296. this._updateCamera(this._leftCamera);
  23297. this._updateCamera(this._rightCamera);
  23298. _super.prototype._update.call(this);
  23299. };
  23300. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23301. camera.minZ = this.minZ;
  23302. camera.maxZ = this.maxZ;
  23303. camera.fov = this.fov;
  23304. camera.viewport = this.viewport;
  23305. camera.setTarget(this.getTarget());
  23306. };
  23307. return AnaglyphFreeCamera;
  23308. })(BABYLON.FreeCamera);
  23309. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23310. })(BABYLON || (BABYLON = {}));
  23311. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23312. var BABYLON;
  23313. (function (BABYLON) {
  23314. var AnaglyphPostProcess = (function (_super) {
  23315. __extends(AnaglyphPostProcess, _super);
  23316. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23317. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23318. }
  23319. return AnaglyphPostProcess;
  23320. })(BABYLON.PostProcess);
  23321. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23322. })(BABYLON || (BABYLON = {}));
  23323. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23324. (function (BABYLON) {
  23325. var Tags = (function () {
  23326. function Tags() {
  23327. }
  23328. Tags.EnableFor = function (obj) {
  23329. obj._tags = obj._tags || {};
  23330. obj.hasTags = function () {
  23331. return Tags.HasTags(obj);
  23332. };
  23333. obj.addTags = function (tagsString) {
  23334. return Tags.AddTagsTo(obj, tagsString);
  23335. };
  23336. obj.removeTags = function (tagsString) {
  23337. return Tags.RemoveTagsFrom(obj, tagsString);
  23338. };
  23339. obj.matchesTagsQuery = function (tagsQuery) {
  23340. return Tags.MatchesQuery(obj, tagsQuery);
  23341. };
  23342. };
  23343. Tags.DisableFor = function (obj) {
  23344. delete obj._tags;
  23345. delete obj.hasTags;
  23346. delete obj.addTags;
  23347. delete obj.removeTags;
  23348. delete obj.matchesTagsQuery;
  23349. };
  23350. Tags.HasTags = function (obj) {
  23351. if (!obj._tags) {
  23352. return false;
  23353. }
  23354. return !BABYLON.Tools.IsEmpty(obj._tags);
  23355. };
  23356. Tags.GetTags = function (obj) {
  23357. if (!obj._tags) {
  23358. return null;
  23359. }
  23360. return obj._tags;
  23361. };
  23362. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23363. // a tag cannot start with '||', '&&', and '!'
  23364. // it cannot contain whitespaces
  23365. Tags.AddTagsTo = function (obj, tagsString) {
  23366. if (!tagsString) {
  23367. return;
  23368. }
  23369. var tags = tagsString.split(" ");
  23370. for (var t in tags) {
  23371. Tags._AddTagTo(obj, tags[t]);
  23372. }
  23373. };
  23374. Tags._AddTagTo = function (obj, tag) {
  23375. tag = tag.trim();
  23376. if (tag === "" || tag === "true" || tag === "false") {
  23377. return;
  23378. }
  23379. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23380. return;
  23381. }
  23382. Tags.EnableFor(obj);
  23383. obj._tags[tag] = true;
  23384. };
  23385. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23386. if (!Tags.HasTags(obj)) {
  23387. return;
  23388. }
  23389. var tags = tagsString.split(" ");
  23390. for (var t in tags) {
  23391. Tags._RemoveTagFrom(obj, tags[t]);
  23392. }
  23393. };
  23394. Tags._RemoveTagFrom = function (obj, tag) {
  23395. delete obj._tags[tag];
  23396. };
  23397. Tags.MatchesQuery = function (obj, tagsQuery) {
  23398. if (tagsQuery === undefined) {
  23399. return true;
  23400. }
  23401. if (tagsQuery === "") {
  23402. return Tags.HasTags(obj);
  23403. }
  23404. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23405. };
  23406. return Tags;
  23407. })();
  23408. BABYLON.Tags = Tags;
  23409. })(BABYLON || (BABYLON = {}));
  23410. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23411. (function (BABYLON) {
  23412. var Internals;
  23413. (function (Internals) {
  23414. var AndOrNotEvaluator = (function () {
  23415. function AndOrNotEvaluator() {
  23416. }
  23417. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23418. if (!query.match(/\([^\(\)]*\)/g)) {
  23419. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23420. }
  23421. else {
  23422. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23423. // remove parenthesis
  23424. r = r.slice(1, r.length - 1);
  23425. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23426. });
  23427. }
  23428. if (query === "true") {
  23429. return true;
  23430. }
  23431. if (query === "false") {
  23432. return false;
  23433. }
  23434. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23435. };
  23436. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23437. evaluateCallback = evaluateCallback || (function (r) {
  23438. return r === "true" ? true : false;
  23439. });
  23440. var result;
  23441. var or = parenthesisContent.split("||");
  23442. for (var i in or) {
  23443. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23444. var and = ori.split("&&");
  23445. if (and.length > 1) {
  23446. for (var j = 0; j < and.length; ++j) {
  23447. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23448. if (andj !== "true" && andj !== "false") {
  23449. if (andj[0] === "!") {
  23450. result = !evaluateCallback(andj.substring(1));
  23451. }
  23452. else {
  23453. result = evaluateCallback(andj);
  23454. }
  23455. }
  23456. else {
  23457. result = andj === "true" ? true : false;
  23458. }
  23459. if (!result) {
  23460. ori = "false";
  23461. break;
  23462. }
  23463. }
  23464. }
  23465. if (result || ori === "true") {
  23466. result = true;
  23467. break;
  23468. }
  23469. // result equals false (or undefined)
  23470. if (ori !== "true" && ori !== "false") {
  23471. if (ori[0] === "!") {
  23472. result = !evaluateCallback(ori.substring(1));
  23473. }
  23474. else {
  23475. result = evaluateCallback(ori);
  23476. }
  23477. }
  23478. else {
  23479. result = ori === "true" ? true : false;
  23480. }
  23481. }
  23482. // the whole parenthesis scope is replaced by 'true' or 'false'
  23483. return result ? "true" : "false";
  23484. };
  23485. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23486. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23487. // remove whitespaces
  23488. r = r.replace(/[\s]/g, function () { return ""; });
  23489. return r.length % 2 ? "!" : "";
  23490. });
  23491. booleanString = booleanString.trim();
  23492. if (booleanString === "!true") {
  23493. booleanString = "false";
  23494. }
  23495. else if (booleanString === "!false") {
  23496. booleanString = "true";
  23497. }
  23498. return booleanString;
  23499. };
  23500. return AndOrNotEvaluator;
  23501. })();
  23502. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23503. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23504. })(BABYLON || (BABYLON = {}));
  23505. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23506. (function (BABYLON) {
  23507. var PostProcessRenderPass = (function () {
  23508. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23509. this._enabled = true;
  23510. this._refCount = 0;
  23511. this._name = name;
  23512. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23513. this.setRenderList(renderList);
  23514. this._renderTexture.onBeforeRender = beforeRender;
  23515. this._renderTexture.onAfterRender = afterRender;
  23516. this._scene = scene;
  23517. this._renderList = renderList;
  23518. }
  23519. // private
  23520. PostProcessRenderPass.prototype._incRefCount = function () {
  23521. if (this._refCount === 0) {
  23522. this._scene.customRenderTargets.push(this._renderTexture);
  23523. }
  23524. return ++this._refCount;
  23525. };
  23526. PostProcessRenderPass.prototype._decRefCount = function () {
  23527. this._refCount--;
  23528. if (this._refCount <= 0) {
  23529. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23530. }
  23531. return this._refCount;
  23532. };
  23533. PostProcessRenderPass.prototype._update = function () {
  23534. this.setRenderList(this._renderList);
  23535. };
  23536. // public
  23537. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23538. this._renderTexture.renderList = renderList;
  23539. };
  23540. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23541. return this._renderTexture;
  23542. };
  23543. return PostProcessRenderPass;
  23544. })();
  23545. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23546. })(BABYLON || (BABYLON = {}));
  23547. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23548. (function (BABYLON) {
  23549. var PostProcessRenderEffect = (function () {
  23550. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23551. this._engine = engine;
  23552. this._name = name;
  23553. this._singleInstance = singleInstance || true;
  23554. this._getPostProcess = getPostProcess;
  23555. this._cameras = [];
  23556. this._indicesForCamera = [];
  23557. this._postProcesses = {};
  23558. this._renderPasses = {};
  23559. this._renderEffectAsPasses = {};
  23560. }
  23561. PostProcessRenderEffect.prototype._update = function () {
  23562. for (var renderPassName in this._renderPasses) {
  23563. this._renderPasses[renderPassName]._update();
  23564. }
  23565. };
  23566. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23567. this._renderPasses[renderPass._name] = renderPass;
  23568. this._linkParameters();
  23569. };
  23570. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23571. delete this._renderPasses[renderPass._name];
  23572. this._linkParameters();
  23573. };
  23574. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23575. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23576. this._linkParameters();
  23577. };
  23578. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23579. for (var renderPassName in this._renderPasses) {
  23580. if (renderPassName === passName) {
  23581. return this._renderPasses[passName];
  23582. }
  23583. }
  23584. };
  23585. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23586. this._renderPasses = {};
  23587. this._linkParameters();
  23588. };
  23589. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23590. var cameraKey;
  23591. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23592. for (var i = 0; i < _cam.length; i++) {
  23593. var camera = _cam[i];
  23594. var cameraName = camera.name;
  23595. if (this._singleInstance) {
  23596. cameraKey = 0;
  23597. }
  23598. else {
  23599. cameraKey = cameraName;
  23600. }
  23601. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23602. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23603. if (!this._indicesForCamera[cameraName]) {
  23604. this._indicesForCamera[cameraName] = [];
  23605. }
  23606. this._indicesForCamera[cameraName].push(index);
  23607. if (this._cameras.indexOf(camera) === -1) {
  23608. this._cameras[cameraName] = camera;
  23609. }
  23610. for (var passName in this._renderPasses) {
  23611. this._renderPasses[passName]._incRefCount();
  23612. }
  23613. }
  23614. this._linkParameters();
  23615. };
  23616. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23617. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23618. for (var i = 0; i < _cam.length; i++) {
  23619. var camera = _cam[i];
  23620. var cameraName = camera.name;
  23621. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23622. var index = this._cameras.indexOf(cameraName);
  23623. this._indicesForCamera.splice(index, 1);
  23624. this._cameras.splice(index, 1);
  23625. for (var passName in this._renderPasses) {
  23626. this._renderPasses[passName]._decRefCount();
  23627. }
  23628. }
  23629. };
  23630. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23631. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23632. for (var i = 0; i < _cam.length; i++) {
  23633. var camera = _cam[i];
  23634. var cameraName = camera.name;
  23635. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23636. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23637. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23638. }
  23639. }
  23640. for (var passName in this._renderPasses) {
  23641. this._renderPasses[passName]._incRefCount();
  23642. }
  23643. }
  23644. };
  23645. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23646. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23647. for (var i = 0; i < _cam.length; i++) {
  23648. var camera = _cam[i];
  23649. var cameraName = camera.Name;
  23650. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23651. for (var passName in this._renderPasses) {
  23652. this._renderPasses[passName]._decRefCount();
  23653. }
  23654. }
  23655. };
  23656. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23657. if (this._singleInstance) {
  23658. return this._postProcesses[0];
  23659. }
  23660. else {
  23661. return this._postProcesses[camera.name];
  23662. }
  23663. };
  23664. PostProcessRenderEffect.prototype._linkParameters = function () {
  23665. var _this = this;
  23666. for (var index in this._postProcesses) {
  23667. if (this.applyParameters) {
  23668. this.applyParameters(this._postProcesses[index]);
  23669. }
  23670. this._postProcesses[index].onBeforeRender = function (effect) {
  23671. _this._linkTextures(effect);
  23672. };
  23673. }
  23674. };
  23675. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23676. for (var renderPassName in this._renderPasses) {
  23677. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23678. }
  23679. for (var renderEffectName in this._renderEffectAsPasses) {
  23680. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23681. }
  23682. };
  23683. return PostProcessRenderEffect;
  23684. })();
  23685. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23686. })(BABYLON || (BABYLON = {}));
  23687. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23688. (function (BABYLON) {
  23689. var PostProcessRenderPipeline = (function () {
  23690. function PostProcessRenderPipeline(engine, name) {
  23691. this._engine = engine;
  23692. this._name = name;
  23693. this._renderEffects = {};
  23694. this._renderEffectsForIsolatedPass = {};
  23695. this._cameras = [];
  23696. }
  23697. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23698. this._renderEffects[renderEffect._name] = renderEffect;
  23699. };
  23700. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23701. var renderEffects = this._renderEffects[renderEffectName];
  23702. if (!renderEffects) {
  23703. return;
  23704. }
  23705. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23706. };
  23707. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23708. var renderEffects = this._renderEffects[renderEffectName];
  23709. if (!renderEffects) {
  23710. return;
  23711. }
  23712. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23713. };
  23714. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23715. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23716. var indicesToDelete = [];
  23717. for (var i = 0; i < _cam.length; i++) {
  23718. var camera = _cam[i];
  23719. var cameraName = camera.name;
  23720. if (this._cameras.indexOf(camera) === -1) {
  23721. this._cameras[cameraName] = camera;
  23722. }
  23723. else if (unique) {
  23724. indicesToDelete.push(i);
  23725. }
  23726. }
  23727. for (var i = 0; i < indicesToDelete.length; i++) {
  23728. cameras.splice(indicesToDelete[i], 1);
  23729. }
  23730. for (var renderEffectName in this._renderEffects) {
  23731. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23732. }
  23733. };
  23734. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23735. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23736. for (var renderEffectName in this._renderEffects) {
  23737. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23738. }
  23739. for (var i = 0; i < _cam.length; i++) {
  23740. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23741. }
  23742. };
  23743. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23744. var _this = this;
  23745. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23746. var pass = null;
  23747. for (var renderEffectName in this._renderEffects) {
  23748. pass = this._renderEffects[renderEffectName].getPass(passName);
  23749. if (pass != null) {
  23750. break;
  23751. }
  23752. }
  23753. if (pass === null) {
  23754. return;
  23755. }
  23756. for (var renderEffectName in this._renderEffects) {
  23757. this._renderEffects[renderEffectName]._disable(_cam);
  23758. }
  23759. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23760. for (var i = 0; i < _cam.length; i++) {
  23761. var camera = _cam[i];
  23762. var cameraName = camera.name;
  23763. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23764. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23765. });
  23766. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23767. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23768. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23769. }
  23770. };
  23771. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23772. var _this = this;
  23773. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23774. for (var i = 0; i < _cam.length; i++) {
  23775. var camera = _cam[i];
  23776. var cameraName = camera.name;
  23777. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23778. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23779. });
  23780. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23781. }
  23782. for (var renderEffectName in this._renderEffects) {
  23783. this._renderEffects[renderEffectName]._enable(_cam);
  23784. }
  23785. };
  23786. PostProcessRenderPipeline.prototype._update = function () {
  23787. for (var renderEffectName in this._renderEffects) {
  23788. this._renderEffects[renderEffectName]._update();
  23789. }
  23790. for (var i = 0; i < this._cameras.length; i++) {
  23791. var cameraName = this._cameras[i].name;
  23792. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23793. this._renderEffectsForIsolatedPass[cameraName]._update();
  23794. }
  23795. }
  23796. };
  23797. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23798. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23799. return PostProcessRenderPipeline;
  23800. })();
  23801. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23802. })(BABYLON || (BABYLON = {}));
  23803. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23804. (function (BABYLON) {
  23805. var PostProcessRenderPipelineManager = (function () {
  23806. function PostProcessRenderPipelineManager() {
  23807. this._renderPipelines = {};
  23808. }
  23809. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23810. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23811. };
  23812. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23813. var renderPipeline = this._renderPipelines[renderPipelineName];
  23814. if (!renderPipeline) {
  23815. return;
  23816. }
  23817. renderPipeline._attachCameras(cameras, unique);
  23818. };
  23819. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23820. var renderPipeline = this._renderPipelines[renderPipelineName];
  23821. if (!renderPipeline) {
  23822. return;
  23823. }
  23824. renderPipeline._detachCameras(cameras);
  23825. };
  23826. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23827. var renderPipeline = this._renderPipelines[renderPipelineName];
  23828. if (!renderPipeline) {
  23829. return;
  23830. }
  23831. renderPipeline._enableEffect(renderEffectName, cameras);
  23832. };
  23833. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23834. var renderPipeline = this._renderPipelines[renderPipelineName];
  23835. if (!renderPipeline) {
  23836. return;
  23837. }
  23838. renderPipeline._disableEffect(renderEffectName, cameras);
  23839. };
  23840. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23841. var renderPipeline = this._renderPipelines[renderPipelineName];
  23842. if (!renderPipeline) {
  23843. return;
  23844. }
  23845. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23846. };
  23847. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23848. var renderPipeline = this._renderPipelines[renderPipelineName];
  23849. if (!renderPipeline) {
  23850. return;
  23851. }
  23852. renderPipeline._disableDisplayOnlyPass(cameras);
  23853. };
  23854. PostProcessRenderPipelineManager.prototype.update = function () {
  23855. for (var renderPipelineName in this._renderPipelines) {
  23856. this._renderPipelines[renderPipelineName]._update();
  23857. }
  23858. };
  23859. return PostProcessRenderPipelineManager;
  23860. })();
  23861. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23862. })(BABYLON || (BABYLON = {}));
  23863. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23864. var BABYLON;
  23865. (function (BABYLON) {
  23866. var DisplayPassPostProcess = (function (_super) {
  23867. __extends(DisplayPassPostProcess, _super);
  23868. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23869. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23870. }
  23871. return DisplayPassPostProcess;
  23872. })(BABYLON.PostProcess);
  23873. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23874. })(BABYLON || (BABYLON = {}));
  23875. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23876. (function (BABYLON) {
  23877. var BoundingBoxRenderer = (function () {
  23878. function BoundingBoxRenderer(scene) {
  23879. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23880. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23881. this.showBackLines = true;
  23882. this.renderList = new BABYLON.SmartArray(32);
  23883. this._scene = scene;
  23884. }
  23885. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23886. if (this._colorShader) {
  23887. return;
  23888. }
  23889. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23890. attributes: ["position"],
  23891. uniforms: ["worldViewProjection", "color"]
  23892. });
  23893. var engine = this._scene.getEngine();
  23894. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23895. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23896. 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]);
  23897. };
  23898. BoundingBoxRenderer.prototype.reset = function () {
  23899. this.renderList.reset();
  23900. };
  23901. BoundingBoxRenderer.prototype.render = function () {
  23902. if (this.renderList.length === 0) {
  23903. return;
  23904. }
  23905. this._prepareRessources();
  23906. if (!this._colorShader.isReady()) {
  23907. return;
  23908. }
  23909. var engine = this._scene.getEngine();
  23910. engine.setDepthWrite(false);
  23911. this._colorShader._preBind();
  23912. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23913. var boundingBox = this.renderList.data[boundingBoxIndex];
  23914. var min = boundingBox.minimum;
  23915. var max = boundingBox.maximum;
  23916. var diff = max.subtract(min);
  23917. var median = min.add(diff.scale(0.5));
  23918. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23919. // VBOs
  23920. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23921. if (this.showBackLines) {
  23922. // Back
  23923. engine.setDepthFunctionToGreaterOrEqual();
  23924. this._scene.resetCachedMaterial();
  23925. this._colorShader.setColor4("color", this.backColor.toColor4());
  23926. this._colorShader.bind(worldMatrix);
  23927. // Draw order
  23928. engine.draw(false, 0, 24);
  23929. }
  23930. // Front
  23931. engine.setDepthFunctionToLess();
  23932. this._scene.resetCachedMaterial();
  23933. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23934. this._colorShader.bind(worldMatrix);
  23935. // Draw order
  23936. engine.draw(false, 0, 24);
  23937. }
  23938. this._colorShader.unbind();
  23939. engine.setDepthFunctionToLessOrEqual();
  23940. engine.setDepthWrite(true);
  23941. };
  23942. BoundingBoxRenderer.prototype.dispose = function () {
  23943. if (!this._colorShader) {
  23944. return;
  23945. }
  23946. this._colorShader.dispose();
  23947. this._vb.dispose();
  23948. this._scene.getEngine()._releaseBuffer(this._ib);
  23949. };
  23950. return BoundingBoxRenderer;
  23951. })();
  23952. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23953. })(BABYLON || (BABYLON = {}));
  23954. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23955. (function (BABYLON) {
  23956. var Internals;
  23957. (function (Internals) {
  23958. /*
  23959. * Based on jsTGALoader - Javascript loader for TGA file
  23960. * By Vincent Thibault
  23961. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23962. */
  23963. var TGATools = (function () {
  23964. function TGATools() {
  23965. }
  23966. TGATools.GetTGAHeader = function (data) {
  23967. var offset = 0;
  23968. var header = {
  23969. id_length: data[offset++],
  23970. colormap_type: data[offset++],
  23971. image_type: data[offset++],
  23972. colormap_index: data[offset++] | data[offset++] << 8,
  23973. colormap_length: data[offset++] | data[offset++] << 8,
  23974. colormap_size: data[offset++],
  23975. origin: [
  23976. data[offset++] | data[offset++] << 8,
  23977. data[offset++] | data[offset++] << 8
  23978. ],
  23979. width: data[offset++] | data[offset++] << 8,
  23980. height: data[offset++] | data[offset++] << 8,
  23981. pixel_size: data[offset++],
  23982. flags: data[offset++]
  23983. };
  23984. return header;
  23985. };
  23986. TGATools.UploadContent = function (gl, data) {
  23987. // Not enough data to contain header ?
  23988. if (data.length < 19) {
  23989. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23990. return;
  23991. }
  23992. // Read Header
  23993. var offset = 18;
  23994. var header = TGATools.GetTGAHeader(data);
  23995. // Assume it's a valid Targa file.
  23996. if (header.id_length + offset > data.length) {
  23997. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23998. return;
  23999. }
  24000. // Skip not needed data
  24001. offset += header.id_length;
  24002. var use_rle = false;
  24003. var use_pal = false;
  24004. var use_rgb = false;
  24005. var use_grey = false;
  24006. switch (header.image_type) {
  24007. case TGATools._TYPE_RLE_INDEXED:
  24008. use_rle = true;
  24009. case TGATools._TYPE_INDEXED:
  24010. use_pal = true;
  24011. break;
  24012. case TGATools._TYPE_RLE_RGB:
  24013. use_rle = true;
  24014. case TGATools._TYPE_RGB:
  24015. use_rgb = true;
  24016. break;
  24017. case TGATools._TYPE_RLE_GREY:
  24018. use_rle = true;
  24019. case TGATools._TYPE_GREY:
  24020. use_grey = true;
  24021. break;
  24022. }
  24023. var pixel_data;
  24024. var numAlphaBits = header.flags & 0xf;
  24025. var pixel_size = header.pixel_size >> 3;
  24026. var pixel_total = header.width * header.height * pixel_size;
  24027. // Read palettes
  24028. var palettes;
  24029. if (use_pal) {
  24030. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  24031. }
  24032. // Read LRE
  24033. if (use_rle) {
  24034. pixel_data = new Uint8Array(pixel_total);
  24035. var c, count, i;
  24036. var localOffset = 0;
  24037. var pixels = new Uint8Array(pixel_size);
  24038. while (offset < pixel_total && localOffset < pixel_total) {
  24039. c = data[offset++];
  24040. count = (c & 0x7f) + 1;
  24041. // RLE pixels
  24042. if (c & 0x80) {
  24043. for (i = 0; i < pixel_size; ++i) {
  24044. pixels[i] = data[offset++];
  24045. }
  24046. for (i = 0; i < count; ++i) {
  24047. pixel_data.set(pixels, localOffset + i * pixel_size);
  24048. }
  24049. localOffset += pixel_size * count;
  24050. }
  24051. else {
  24052. count *= pixel_size;
  24053. for (i = 0; i < count; ++i) {
  24054. pixel_data[localOffset + i] = data[offset++];
  24055. }
  24056. localOffset += count;
  24057. }
  24058. }
  24059. }
  24060. else {
  24061. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  24062. }
  24063. // Load to texture
  24064. var x_start, y_start, x_step, y_step, y_end, x_end;
  24065. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24066. default:
  24067. case TGATools._ORIGIN_UL:
  24068. x_start = 0;
  24069. x_step = 1;
  24070. x_end = header.width;
  24071. y_start = 0;
  24072. y_step = 1;
  24073. y_end = header.height;
  24074. break;
  24075. case TGATools._ORIGIN_BL:
  24076. x_start = 0;
  24077. x_step = 1;
  24078. x_end = header.width;
  24079. y_start = header.height - 1;
  24080. y_step = -1;
  24081. y_end = -1;
  24082. break;
  24083. case TGATools._ORIGIN_UR:
  24084. x_start = header.width - 1;
  24085. x_step = -1;
  24086. x_end = -1;
  24087. y_start = 0;
  24088. y_step = 1;
  24089. y_end = header.height;
  24090. break;
  24091. case TGATools._ORIGIN_BR:
  24092. x_start = header.width - 1;
  24093. x_step = -1;
  24094. x_end = -1;
  24095. y_start = header.height - 1;
  24096. y_step = -1;
  24097. y_end = -1;
  24098. break;
  24099. }
  24100. // Load the specify method
  24101. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24102. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24103. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24104. };
  24105. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24106. var image = pixel_data, colormap = palettes;
  24107. var width = header.width, height = header.height;
  24108. var color, i = 0, x, y;
  24109. var imageData = new Uint8Array(width * height * 4);
  24110. for (y = y_start; y !== y_end; y += y_step) {
  24111. for (x = x_start; x !== x_end; x += x_step, i++) {
  24112. color = image[i];
  24113. imageData[(x + width * y) * 4 + 3] = 255;
  24114. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24115. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24116. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24117. }
  24118. }
  24119. return imageData;
  24120. };
  24121. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24122. var image = pixel_data;
  24123. var width = header.width, height = header.height;
  24124. var color, i = 0, x, y;
  24125. var imageData = new Uint8Array(width * height * 4);
  24126. for (y = y_start; y !== y_end; y += y_step) {
  24127. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24128. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24129. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24130. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24131. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24132. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24133. }
  24134. }
  24135. return imageData;
  24136. };
  24137. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24138. var image = pixel_data;
  24139. var width = header.width, height = header.height;
  24140. var i = 0, x, y;
  24141. var imageData = new Uint8Array(width * height * 4);
  24142. for (y = y_start; y !== y_end; y += y_step) {
  24143. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24144. imageData[(x + width * y) * 4 + 3] = 255;
  24145. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24146. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24147. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24148. }
  24149. }
  24150. return imageData;
  24151. };
  24152. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24153. var image = pixel_data;
  24154. var width = header.width, height = header.height;
  24155. var i = 0, x, y;
  24156. var imageData = new Uint8Array(width * height * 4);
  24157. for (y = y_start; y !== y_end; y += y_step) {
  24158. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24159. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24160. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24161. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24162. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24163. }
  24164. }
  24165. return imageData;
  24166. };
  24167. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24168. var image = pixel_data;
  24169. var width = header.width, height = header.height;
  24170. var color, i = 0, x, y;
  24171. var imageData = new Uint8Array(width * height * 4);
  24172. for (y = y_start; y !== y_end; y += y_step) {
  24173. for (x = x_start; x !== x_end; x += x_step, i++) {
  24174. color = image[i];
  24175. imageData[(x + width * y) * 4 + 0] = color;
  24176. imageData[(x + width * y) * 4 + 1] = color;
  24177. imageData[(x + width * y) * 4 + 2] = color;
  24178. imageData[(x + width * y) * 4 + 3] = 255;
  24179. }
  24180. }
  24181. return imageData;
  24182. };
  24183. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24184. var image = pixel_data;
  24185. var width = header.width, height = header.height;
  24186. var i = 0, x, y;
  24187. var imageData = new Uint8Array(width * height * 4);
  24188. for (y = y_start; y !== y_end; y += y_step) {
  24189. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24190. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24191. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24192. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24193. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24194. }
  24195. }
  24196. return imageData;
  24197. };
  24198. TGATools._TYPE_NO_DATA = 0;
  24199. TGATools._TYPE_INDEXED = 1;
  24200. TGATools._TYPE_RGB = 2;
  24201. TGATools._TYPE_GREY = 3;
  24202. TGATools._TYPE_RLE_INDEXED = 9;
  24203. TGATools._TYPE_RLE_RGB = 10;
  24204. TGATools._TYPE_RLE_GREY = 11;
  24205. TGATools._ORIGIN_MASK = 0x30;
  24206. TGATools._ORIGIN_SHIFT = 0x04;
  24207. TGATools._ORIGIN_BL = 0x00;
  24208. TGATools._ORIGIN_BR = 0x01;
  24209. TGATools._ORIGIN_UL = 0x02;
  24210. TGATools._ORIGIN_UR = 0x03;
  24211. return TGATools;
  24212. })();
  24213. Internals.TGATools = TGATools;
  24214. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24215. })(BABYLON || (BABYLON = {}));
  24216. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24217. (function (BABYLON) {
  24218. var Internals;
  24219. (function (Internals) {
  24220. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24221. // All values and structures referenced from:
  24222. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24223. var DDS_MAGIC = 0x20534444;
  24224. 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;
  24225. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24226. 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;
  24227. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24228. function FourCCToInt32(value) {
  24229. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24230. }
  24231. function Int32ToFourCC(value) {
  24232. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24233. }
  24234. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24235. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24236. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24237. var headerLengthInt = 31; // The header length in 32 bit ints
  24238. // Offsets into the header array
  24239. var off_magic = 0;
  24240. var off_size = 1;
  24241. var off_flags = 2;
  24242. var off_height = 3;
  24243. var off_width = 4;
  24244. var off_mipmapCount = 7;
  24245. var off_pfFlags = 20;
  24246. var off_pfFourCC = 21;
  24247. var off_RGBbpp = 22;
  24248. var off_RMask = 23;
  24249. var off_GMask = 24;
  24250. var off_BMask = 25;
  24251. var off_AMask = 26;
  24252. var off_caps1 = 27;
  24253. var off_caps2 = 28;
  24254. ;
  24255. var DDSTools = (function () {
  24256. function DDSTools() {
  24257. }
  24258. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24259. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24260. var mipmapCount = 1;
  24261. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24262. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24263. }
  24264. return {
  24265. width: header[off_width],
  24266. height: header[off_height],
  24267. mipmapCount: mipmapCount,
  24268. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24269. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24270. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24271. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24272. };
  24273. };
  24274. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24275. var byteArray = new Uint8Array(dataLength);
  24276. var srcData = new Uint8Array(arrayBuffer);
  24277. var index = 0;
  24278. for (var y = height - 1; y >= 0; y--) {
  24279. for (var x = 0; x < width; x++) {
  24280. var srcPos = dataOffset + (x + y * width) * 4;
  24281. byteArray[index + 2] = srcData[srcPos];
  24282. byteArray[index + 1] = srcData[srcPos + 1];
  24283. byteArray[index] = srcData[srcPos + 2];
  24284. byteArray[index + 3] = srcData[srcPos + 3];
  24285. index += 4;
  24286. }
  24287. }
  24288. return byteArray;
  24289. };
  24290. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24291. var byteArray = new Uint8Array(dataLength);
  24292. var srcData = new Uint8Array(arrayBuffer);
  24293. var index = 0;
  24294. for (var y = height - 1; y >= 0; y--) {
  24295. for (var x = 0; x < width; x++) {
  24296. var srcPos = dataOffset + (x + y * width) * 3;
  24297. byteArray[index + 2] = srcData[srcPos];
  24298. byteArray[index + 1] = srcData[srcPos + 1];
  24299. byteArray[index] = srcData[srcPos + 2];
  24300. index += 3;
  24301. }
  24302. }
  24303. return byteArray;
  24304. };
  24305. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24306. var byteArray = new Uint8Array(dataLength);
  24307. var srcData = new Uint8Array(arrayBuffer);
  24308. var index = 0;
  24309. for (var y = height - 1; y >= 0; y--) {
  24310. for (var x = 0; x < width; x++) {
  24311. var srcPos = dataOffset + (x + y * width);
  24312. byteArray[index] = srcData[srcPos];
  24313. index++;
  24314. }
  24315. }
  24316. return byteArray;
  24317. };
  24318. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24319. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24320. if (header[off_magic] != DDS_MAGIC) {
  24321. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24322. return;
  24323. }
  24324. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24325. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24326. return;
  24327. }
  24328. if (info.isFourCC) {
  24329. fourCC = header[off_pfFourCC];
  24330. switch (fourCC) {
  24331. case FOURCC_DXT1:
  24332. blockBytes = 8;
  24333. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24334. break;
  24335. case FOURCC_DXT3:
  24336. blockBytes = 16;
  24337. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24338. break;
  24339. case FOURCC_DXT5:
  24340. blockBytes = 16;
  24341. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24342. break;
  24343. default:
  24344. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24345. return;
  24346. }
  24347. }
  24348. mipmapCount = 1;
  24349. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24350. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24351. }
  24352. var bpp = header[off_RGBbpp];
  24353. for (var face = 0; face < faces; face++) {
  24354. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24355. width = header[off_width];
  24356. height = header[off_height];
  24357. dataOffset = header[off_size] + 4;
  24358. for (i = 0; i < mipmapCount; ++i) {
  24359. if (info.isRGB) {
  24360. if (bpp == 24) {
  24361. dataLength = width * height * 3;
  24362. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24363. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24364. }
  24365. else {
  24366. dataLength = width * height * 4;
  24367. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24368. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24369. }
  24370. }
  24371. else if (info.isLuminance) {
  24372. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24373. var unpaddedRowSize = width;
  24374. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24375. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24376. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24377. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24378. }
  24379. else {
  24380. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24381. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24382. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24383. }
  24384. dataOffset += dataLength;
  24385. width *= 0.5;
  24386. height *= 0.5;
  24387. width = Math.max(1.0, width);
  24388. height = Math.max(1.0, height);
  24389. }
  24390. }
  24391. };
  24392. return DDSTools;
  24393. })();
  24394. Internals.DDSTools = DDSTools;
  24395. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24396. })(BABYLON || (BABYLON = {}));
  24397. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24398. (function (BABYLON) {
  24399. var SmartArray = (function () {
  24400. function SmartArray(capacity) {
  24401. this.length = 0;
  24402. this._duplicateId = 0;
  24403. this.data = new Array(capacity);
  24404. this._id = SmartArray._GlobalId++;
  24405. }
  24406. SmartArray.prototype.push = function (value) {
  24407. this.data[this.length++] = value;
  24408. if (this.length > this.data.length) {
  24409. this.data.length *= 2;
  24410. }
  24411. if (!value.__smartArrayFlags) {
  24412. value.__smartArrayFlags = {};
  24413. }
  24414. value.__smartArrayFlags[this._id] = this._duplicateId;
  24415. };
  24416. SmartArray.prototype.pushNoDuplicate = function (value) {
  24417. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24418. return;
  24419. }
  24420. this.push(value);
  24421. };
  24422. SmartArray.prototype.sort = function (compareFn) {
  24423. this.data.sort(compareFn);
  24424. };
  24425. SmartArray.prototype.reset = function () {
  24426. this.length = 0;
  24427. this._duplicateId++;
  24428. };
  24429. SmartArray.prototype.concat = function (array) {
  24430. if (array.length === 0) {
  24431. return;
  24432. }
  24433. if (this.length + array.length > this.data.length) {
  24434. this.data.length = (this.length + array.length) * 2;
  24435. }
  24436. for (var index = 0; index < array.length; index++) {
  24437. this.data[this.length++] = (array.data || array)[index];
  24438. }
  24439. };
  24440. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24441. if (array.length === 0) {
  24442. return;
  24443. }
  24444. if (this.length + array.length > this.data.length) {
  24445. this.data.length = (this.length + array.length) * 2;
  24446. }
  24447. for (var index = 0; index < array.length; index++) {
  24448. var item = (array.data || array)[index];
  24449. this.pushNoDuplicate(item);
  24450. }
  24451. };
  24452. SmartArray.prototype.indexOf = function (value) {
  24453. var position = this.data.indexOf(value);
  24454. if (position >= this.length) {
  24455. return -1;
  24456. }
  24457. return position;
  24458. };
  24459. // Statics
  24460. SmartArray._GlobalId = 0;
  24461. return SmartArray;
  24462. })();
  24463. BABYLON.SmartArray = SmartArray;
  24464. })(BABYLON || (BABYLON = {}));
  24465. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24466. (function (BABYLON) {
  24467. var CannonJSPlugin = (function () {
  24468. function CannonJSPlugin() {
  24469. this._registeredMeshes = [];
  24470. this._physicsMaterials = [];
  24471. this.updateBodyPosition = function (mesh) {
  24472. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24473. var registeredMesh = this._registeredMeshes[index];
  24474. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24475. var body = registeredMesh.body;
  24476. var center = mesh.getBoundingInfo().boundingBox.center;
  24477. body.position.set(center.x, center.z, center.y);
  24478. body.quaternion.x = mesh.rotationQuaternion.x;
  24479. body.quaternion.z = mesh.rotationQuaternion.y;
  24480. body.quaternion.y = mesh.rotationQuaternion.z;
  24481. body.quaternion.w = -mesh.rotationQuaternion.w;
  24482. return;
  24483. }
  24484. }
  24485. };
  24486. }
  24487. CannonJSPlugin.prototype.initialize = function (iterations) {
  24488. if (iterations === void 0) { iterations = 10; }
  24489. this._world = new CANNON.World();
  24490. this._world.broadphase = new CANNON.NaiveBroadphase();
  24491. this._world.solver.iterations = iterations;
  24492. };
  24493. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24494. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24495. };
  24496. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24497. this._world.step(delta);
  24498. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24499. var registeredMesh = this._registeredMeshes[index];
  24500. if (registeredMesh.isChild) {
  24501. continue;
  24502. }
  24503. // Body position
  24504. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24505. var deltaPos = registeredMesh.delta;
  24506. if (deltaPos) {
  24507. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24508. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24509. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24510. }
  24511. else {
  24512. registeredMesh.mesh.position.x = bodyX;
  24513. registeredMesh.mesh.position.y = bodyZ;
  24514. registeredMesh.mesh.position.z = bodyY;
  24515. }
  24516. if (!registeredMesh.mesh.rotationQuaternion) {
  24517. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24518. }
  24519. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24520. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24521. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24522. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24523. }
  24524. };
  24525. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24526. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24527. };
  24528. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24529. this.unregisterMesh(mesh);
  24530. mesh.computeWorldMatrix(true);
  24531. switch (impostor) {
  24532. case BABYLON.PhysicsEngine.SphereImpostor:
  24533. var bbox = mesh.getBoundingInfo().boundingBox;
  24534. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24535. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24536. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24537. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24538. case BABYLON.PhysicsEngine.BoxImpostor:
  24539. bbox = mesh.getBoundingInfo().boundingBox;
  24540. var min = bbox.minimumWorld;
  24541. var max = bbox.maximumWorld;
  24542. var box = max.subtract(min).scale(0.5);
  24543. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24544. case BABYLON.PhysicsEngine.PlaneImpostor:
  24545. return this._createPlane(mesh, options);
  24546. case BABYLON.PhysicsEngine.MeshImpostor:
  24547. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24548. var rawFaces = mesh.getIndices();
  24549. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24550. }
  24551. return null;
  24552. };
  24553. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24554. var shape = new CANNON.Sphere(radius);
  24555. if (!options) {
  24556. return shape;
  24557. }
  24558. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24559. };
  24560. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24561. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24562. if (!options) {
  24563. return shape;
  24564. }
  24565. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24566. };
  24567. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24568. var shape = new CANNON.Plane();
  24569. if (!options) {
  24570. return shape;
  24571. }
  24572. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24573. };
  24574. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24575. var verts = [], faces = [];
  24576. mesh.computeWorldMatrix(true);
  24577. for (var i = 0; i < rawVerts.length; i += 3) {
  24578. var transformed = BABYLON.Vector3.Zero();
  24579. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24580. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24581. }
  24582. for (var j = 0; j < rawFaces.length; j += 3) {
  24583. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24584. }
  24585. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24586. if (!options) {
  24587. return shape;
  24588. }
  24589. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24590. };
  24591. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24592. var index;
  24593. var mat;
  24594. for (index = 0; index < this._physicsMaterials.length; index++) {
  24595. mat = this._physicsMaterials[index];
  24596. if (mat.friction === friction && mat.restitution === restitution) {
  24597. return mat;
  24598. }
  24599. }
  24600. var currentMat = new CANNON.Material();
  24601. currentMat.friction = friction;
  24602. currentMat.restitution = restitution;
  24603. this._physicsMaterials.push(currentMat);
  24604. for (index = 0; index < this._physicsMaterials.length; index++) {
  24605. mat = this._physicsMaterials[index];
  24606. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24607. contactMaterial.contactEquationStiffness = 1e10;
  24608. contactMaterial.contactEquationRegularizationTime = 10;
  24609. this._world.addContactMaterial(contactMaterial);
  24610. }
  24611. return currentMat;
  24612. };
  24613. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24614. var initialRotation = null;
  24615. if (mesh.rotationQuaternion) {
  24616. initialRotation = mesh.rotationQuaternion.clone();
  24617. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24618. }
  24619. // The delta between the mesh position and the mesh bounding box center
  24620. var bbox = mesh.getBoundingInfo().boundingBox;
  24621. var deltaPosition = mesh.position.subtract(bbox.center);
  24622. var material = this._addMaterial(friction, restitution);
  24623. var body = new CANNON.RigidBody(mass, shape, material);
  24624. if (initialRotation) {
  24625. body.quaternion.x = initialRotation.x;
  24626. body.quaternion.z = initialRotation.y;
  24627. body.quaternion.y = initialRotation.z;
  24628. body.quaternion.w = -initialRotation.w;
  24629. }
  24630. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24631. this._world.add(body);
  24632. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24633. return body;
  24634. };
  24635. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24636. var compoundShape = new CANNON.Compound();
  24637. for (var index = 0; index < parts.length; index++) {
  24638. var mesh = parts[index].mesh;
  24639. var shape = this.registerMesh(mesh, parts[index].impostor);
  24640. if (index == 0) {
  24641. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24642. }
  24643. else {
  24644. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24645. }
  24646. }
  24647. var initialMesh = parts[0].mesh;
  24648. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24649. body.parts = parts;
  24650. return body;
  24651. };
  24652. CannonJSPlugin.prototype._unbindBody = function (body) {
  24653. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24654. var registeredMesh = this._registeredMeshes[index];
  24655. if (registeredMesh.body === body) {
  24656. registeredMesh.body = null;
  24657. registeredMesh.delta = 0;
  24658. }
  24659. }
  24660. };
  24661. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24662. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24663. var registeredMesh = this._registeredMeshes[index];
  24664. if (registeredMesh.mesh === mesh) {
  24665. // Remove body
  24666. if (registeredMesh.body) {
  24667. this._world.remove(registeredMesh.body);
  24668. this._unbindBody(registeredMesh.body);
  24669. }
  24670. this._registeredMeshes.splice(index, 1);
  24671. return;
  24672. }
  24673. }
  24674. };
  24675. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24676. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24677. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24678. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24679. var registeredMesh = this._registeredMeshes[index];
  24680. if (registeredMesh.mesh === mesh) {
  24681. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24682. return;
  24683. }
  24684. }
  24685. };
  24686. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24687. var body1 = null, body2 = null;
  24688. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24689. var registeredMesh = this._registeredMeshes[index];
  24690. if (registeredMesh.mesh === mesh1) {
  24691. body1 = registeredMesh.body;
  24692. }
  24693. else if (registeredMesh.mesh === mesh2) {
  24694. body2 = registeredMesh.body;
  24695. }
  24696. }
  24697. if (!body1 || !body2) {
  24698. return false;
  24699. }
  24700. 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));
  24701. this._world.addConstraint(constraint);
  24702. return true;
  24703. };
  24704. CannonJSPlugin.prototype.dispose = function () {
  24705. while (this._registeredMeshes.length) {
  24706. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24707. }
  24708. };
  24709. CannonJSPlugin.prototype.isSupported = function () {
  24710. return window.CANNON !== undefined;
  24711. };
  24712. return CannonJSPlugin;
  24713. })();
  24714. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24715. })(BABYLON || (BABYLON = {}));
  24716. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24717. var BABYLON;
  24718. (function (BABYLON) {
  24719. var Condition = (function () {
  24720. function Condition(actionManager) {
  24721. this._actionManager = actionManager;
  24722. }
  24723. Condition.prototype.isValid = function () {
  24724. return true;
  24725. };
  24726. Condition.prototype._getProperty = function (propertyPath) {
  24727. return this._actionManager._getProperty(propertyPath);
  24728. };
  24729. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24730. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24731. };
  24732. return Condition;
  24733. })();
  24734. BABYLON.Condition = Condition;
  24735. var ValueCondition = (function (_super) {
  24736. __extends(ValueCondition, _super);
  24737. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24738. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24739. _super.call(this, actionManager);
  24740. this.propertyPath = propertyPath;
  24741. this.value = value;
  24742. this.operator = operator;
  24743. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24744. this._property = this._getProperty(this.propertyPath);
  24745. }
  24746. Object.defineProperty(ValueCondition, "IsEqual", {
  24747. get: function () {
  24748. return ValueCondition._IsEqual;
  24749. },
  24750. enumerable: true,
  24751. configurable: true
  24752. });
  24753. Object.defineProperty(ValueCondition, "IsDifferent", {
  24754. get: function () {
  24755. return ValueCondition._IsDifferent;
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(ValueCondition, "IsGreater", {
  24761. get: function () {
  24762. return ValueCondition._IsGreater;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(ValueCondition, "IsLesser", {
  24768. get: function () {
  24769. return ValueCondition._IsLesser;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. // Methods
  24775. ValueCondition.prototype.isValid = function () {
  24776. switch (this.operator) {
  24777. case ValueCondition.IsGreater:
  24778. return this._target[this._property] > this.value;
  24779. case ValueCondition.IsLesser:
  24780. return this._target[this._property] < this.value;
  24781. case ValueCondition.IsEqual:
  24782. case ValueCondition.IsDifferent:
  24783. var check;
  24784. if (this.value.equals) {
  24785. check = this.value.equals(this._target[this._property]);
  24786. }
  24787. else {
  24788. check = this.value === this._target[this._property];
  24789. }
  24790. return this.operator === ValueCondition.IsEqual ? check : !check;
  24791. }
  24792. return false;
  24793. };
  24794. // Statics
  24795. ValueCondition._IsEqual = 0;
  24796. ValueCondition._IsDifferent = 1;
  24797. ValueCondition._IsGreater = 2;
  24798. ValueCondition._IsLesser = 3;
  24799. return ValueCondition;
  24800. })(Condition);
  24801. BABYLON.ValueCondition = ValueCondition;
  24802. var PredicateCondition = (function (_super) {
  24803. __extends(PredicateCondition, _super);
  24804. function PredicateCondition(actionManager, predicate) {
  24805. _super.call(this, actionManager);
  24806. this.predicate = predicate;
  24807. }
  24808. PredicateCondition.prototype.isValid = function () {
  24809. return this.predicate();
  24810. };
  24811. return PredicateCondition;
  24812. })(Condition);
  24813. BABYLON.PredicateCondition = PredicateCondition;
  24814. var StateCondition = (function (_super) {
  24815. __extends(StateCondition, _super);
  24816. function StateCondition(actionManager, target, value) {
  24817. _super.call(this, actionManager);
  24818. this.value = value;
  24819. this._target = target;
  24820. }
  24821. // Methods
  24822. StateCondition.prototype.isValid = function () {
  24823. return this._target.state === this.value;
  24824. };
  24825. return StateCondition;
  24826. })(Condition);
  24827. BABYLON.StateCondition = StateCondition;
  24828. })(BABYLON || (BABYLON = {}));
  24829. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24830. (function (BABYLON) {
  24831. var Action = (function () {
  24832. function Action(triggerOptions, condition) {
  24833. this.triggerOptions = triggerOptions;
  24834. if (triggerOptions.parameter) {
  24835. this.trigger = triggerOptions.trigger;
  24836. this._triggerParameter = triggerOptions.parameter;
  24837. }
  24838. else {
  24839. this.trigger = triggerOptions;
  24840. }
  24841. this._nextActiveAction = this;
  24842. this._condition = condition;
  24843. }
  24844. // Methods
  24845. Action.prototype._prepare = function () {
  24846. };
  24847. Action.prototype.getTriggerParameter = function () {
  24848. return this._triggerParameter;
  24849. };
  24850. Action.prototype._executeCurrent = function (evt) {
  24851. if (this._nextActiveAction._condition) {
  24852. var condition = this._nextActiveAction._condition;
  24853. var currentRenderId = this._actionManager.getScene().getRenderId();
  24854. // We cache the current evaluation for the current frame
  24855. if (condition._evaluationId === currentRenderId) {
  24856. if (!condition._currentResult) {
  24857. return;
  24858. }
  24859. }
  24860. else {
  24861. condition._evaluationId = currentRenderId;
  24862. if (!condition.isValid()) {
  24863. condition._currentResult = false;
  24864. return;
  24865. }
  24866. condition._currentResult = true;
  24867. }
  24868. }
  24869. this._nextActiveAction.execute(evt);
  24870. if (this._nextActiveAction._child) {
  24871. if (!this._nextActiveAction._child._actionManager) {
  24872. this._nextActiveAction._child._actionManager = this._actionManager;
  24873. }
  24874. this._nextActiveAction = this._nextActiveAction._child;
  24875. }
  24876. else {
  24877. this._nextActiveAction = this;
  24878. }
  24879. };
  24880. Action.prototype.execute = function (evt) {
  24881. };
  24882. Action.prototype.then = function (action) {
  24883. this._child = action;
  24884. action._actionManager = this._actionManager;
  24885. action._prepare();
  24886. return action;
  24887. };
  24888. Action.prototype._getProperty = function (propertyPath) {
  24889. return this._actionManager._getProperty(propertyPath);
  24890. };
  24891. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24892. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24893. };
  24894. return Action;
  24895. })();
  24896. BABYLON.Action = Action;
  24897. })(BABYLON || (BABYLON = {}));
  24898. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24899. (function (BABYLON) {
  24900. /**
  24901. * ActionEvent is the event beint sent when an action is triggered.
  24902. */
  24903. var ActionEvent = (function () {
  24904. /**
  24905. * @constructor
  24906. * @param source The mesh that triggered the action.
  24907. * @param pointerX the X mouse cursor position at the time of the event
  24908. * @param pointerY the Y mouse cursor position at the time of the event
  24909. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24910. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24911. */
  24912. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24913. this.source = source;
  24914. this.pointerX = pointerX;
  24915. this.pointerY = pointerY;
  24916. this.meshUnderPointer = meshUnderPointer;
  24917. this.sourceEvent = sourceEvent;
  24918. }
  24919. /**
  24920. * Helper function to auto-create an ActionEvent from a source mesh.
  24921. * @param source the source mesh that triggered the event
  24922. * @param evt {Event} The original (browser) event
  24923. */
  24924. ActionEvent.CreateNew = function (source, evt) {
  24925. var scene = source.getScene();
  24926. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24927. };
  24928. /**
  24929. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24930. * @param scene the scene where the event occurred
  24931. * @param evt {Event} The original (browser) event
  24932. */
  24933. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24934. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24935. };
  24936. return ActionEvent;
  24937. })();
  24938. BABYLON.ActionEvent = ActionEvent;
  24939. /**
  24940. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24941. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24942. */
  24943. var ActionManager = (function () {
  24944. function ActionManager(scene) {
  24945. // Members
  24946. this.actions = new Array();
  24947. this._scene = scene;
  24948. scene._actionManagers.push(this);
  24949. }
  24950. Object.defineProperty(ActionManager, "NothingTrigger", {
  24951. get: function () {
  24952. return ActionManager._NothingTrigger;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24958. get: function () {
  24959. return ActionManager._OnPickTrigger;
  24960. },
  24961. enumerable: true,
  24962. configurable: true
  24963. });
  24964. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24965. get: function () {
  24966. return ActionManager._OnLeftPickTrigger;
  24967. },
  24968. enumerable: true,
  24969. configurable: true
  24970. });
  24971. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24972. get: function () {
  24973. return ActionManager._OnRightPickTrigger;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24979. get: function () {
  24980. return ActionManager._OnCenterPickTrigger;
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24986. get: function () {
  24987. return ActionManager._OnPointerOverTrigger;
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24993. get: function () {
  24994. return ActionManager._OnPointerOutTrigger;
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25000. get: function () {
  25001. return ActionManager._OnEveryFrameTrigger;
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25007. get: function () {
  25008. return ActionManager._OnIntersectionEnterTrigger;
  25009. },
  25010. enumerable: true,
  25011. configurable: true
  25012. });
  25013. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25014. get: function () {
  25015. return ActionManager._OnIntersectionExitTrigger;
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25021. get: function () {
  25022. return ActionManager._OnKeyDownTrigger;
  25023. },
  25024. enumerable: true,
  25025. configurable: true
  25026. });
  25027. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25028. get: function () {
  25029. return ActionManager._OnKeyUpTrigger;
  25030. },
  25031. enumerable: true,
  25032. configurable: true
  25033. });
  25034. // Methods
  25035. ActionManager.prototype.dispose = function () {
  25036. var index = this._scene._actionManagers.indexOf(this);
  25037. if (index > -1) {
  25038. this._scene._actionManagers.splice(index, 1);
  25039. }
  25040. };
  25041. ActionManager.prototype.getScene = function () {
  25042. return this._scene;
  25043. };
  25044. /**
  25045. * Does this action manager handles actions of any of the given triggers
  25046. * @param {number[]} triggers - the triggers to be tested
  25047. * @return {boolean} whether one (or more) of the triggers is handeled
  25048. */
  25049. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25050. for (var index = 0; index < this.actions.length; index++) {
  25051. var action = this.actions[index];
  25052. if (triggers.indexOf(action.trigger) > -1) {
  25053. return true;
  25054. }
  25055. }
  25056. return false;
  25057. };
  25058. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25059. /**
  25060. * Does this action manager has pointer triggers
  25061. * @return {boolean} whether or not it has pointer triggers
  25062. */
  25063. get: function () {
  25064. for (var index = 0; index < this.actions.length; index++) {
  25065. var action = this.actions[index];
  25066. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25067. return true;
  25068. }
  25069. }
  25070. return false;
  25071. },
  25072. enumerable: true,
  25073. configurable: true
  25074. });
  25075. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25076. /**
  25077. * Does this action manager has pick triggers
  25078. * @return {boolean} whether or not it has pick triggers
  25079. */
  25080. get: function () {
  25081. for (var index = 0; index < this.actions.length; index++) {
  25082. var action = this.actions[index];
  25083. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25084. return true;
  25085. }
  25086. }
  25087. return false;
  25088. },
  25089. enumerable: true,
  25090. configurable: true
  25091. });
  25092. /**
  25093. * Registers an action to this action manager
  25094. * @param {BABYLON.Action} action - the action to be registered
  25095. * @return {BABYLON.Action} the action amended (prepared) after registration
  25096. */
  25097. ActionManager.prototype.registerAction = function (action) {
  25098. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25099. if (this.getScene().actionManager !== this) {
  25100. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25101. return null;
  25102. }
  25103. }
  25104. this.actions.push(action);
  25105. action._actionManager = this;
  25106. action._prepare();
  25107. return action;
  25108. };
  25109. /**
  25110. * Process a specific trigger
  25111. * @param {number} trigger - the trigger to process
  25112. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25113. */
  25114. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25115. for (var index = 0; index < this.actions.length; index++) {
  25116. var action = this.actions[index];
  25117. if (action.trigger === trigger) {
  25118. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25119. var parameter = action.getTriggerParameter();
  25120. if (parameter) {
  25121. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25122. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25123. if (actualkey !== parameter.toLowerCase()) {
  25124. continue;
  25125. }
  25126. }
  25127. }
  25128. action._executeCurrent(evt);
  25129. }
  25130. }
  25131. };
  25132. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25133. var properties = propertyPath.split(".");
  25134. for (var index = 0; index < properties.length - 1; index++) {
  25135. target = target[properties[index]];
  25136. }
  25137. return target;
  25138. };
  25139. ActionManager.prototype._getProperty = function (propertyPath) {
  25140. var properties = propertyPath.split(".");
  25141. return properties[properties.length - 1];
  25142. };
  25143. // Statics
  25144. ActionManager._NothingTrigger = 0;
  25145. ActionManager._OnPickTrigger = 1;
  25146. ActionManager._OnLeftPickTrigger = 2;
  25147. ActionManager._OnRightPickTrigger = 3;
  25148. ActionManager._OnCenterPickTrigger = 4;
  25149. ActionManager._OnPointerOverTrigger = 5;
  25150. ActionManager._OnPointerOutTrigger = 6;
  25151. ActionManager._OnEveryFrameTrigger = 7;
  25152. ActionManager._OnIntersectionEnterTrigger = 8;
  25153. ActionManager._OnIntersectionExitTrigger = 9;
  25154. ActionManager._OnKeyDownTrigger = 10;
  25155. ActionManager._OnKeyUpTrigger = 11;
  25156. return ActionManager;
  25157. })();
  25158. BABYLON.ActionManager = ActionManager;
  25159. })(BABYLON || (BABYLON = {}));
  25160. //# sourceMappingURL=babylon.actionManager.js.map
  25161. var BABYLON;
  25162. (function (BABYLON) {
  25163. var InterpolateValueAction = (function (_super) {
  25164. __extends(InterpolateValueAction, _super);
  25165. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25166. if (duration === void 0) { duration = 1000; }
  25167. _super.call(this, triggerOptions, condition);
  25168. this.propertyPath = propertyPath;
  25169. this.value = value;
  25170. this.duration = duration;
  25171. this.stopOtherAnimations = stopOtherAnimations;
  25172. this._target = target;
  25173. }
  25174. InterpolateValueAction.prototype._prepare = function () {
  25175. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25176. this._property = this._getProperty(this.propertyPath);
  25177. };
  25178. InterpolateValueAction.prototype.execute = function () {
  25179. var scene = this._actionManager.getScene();
  25180. var keys = [
  25181. {
  25182. frame: 0,
  25183. value: this._target[this._property]
  25184. },
  25185. {
  25186. frame: 100,
  25187. value: this.value
  25188. }
  25189. ];
  25190. var dataType;
  25191. if (typeof this.value === "number") {
  25192. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25193. }
  25194. else if (this.value instanceof BABYLON.Color3) {
  25195. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25196. }
  25197. else if (this.value instanceof BABYLON.Vector3) {
  25198. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25199. }
  25200. else if (this.value instanceof BABYLON.Matrix) {
  25201. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25202. }
  25203. else if (this.value instanceof BABYLON.Quaternion) {
  25204. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25205. }
  25206. else {
  25207. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25208. return;
  25209. }
  25210. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25211. animation.setKeys(keys);
  25212. if (this.stopOtherAnimations) {
  25213. scene.stopAnimation(this._target);
  25214. }
  25215. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25216. };
  25217. return InterpolateValueAction;
  25218. })(BABYLON.Action);
  25219. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25220. })(BABYLON || (BABYLON = {}));
  25221. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25222. var BABYLON;
  25223. (function (BABYLON) {
  25224. var SwitchBooleanAction = (function (_super) {
  25225. __extends(SwitchBooleanAction, _super);
  25226. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25227. _super.call(this, triggerOptions, condition);
  25228. this.propertyPath = propertyPath;
  25229. this._target = target;
  25230. }
  25231. SwitchBooleanAction.prototype._prepare = function () {
  25232. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25233. this._property = this._getProperty(this.propertyPath);
  25234. };
  25235. SwitchBooleanAction.prototype.execute = function () {
  25236. this._target[this._property] = !this._target[this._property];
  25237. };
  25238. return SwitchBooleanAction;
  25239. })(BABYLON.Action);
  25240. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25241. var SetStateAction = (function (_super) {
  25242. __extends(SetStateAction, _super);
  25243. function SetStateAction(triggerOptions, target, value, condition) {
  25244. _super.call(this, triggerOptions, condition);
  25245. this.value = value;
  25246. this._target = target;
  25247. }
  25248. SetStateAction.prototype.execute = function () {
  25249. this._target.state = this.value;
  25250. };
  25251. return SetStateAction;
  25252. })(BABYLON.Action);
  25253. BABYLON.SetStateAction = SetStateAction;
  25254. var SetValueAction = (function (_super) {
  25255. __extends(SetValueAction, _super);
  25256. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25257. _super.call(this, triggerOptions, condition);
  25258. this.propertyPath = propertyPath;
  25259. this.value = value;
  25260. this._target = target;
  25261. }
  25262. SetValueAction.prototype._prepare = function () {
  25263. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25264. this._property = this._getProperty(this.propertyPath);
  25265. };
  25266. SetValueAction.prototype.execute = function () {
  25267. this._target[this._property] = this.value;
  25268. };
  25269. return SetValueAction;
  25270. })(BABYLON.Action);
  25271. BABYLON.SetValueAction = SetValueAction;
  25272. var IncrementValueAction = (function (_super) {
  25273. __extends(IncrementValueAction, _super);
  25274. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25275. _super.call(this, triggerOptions, condition);
  25276. this.propertyPath = propertyPath;
  25277. this.value = value;
  25278. this._target = target;
  25279. }
  25280. IncrementValueAction.prototype._prepare = function () {
  25281. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25282. this._property = this._getProperty(this.propertyPath);
  25283. if (typeof this._target[this._property] !== "number") {
  25284. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25285. }
  25286. };
  25287. IncrementValueAction.prototype.execute = function () {
  25288. this._target[this._property] += this.value;
  25289. };
  25290. return IncrementValueAction;
  25291. })(BABYLON.Action);
  25292. BABYLON.IncrementValueAction = IncrementValueAction;
  25293. var PlayAnimationAction = (function (_super) {
  25294. __extends(PlayAnimationAction, _super);
  25295. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25296. _super.call(this, triggerOptions, condition);
  25297. this.from = from;
  25298. this.to = to;
  25299. this.loop = loop;
  25300. this._target = target;
  25301. }
  25302. PlayAnimationAction.prototype._prepare = function () {
  25303. };
  25304. PlayAnimationAction.prototype.execute = function () {
  25305. var scene = this._actionManager.getScene();
  25306. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25307. };
  25308. return PlayAnimationAction;
  25309. })(BABYLON.Action);
  25310. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25311. var StopAnimationAction = (function (_super) {
  25312. __extends(StopAnimationAction, _super);
  25313. function StopAnimationAction(triggerOptions, target, condition) {
  25314. _super.call(this, triggerOptions, condition);
  25315. this._target = target;
  25316. }
  25317. StopAnimationAction.prototype._prepare = function () {
  25318. };
  25319. StopAnimationAction.prototype.execute = function () {
  25320. var scene = this._actionManager.getScene();
  25321. scene.stopAnimation(this._target);
  25322. };
  25323. return StopAnimationAction;
  25324. })(BABYLON.Action);
  25325. BABYLON.StopAnimationAction = StopAnimationAction;
  25326. var DoNothingAction = (function (_super) {
  25327. __extends(DoNothingAction, _super);
  25328. function DoNothingAction(triggerOptions, condition) {
  25329. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25330. _super.call(this, triggerOptions, condition);
  25331. }
  25332. DoNothingAction.prototype.execute = function () {
  25333. };
  25334. return DoNothingAction;
  25335. })(BABYLON.Action);
  25336. BABYLON.DoNothingAction = DoNothingAction;
  25337. var CombineAction = (function (_super) {
  25338. __extends(CombineAction, _super);
  25339. function CombineAction(triggerOptions, children, condition) {
  25340. _super.call(this, triggerOptions, condition);
  25341. this.children = children;
  25342. }
  25343. CombineAction.prototype._prepare = function () {
  25344. for (var index = 0; index < this.children.length; index++) {
  25345. this.children[index]._actionManager = this._actionManager;
  25346. this.children[index]._prepare();
  25347. }
  25348. };
  25349. CombineAction.prototype.execute = function (evt) {
  25350. for (var index = 0; index < this.children.length; index++) {
  25351. this.children[index].execute(evt);
  25352. }
  25353. };
  25354. return CombineAction;
  25355. })(BABYLON.Action);
  25356. BABYLON.CombineAction = CombineAction;
  25357. var ExecuteCodeAction = (function (_super) {
  25358. __extends(ExecuteCodeAction, _super);
  25359. function ExecuteCodeAction(triggerOptions, func, condition) {
  25360. _super.call(this, triggerOptions, condition);
  25361. this.func = func;
  25362. }
  25363. ExecuteCodeAction.prototype.execute = function (evt) {
  25364. this.func(evt);
  25365. };
  25366. return ExecuteCodeAction;
  25367. })(BABYLON.Action);
  25368. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25369. var SetParentAction = (function (_super) {
  25370. __extends(SetParentAction, _super);
  25371. function SetParentAction(triggerOptions, target, parent, condition) {
  25372. _super.call(this, triggerOptions, condition);
  25373. this._target = target;
  25374. this._parent = parent;
  25375. }
  25376. SetParentAction.prototype._prepare = function () {
  25377. };
  25378. SetParentAction.prototype.execute = function () {
  25379. if (this._target.parent === this._parent) {
  25380. return;
  25381. }
  25382. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25383. invertParentWorldMatrix.invert();
  25384. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25385. this._target.parent = this._parent;
  25386. };
  25387. return SetParentAction;
  25388. })(BABYLON.Action);
  25389. BABYLON.SetParentAction = SetParentAction;
  25390. var PlaySoundAction = (function (_super) {
  25391. __extends(PlaySoundAction, _super);
  25392. function PlaySoundAction(triggerOptions, sound, condition) {
  25393. _super.call(this, triggerOptions, condition);
  25394. this._sound = sound;
  25395. }
  25396. PlaySoundAction.prototype._prepare = function () {
  25397. };
  25398. PlaySoundAction.prototype.execute = function () {
  25399. if (this._sound !== undefined)
  25400. this._sound.play();
  25401. };
  25402. return PlaySoundAction;
  25403. })(BABYLON.Action);
  25404. BABYLON.PlaySoundAction = PlaySoundAction;
  25405. var StopSoundAction = (function (_super) {
  25406. __extends(StopSoundAction, _super);
  25407. function StopSoundAction(triggerOptions, sound, condition) {
  25408. _super.call(this, triggerOptions, condition);
  25409. this._sound = sound;
  25410. }
  25411. StopSoundAction.prototype._prepare = function () {
  25412. };
  25413. StopSoundAction.prototype.execute = function () {
  25414. if (this._sound !== undefined)
  25415. this._sound.stop();
  25416. };
  25417. return StopSoundAction;
  25418. })(BABYLON.Action);
  25419. BABYLON.StopSoundAction = StopSoundAction;
  25420. })(BABYLON || (BABYLON = {}));
  25421. //# sourceMappingURL=babylon.directActions.js.map
  25422. var BABYLON;
  25423. (function (BABYLON) {
  25424. var Geometry = (function () {
  25425. function Geometry(id, scene, vertexData, updatable, mesh) {
  25426. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25427. this._totalVertices = 0;
  25428. this._indices = [];
  25429. this._isDisposed = false;
  25430. this.id = id;
  25431. this._engine = scene.getEngine();
  25432. this._meshes = [];
  25433. this._scene = scene;
  25434. // vertexData
  25435. if (vertexData) {
  25436. this.setAllVerticesData(vertexData, updatable);
  25437. }
  25438. else {
  25439. this._totalVertices = 0;
  25440. this._indices = [];
  25441. }
  25442. // applyToMesh
  25443. if (mesh) {
  25444. this.applyToMesh(mesh);
  25445. mesh.computeWorldMatrix(true);
  25446. }
  25447. }
  25448. Geometry.prototype.getScene = function () {
  25449. return this._scene;
  25450. };
  25451. Geometry.prototype.getEngine = function () {
  25452. return this._engine;
  25453. };
  25454. Geometry.prototype.isReady = function () {
  25455. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25456. };
  25457. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25458. vertexData.applyToGeometry(this, updatable);
  25459. this.notifyUpdate();
  25460. };
  25461. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25462. this._vertexBuffers = this._vertexBuffers || {};
  25463. if (this._vertexBuffers[kind]) {
  25464. this._vertexBuffers[kind].dispose();
  25465. }
  25466. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25467. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25468. stride = this._vertexBuffers[kind].getStrideSize();
  25469. this._totalVertices = data.length / stride;
  25470. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25471. var meshes = this._meshes;
  25472. var numOfMeshes = meshes.length;
  25473. for (var index = 0; index < numOfMeshes; index++) {
  25474. var mesh = meshes[index];
  25475. mesh._resetPointsArrayCache();
  25476. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25477. mesh._createGlobalSubMesh();
  25478. mesh.computeWorldMatrix(true);
  25479. }
  25480. }
  25481. this.notifyUpdate(kind);
  25482. };
  25483. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25484. var vertexBuffer = this.getVertexBuffer(kind);
  25485. if (!vertexBuffer) {
  25486. return;
  25487. }
  25488. vertexBuffer.updateDirectly(data, offset);
  25489. this.notifyUpdate(kind);
  25490. };
  25491. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25492. var vertexBuffer = this.getVertexBuffer(kind);
  25493. if (!vertexBuffer) {
  25494. return;
  25495. }
  25496. vertexBuffer.update(data);
  25497. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25498. var extend;
  25499. var stride = vertexBuffer.getStrideSize();
  25500. this._totalVertices = data.length / stride;
  25501. if (updateExtends) {
  25502. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25503. }
  25504. var meshes = this._meshes;
  25505. var numOfMeshes = meshes.length;
  25506. for (var index = 0; index < numOfMeshes; index++) {
  25507. var mesh = meshes[index];
  25508. mesh._resetPointsArrayCache();
  25509. if (updateExtends) {
  25510. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25511. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25512. var subMesh = mesh.subMeshes[subIndex];
  25513. subMesh.refreshBoundingInfo();
  25514. }
  25515. }
  25516. }
  25517. }
  25518. this.notifyUpdate(kind);
  25519. };
  25520. Geometry.prototype.getTotalVertices = function () {
  25521. if (!this.isReady()) {
  25522. return 0;
  25523. }
  25524. return this._totalVertices;
  25525. };
  25526. Geometry.prototype.getVerticesData = function (kind) {
  25527. var vertexBuffer = this.getVertexBuffer(kind);
  25528. if (!vertexBuffer) {
  25529. return null;
  25530. }
  25531. return vertexBuffer.getData();
  25532. };
  25533. Geometry.prototype.getVertexBuffer = function (kind) {
  25534. if (!this.isReady()) {
  25535. return null;
  25536. }
  25537. return this._vertexBuffers[kind];
  25538. };
  25539. Geometry.prototype.getVertexBuffers = function () {
  25540. if (!this.isReady()) {
  25541. return null;
  25542. }
  25543. return this._vertexBuffers;
  25544. };
  25545. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25546. if (!this._vertexBuffers) {
  25547. if (this._delayInfo) {
  25548. return this._delayInfo.indexOf(kind) !== -1;
  25549. }
  25550. return false;
  25551. }
  25552. return this._vertexBuffers[kind] !== undefined;
  25553. };
  25554. Geometry.prototype.getVerticesDataKinds = function () {
  25555. var result = [];
  25556. if (!this._vertexBuffers && this._delayInfo) {
  25557. for (var kind in this._delayInfo) {
  25558. result.push(kind);
  25559. }
  25560. }
  25561. else {
  25562. for (kind in this._vertexBuffers) {
  25563. result.push(kind);
  25564. }
  25565. }
  25566. return result;
  25567. };
  25568. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25569. if (this._indexBuffer) {
  25570. this._engine._releaseBuffer(this._indexBuffer);
  25571. }
  25572. this._indices = indices;
  25573. if (this._meshes.length !== 0 && this._indices) {
  25574. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25575. }
  25576. if (totalVertices !== undefined) {
  25577. this._totalVertices = totalVertices;
  25578. }
  25579. var meshes = this._meshes;
  25580. var numOfMeshes = meshes.length;
  25581. for (var index = 0; index < numOfMeshes; index++) {
  25582. meshes[index]._createGlobalSubMesh();
  25583. }
  25584. this.notifyUpdate();
  25585. };
  25586. Geometry.prototype.getTotalIndices = function () {
  25587. if (!this.isReady()) {
  25588. return 0;
  25589. }
  25590. return this._indices.length;
  25591. };
  25592. Geometry.prototype.getIndices = function () {
  25593. if (!this.isReady()) {
  25594. return null;
  25595. }
  25596. return this._indices;
  25597. };
  25598. Geometry.prototype.getIndexBuffer = function () {
  25599. if (!this.isReady()) {
  25600. return null;
  25601. }
  25602. return this._indexBuffer;
  25603. };
  25604. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25605. var meshes = this._meshes;
  25606. var index = meshes.indexOf(mesh);
  25607. if (index === -1) {
  25608. return;
  25609. }
  25610. for (var kind in this._vertexBuffers) {
  25611. this._vertexBuffers[kind].dispose();
  25612. }
  25613. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25614. this._indexBuffer = null;
  25615. }
  25616. meshes.splice(index, 1);
  25617. mesh._geometry = null;
  25618. if (meshes.length === 0 && shouldDispose) {
  25619. this.dispose();
  25620. }
  25621. };
  25622. Geometry.prototype.applyToMesh = function (mesh) {
  25623. if (mesh._geometry === this) {
  25624. return;
  25625. }
  25626. var previousGeometry = mesh._geometry;
  25627. if (previousGeometry) {
  25628. previousGeometry.releaseForMesh(mesh);
  25629. }
  25630. var meshes = this._meshes;
  25631. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25632. mesh._geometry = this;
  25633. this._scene.pushGeometry(this);
  25634. meshes.push(mesh);
  25635. if (this.isReady()) {
  25636. this._applyToMesh(mesh);
  25637. }
  25638. else {
  25639. mesh._boundingInfo = this._boundingInfo;
  25640. }
  25641. };
  25642. Geometry.prototype._applyToMesh = function (mesh) {
  25643. var numOfMeshes = this._meshes.length;
  25644. for (var kind in this._vertexBuffers) {
  25645. if (numOfMeshes === 1) {
  25646. this._vertexBuffers[kind].create();
  25647. }
  25648. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25649. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25650. mesh._resetPointsArrayCache();
  25651. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25652. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25653. mesh._createGlobalSubMesh();
  25654. //bounding info was just created again, world matrix should be applied again.
  25655. mesh._updateBoundingInfo();
  25656. }
  25657. }
  25658. // indexBuffer
  25659. if (numOfMeshes === 1 && this._indices) {
  25660. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25661. }
  25662. if (this._indexBuffer) {
  25663. this._indexBuffer.references = numOfMeshes;
  25664. }
  25665. };
  25666. Geometry.prototype.notifyUpdate = function (kind) {
  25667. if (this.onGeometryUpdated) {
  25668. this.onGeometryUpdated(this, kind);
  25669. }
  25670. };
  25671. Geometry.prototype.load = function (scene, onLoaded) {
  25672. var _this = this;
  25673. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25674. return;
  25675. }
  25676. if (this.isReady()) {
  25677. if (onLoaded) {
  25678. onLoaded();
  25679. }
  25680. return;
  25681. }
  25682. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25683. scene._addPendingData(this);
  25684. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25685. _this._delayLoadingFunction(JSON.parse(data), _this);
  25686. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25687. _this._delayInfo = [];
  25688. scene._removePendingData(_this);
  25689. var meshes = _this._meshes;
  25690. var numOfMeshes = meshes.length;
  25691. for (var index = 0; index < numOfMeshes; index++) {
  25692. _this._applyToMesh(meshes[index]);
  25693. }
  25694. if (onLoaded) {
  25695. onLoaded();
  25696. }
  25697. }, function () {
  25698. }, scene.database);
  25699. };
  25700. Geometry.prototype.isDisposed = function () {
  25701. return this._isDisposed;
  25702. };
  25703. Geometry.prototype.dispose = function () {
  25704. var meshes = this._meshes;
  25705. var numOfMeshes = meshes.length;
  25706. var index;
  25707. for (index = 0; index < numOfMeshes; index++) {
  25708. this.releaseForMesh(meshes[index]);
  25709. }
  25710. this._meshes = [];
  25711. for (var kind in this._vertexBuffers) {
  25712. this._vertexBuffers[kind].dispose();
  25713. }
  25714. this._vertexBuffers = [];
  25715. this._totalVertices = 0;
  25716. if (this._indexBuffer) {
  25717. this._engine._releaseBuffer(this._indexBuffer);
  25718. }
  25719. this._indexBuffer = null;
  25720. this._indices = [];
  25721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25722. this.delayLoadingFile = null;
  25723. this._delayLoadingFunction = null;
  25724. this._delayInfo = [];
  25725. this._boundingInfo = null; // todo: .dispose()
  25726. this._scene.removeGeometry(this);
  25727. this._isDisposed = true;
  25728. };
  25729. Geometry.prototype.copy = function (id) {
  25730. var vertexData = new BABYLON.VertexData();
  25731. vertexData.indices = [];
  25732. var indices = this.getIndices();
  25733. for (var index = 0; index < indices.length; index++) {
  25734. vertexData.indices.push(indices[index]);
  25735. }
  25736. var updatable = false;
  25737. var stopChecking = false;
  25738. for (var kind in this._vertexBuffers) {
  25739. // using slice() to make a copy of the array and not just reference it
  25740. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25741. if (!stopChecking) {
  25742. updatable = this.getVertexBuffer(kind).isUpdatable();
  25743. stopChecking = !updatable;
  25744. }
  25745. }
  25746. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25747. geometry.delayLoadState = this.delayLoadState;
  25748. geometry.delayLoadingFile = this.delayLoadingFile;
  25749. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25750. for (kind in this._delayInfo) {
  25751. geometry._delayInfo = geometry._delayInfo || [];
  25752. geometry._delayInfo.push(kind);
  25753. }
  25754. // Bounding info
  25755. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25756. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25757. return geometry;
  25758. };
  25759. // Statics
  25760. Geometry.ExtractFromMesh = function (mesh, id) {
  25761. var geometry = mesh._geometry;
  25762. if (!geometry) {
  25763. return null;
  25764. }
  25765. return geometry.copy(id);
  25766. };
  25767. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25768. // be aware Math.random() could cause collisions
  25769. Geometry.RandomId = function () {
  25770. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25771. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25772. return v.toString(16);
  25773. });
  25774. };
  25775. return Geometry;
  25776. })();
  25777. BABYLON.Geometry = Geometry;
  25778. /////// Primitives //////////////////////////////////////////////
  25779. var Geometry;
  25780. (function (Geometry) {
  25781. var Primitives;
  25782. (function (Primitives) {
  25783. /// Abstract class
  25784. var _Primitive = (function (_super) {
  25785. __extends(_Primitive, _super);
  25786. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25787. this._beingRegenerated = true;
  25788. this._canBeRegenerated = canBeRegenerated;
  25789. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25790. this._beingRegenerated = false;
  25791. }
  25792. _Primitive.prototype.canBeRegenerated = function () {
  25793. return this._canBeRegenerated;
  25794. };
  25795. _Primitive.prototype.regenerate = function () {
  25796. if (!this._canBeRegenerated) {
  25797. return;
  25798. }
  25799. this._beingRegenerated = true;
  25800. this.setAllVerticesData(this._regenerateVertexData(), false);
  25801. this._beingRegenerated = false;
  25802. };
  25803. _Primitive.prototype.asNewGeometry = function (id) {
  25804. return _super.prototype.copy.call(this, id);
  25805. };
  25806. // overrides
  25807. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25808. if (!this._beingRegenerated) {
  25809. return;
  25810. }
  25811. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25812. };
  25813. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25814. if (!this._beingRegenerated) {
  25815. return;
  25816. }
  25817. _super.prototype.setVerticesData.call(this, kind, data, false);
  25818. };
  25819. // to override
  25820. // protected
  25821. _Primitive.prototype._regenerateVertexData = function () {
  25822. throw new Error("Abstract method");
  25823. };
  25824. _Primitive.prototype.copy = function (id) {
  25825. throw new Error("Must be overriden in sub-classes.");
  25826. };
  25827. return _Primitive;
  25828. })(Geometry);
  25829. Primitives._Primitive = _Primitive;
  25830. var Ribbon = (function (_super) {
  25831. __extends(Ribbon, _super);
  25832. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25833. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25834. this.pathArray = pathArray;
  25835. this.closeArray = closeArray;
  25836. this.closePath = closePath;
  25837. this.offset = offset;
  25838. this.side = side;
  25839. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25840. }
  25841. Ribbon.prototype._regenerateVertexData = function () {
  25842. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25843. };
  25844. Ribbon.prototype.copy = function (id) {
  25845. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25846. };
  25847. return Ribbon;
  25848. })(_Primitive);
  25849. Primitives.Ribbon = Ribbon;
  25850. var Box = (function (_super) {
  25851. __extends(Box, _super);
  25852. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25853. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25854. this.size = size;
  25855. this.side = side;
  25856. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25857. }
  25858. Box.prototype._regenerateVertexData = function () {
  25859. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25860. };
  25861. Box.prototype.copy = function (id) {
  25862. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25863. };
  25864. return Box;
  25865. })(_Primitive);
  25866. Primitives.Box = Box;
  25867. var Sphere = (function (_super) {
  25868. __extends(Sphere, _super);
  25869. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25870. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25871. this.segments = segments;
  25872. this.diameter = diameter;
  25873. this.side = side;
  25874. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25875. }
  25876. Sphere.prototype._regenerateVertexData = function () {
  25877. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25878. };
  25879. Sphere.prototype.copy = function (id) {
  25880. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25881. };
  25882. return Sphere;
  25883. })(_Primitive);
  25884. Primitives.Sphere = Sphere;
  25885. var Cylinder = (function (_super) {
  25886. __extends(Cylinder, _super);
  25887. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25888. if (subdivisions === void 0) { subdivisions = 1; }
  25889. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25890. this.height = height;
  25891. this.diameterTop = diameterTop;
  25892. this.diameterBottom = diameterBottom;
  25893. this.tessellation = tessellation;
  25894. this.subdivisions = subdivisions;
  25895. this.side = side;
  25896. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25897. }
  25898. Cylinder.prototype._regenerateVertexData = function () {
  25899. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25900. };
  25901. Cylinder.prototype.copy = function (id) {
  25902. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25903. };
  25904. return Cylinder;
  25905. })(_Primitive);
  25906. Primitives.Cylinder = Cylinder;
  25907. var Torus = (function (_super) {
  25908. __extends(Torus, _super);
  25909. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25910. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25911. this.diameter = diameter;
  25912. this.thickness = thickness;
  25913. this.tessellation = tessellation;
  25914. this.side = side;
  25915. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25916. }
  25917. Torus.prototype._regenerateVertexData = function () {
  25918. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25919. };
  25920. Torus.prototype.copy = function (id) {
  25921. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25922. };
  25923. return Torus;
  25924. })(_Primitive);
  25925. Primitives.Torus = Torus;
  25926. var Ground = (function (_super) {
  25927. __extends(Ground, _super);
  25928. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25929. this.width = width;
  25930. this.height = height;
  25931. this.subdivisions = subdivisions;
  25932. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25933. }
  25934. Ground.prototype._regenerateVertexData = function () {
  25935. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25936. };
  25937. Ground.prototype.copy = function (id) {
  25938. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25939. };
  25940. return Ground;
  25941. })(_Primitive);
  25942. Primitives.Ground = Ground;
  25943. var TiledGround = (function (_super) {
  25944. __extends(TiledGround, _super);
  25945. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25946. this.xmin = xmin;
  25947. this.zmin = zmin;
  25948. this.xmax = xmax;
  25949. this.zmax = zmax;
  25950. this.subdivisions = subdivisions;
  25951. this.precision = precision;
  25952. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25953. }
  25954. TiledGround.prototype._regenerateVertexData = function () {
  25955. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25956. };
  25957. TiledGround.prototype.copy = function (id) {
  25958. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25959. };
  25960. return TiledGround;
  25961. })(_Primitive);
  25962. Primitives.TiledGround = TiledGround;
  25963. var Plane = (function (_super) {
  25964. __extends(Plane, _super);
  25965. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25966. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25967. this.size = size;
  25968. this.side = side;
  25969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25970. }
  25971. Plane.prototype._regenerateVertexData = function () {
  25972. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25973. };
  25974. Plane.prototype.copy = function (id) {
  25975. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25976. };
  25977. return Plane;
  25978. })(_Primitive);
  25979. Primitives.Plane = Plane;
  25980. var TorusKnot = (function (_super) {
  25981. __extends(TorusKnot, _super);
  25982. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25984. this.radius = radius;
  25985. this.tube = tube;
  25986. this.radialSegments = radialSegments;
  25987. this.tubularSegments = tubularSegments;
  25988. this.p = p;
  25989. this.q = q;
  25990. this.side = side;
  25991. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25992. }
  25993. TorusKnot.prototype._regenerateVertexData = function () {
  25994. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25995. };
  25996. TorusKnot.prototype.copy = function (id) {
  25997. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25998. };
  25999. return TorusKnot;
  26000. })(_Primitive);
  26001. Primitives.TorusKnot = TorusKnot;
  26002. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26003. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26004. })(BABYLON || (BABYLON = {}));
  26005. //# sourceMappingURL=babylon.geometry.js.map
  26006. var BABYLON;
  26007. (function (BABYLON) {
  26008. var Gamepads = (function () {
  26009. function Gamepads(ongamedpadconnected) {
  26010. var _this = this;
  26011. this.babylonGamepads = [];
  26012. this.oneGamepadConnected = false;
  26013. this.isMonitoring = false;
  26014. this.gamepadEventSupported = 'GamepadEvent' in window;
  26015. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  26016. 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=";
  26017. this._callbackGamepadConnected = ongamedpadconnected;
  26018. if (this.gamepadSupportAvailable) {
  26019. // Checking if the gamepad connected event is supported (like in Firefox)
  26020. if (this.gamepadEventSupported) {
  26021. window.addEventListener('gamepadconnected', function (evt) {
  26022. _this._onGamepadConnected(evt);
  26023. }, false);
  26024. window.addEventListener('gamepaddisconnected', function (evt) {
  26025. _this._onGamepadDisconnected(evt);
  26026. }, false);
  26027. }
  26028. else {
  26029. this._startMonitoringGamepads();
  26030. }
  26031. if (!this.oneGamepadConnected) {
  26032. this._insertGamepadDOMInstructions();
  26033. }
  26034. }
  26035. else {
  26036. this._insertGamepadDOMNotSupported();
  26037. }
  26038. }
  26039. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  26040. Gamepads.gamepadDOMInfo = document.createElement("div");
  26041. var buttonAImage = document.createElement("img");
  26042. buttonAImage.src = this.buttonADataURL;
  26043. var spanMessage = document.createElement("span");
  26044. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  26045. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  26046. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26047. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26048. Gamepads.gamepadDOMInfo.style.width = "100%";
  26049. Gamepads.gamepadDOMInfo.style.height = "48px";
  26050. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26051. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26052. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26053. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26054. buttonAImage.style.position = "relative";
  26055. buttonAImage.style.bottom = "8px";
  26056. spanMessage.style.position = "relative";
  26057. spanMessage.style.fontSize = "32px";
  26058. spanMessage.style.bottom = "32px";
  26059. spanMessage.style.color = "green";
  26060. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26061. };
  26062. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  26063. Gamepads.gamepadDOMInfo = document.createElement("div");
  26064. var spanMessage = document.createElement("span");
  26065. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26066. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26067. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26068. Gamepads.gamepadDOMInfo.style.width = "100%";
  26069. Gamepads.gamepadDOMInfo.style.height = "40px";
  26070. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26071. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26072. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26073. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26074. spanMessage.style.position = "relative";
  26075. spanMessage.style.fontSize = "32px";
  26076. spanMessage.style.color = "red";
  26077. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26078. };
  26079. Gamepads.prototype.dispose = function () {
  26080. if (Gamepads.gamepadDOMInfo) {
  26081. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26082. }
  26083. };
  26084. Gamepads.prototype._onGamepadConnected = function (evt) {
  26085. var newGamepad = this._addNewGamepad(evt.gamepad);
  26086. if (this._callbackGamepadConnected)
  26087. this._callbackGamepadConnected(newGamepad);
  26088. this._startMonitoringGamepads();
  26089. };
  26090. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26091. if (!this.oneGamepadConnected) {
  26092. this.oneGamepadConnected = true;
  26093. if (Gamepads.gamepadDOMInfo) {
  26094. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26095. Gamepads.gamepadDOMInfo = null;
  26096. }
  26097. }
  26098. var newGamepad;
  26099. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26100. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26101. }
  26102. else {
  26103. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26104. }
  26105. this.babylonGamepads.push(newGamepad);
  26106. return newGamepad;
  26107. };
  26108. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26109. for (var i in this.babylonGamepads) {
  26110. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26111. this.babylonGamepads.splice(i, 1);
  26112. break;
  26113. }
  26114. }
  26115. // If no gamepads are left, stop the polling loop.
  26116. if (this.babylonGamepads.length == 0) {
  26117. this._stopMonitoringGamepads();
  26118. }
  26119. };
  26120. Gamepads.prototype._startMonitoringGamepads = function () {
  26121. if (!this.isMonitoring) {
  26122. this.isMonitoring = true;
  26123. this._checkGamepadsStatus();
  26124. }
  26125. };
  26126. Gamepads.prototype._stopMonitoringGamepads = function () {
  26127. this.isMonitoring = false;
  26128. };
  26129. Gamepads.prototype._checkGamepadsStatus = function () {
  26130. var _this = this;
  26131. // updating gamepad objects
  26132. this._updateGamepadObjects();
  26133. for (var i in this.babylonGamepads) {
  26134. this.babylonGamepads[i].update();
  26135. }
  26136. if (this.isMonitoring) {
  26137. if (window.requestAnimationFrame) {
  26138. window.requestAnimationFrame(function () {
  26139. _this._checkGamepadsStatus();
  26140. });
  26141. }
  26142. else if (window.mozRequestAnimationFrame) {
  26143. window.mozRequestAnimationFrame(function () {
  26144. _this._checkGamepadsStatus();
  26145. });
  26146. }
  26147. else if (window.webkitRequestAnimationFrame) {
  26148. window.webkitRequestAnimationFrame(function () {
  26149. _this._checkGamepadsStatus();
  26150. });
  26151. }
  26152. }
  26153. };
  26154. // This function is called only on Chrome, which does not yet support
  26155. // connection/disconnection events, but requires you to monitor
  26156. // an array for changes.
  26157. Gamepads.prototype._updateGamepadObjects = function () {
  26158. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26159. for (var i = 0; i < gamepads.length; i++) {
  26160. if (gamepads[i]) {
  26161. if (!(gamepads[i].index in this.babylonGamepads)) {
  26162. var newGamepad = this._addNewGamepad(gamepads[i]);
  26163. if (this._callbackGamepadConnected) {
  26164. this._callbackGamepadConnected(newGamepad);
  26165. }
  26166. }
  26167. else {
  26168. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26169. }
  26170. }
  26171. }
  26172. };
  26173. return Gamepads;
  26174. })();
  26175. BABYLON.Gamepads = Gamepads;
  26176. var StickValues = (function () {
  26177. function StickValues(x, y) {
  26178. this.x = x;
  26179. this.y = y;
  26180. }
  26181. return StickValues;
  26182. })();
  26183. BABYLON.StickValues = StickValues;
  26184. var Gamepad = (function () {
  26185. function Gamepad(id, index, browserGamepad) {
  26186. this.id = id;
  26187. this.index = index;
  26188. this.browserGamepad = browserGamepad;
  26189. if (this.browserGamepad.axes.length >= 2) {
  26190. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26191. }
  26192. if (this.browserGamepad.axes.length >= 4) {
  26193. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26194. }
  26195. }
  26196. Gamepad.prototype.onleftstickchanged = function (callback) {
  26197. this._onleftstickchanged = callback;
  26198. };
  26199. Gamepad.prototype.onrightstickchanged = function (callback) {
  26200. this._onrightstickchanged = callback;
  26201. };
  26202. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26203. get: function () {
  26204. return this._leftStick;
  26205. },
  26206. set: function (newValues) {
  26207. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26208. this._onleftstickchanged(newValues);
  26209. }
  26210. this._leftStick = newValues;
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26216. get: function () {
  26217. return this._rightStick;
  26218. },
  26219. set: function (newValues) {
  26220. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26221. this._onrightstickchanged(newValues);
  26222. }
  26223. this._rightStick = newValues;
  26224. },
  26225. enumerable: true,
  26226. configurable: true
  26227. });
  26228. Gamepad.prototype.update = function () {
  26229. if (this._leftStick) {
  26230. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26231. }
  26232. if (this._rightStick) {
  26233. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26234. }
  26235. };
  26236. return Gamepad;
  26237. })();
  26238. BABYLON.Gamepad = Gamepad;
  26239. var GenericPad = (function (_super) {
  26240. __extends(GenericPad, _super);
  26241. function GenericPad(id, index, gamepad) {
  26242. _super.call(this, id, index, gamepad);
  26243. this.id = id;
  26244. this.index = index;
  26245. this.gamepad = gamepad;
  26246. this._buttons = new Array(gamepad.buttons.length);
  26247. }
  26248. GenericPad.prototype.onbuttondown = function (callback) {
  26249. this._onbuttondown = callback;
  26250. };
  26251. GenericPad.prototype.onbuttonup = function (callback) {
  26252. this._onbuttonup = callback;
  26253. };
  26254. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26255. if (newValue !== currentValue) {
  26256. if (this._onbuttondown && newValue === 1) {
  26257. this._onbuttondown(buttonIndex);
  26258. }
  26259. if (this._onbuttonup && newValue === 0) {
  26260. this._onbuttonup(buttonIndex);
  26261. }
  26262. }
  26263. return newValue;
  26264. };
  26265. GenericPad.prototype.update = function () {
  26266. _super.prototype.update.call(this);
  26267. for (var index = 0; index < this._buttons.length; index++) {
  26268. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26269. }
  26270. };
  26271. return GenericPad;
  26272. })(Gamepad);
  26273. BABYLON.GenericPad = GenericPad;
  26274. (function (Xbox360Button) {
  26275. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26276. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26277. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26278. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26279. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26280. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26281. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26282. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26283. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26284. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26285. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26286. var Xbox360Button = BABYLON.Xbox360Button;
  26287. (function (Xbox360Dpad) {
  26288. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26289. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26290. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26291. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26292. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26293. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26294. var Xbox360Pad = (function (_super) {
  26295. __extends(Xbox360Pad, _super);
  26296. function Xbox360Pad() {
  26297. _super.apply(this, arguments);
  26298. this._leftTrigger = 0;
  26299. this._rightTrigger = 0;
  26300. this._buttonA = 0;
  26301. this._buttonB = 0;
  26302. this._buttonX = 0;
  26303. this._buttonY = 0;
  26304. this._buttonBack = 0;
  26305. this._buttonStart = 0;
  26306. this._buttonLB = 0;
  26307. this._buttonRB = 0;
  26308. this._buttonLeftStick = 0;
  26309. this._buttonRightStick = 0;
  26310. this._dPadUp = 0;
  26311. this._dPadDown = 0;
  26312. this._dPadLeft = 0;
  26313. this._dPadRight = 0;
  26314. }
  26315. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26316. this._onlefttriggerchanged = callback;
  26317. };
  26318. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26319. this._onrighttriggerchanged = callback;
  26320. };
  26321. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26322. get: function () {
  26323. return this._leftTrigger;
  26324. },
  26325. set: function (newValue) {
  26326. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26327. this._onlefttriggerchanged(newValue);
  26328. }
  26329. this._leftTrigger = newValue;
  26330. },
  26331. enumerable: true,
  26332. configurable: true
  26333. });
  26334. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26335. get: function () {
  26336. return this._rightTrigger;
  26337. },
  26338. set: function (newValue) {
  26339. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26340. this._onrighttriggerchanged(newValue);
  26341. }
  26342. this._rightTrigger = newValue;
  26343. },
  26344. enumerable: true,
  26345. configurable: true
  26346. });
  26347. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26348. this._onbuttondown = callback;
  26349. };
  26350. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26351. this._onbuttonup = callback;
  26352. };
  26353. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26354. this._ondpaddown = callback;
  26355. };
  26356. Xbox360Pad.prototype.ondpadup = function (callback) {
  26357. this._ondpadup = callback;
  26358. };
  26359. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26360. if (newValue !== currentValue) {
  26361. if (this._onbuttondown && newValue === 1) {
  26362. this._onbuttondown(buttonType);
  26363. }
  26364. if (this._onbuttonup && newValue === 0) {
  26365. this._onbuttonup(buttonType);
  26366. }
  26367. }
  26368. return newValue;
  26369. };
  26370. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26371. if (newValue !== currentValue) {
  26372. if (this._ondpaddown && newValue === 1) {
  26373. this._ondpaddown(buttonType);
  26374. }
  26375. if (this._ondpadup && newValue === 0) {
  26376. this._ondpadup(buttonType);
  26377. }
  26378. }
  26379. return newValue;
  26380. };
  26381. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26382. get: function () {
  26383. return this._buttonA;
  26384. },
  26385. set: function (value) {
  26386. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26387. },
  26388. enumerable: true,
  26389. configurable: true
  26390. });
  26391. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26392. get: function () {
  26393. return this._buttonB;
  26394. },
  26395. set: function (value) {
  26396. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26397. },
  26398. enumerable: true,
  26399. configurable: true
  26400. });
  26401. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26402. get: function () {
  26403. return this._buttonX;
  26404. },
  26405. set: function (value) {
  26406. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26407. },
  26408. enumerable: true,
  26409. configurable: true
  26410. });
  26411. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26412. get: function () {
  26413. return this._buttonY;
  26414. },
  26415. set: function (value) {
  26416. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26417. },
  26418. enumerable: true,
  26419. configurable: true
  26420. });
  26421. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26422. get: function () {
  26423. return this._buttonStart;
  26424. },
  26425. set: function (value) {
  26426. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26427. },
  26428. enumerable: true,
  26429. configurable: true
  26430. });
  26431. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26432. get: function () {
  26433. return this._buttonBack;
  26434. },
  26435. set: function (value) {
  26436. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26437. },
  26438. enumerable: true,
  26439. configurable: true
  26440. });
  26441. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26442. get: function () {
  26443. return this._buttonLB;
  26444. },
  26445. set: function (value) {
  26446. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26452. get: function () {
  26453. return this._buttonRB;
  26454. },
  26455. set: function (value) {
  26456. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26462. get: function () {
  26463. return this._buttonLeftStick;
  26464. },
  26465. set: function (value) {
  26466. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26472. get: function () {
  26473. return this._buttonRightStick;
  26474. },
  26475. set: function (value) {
  26476. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26477. },
  26478. enumerable: true,
  26479. configurable: true
  26480. });
  26481. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26482. get: function () {
  26483. return this._dPadUp;
  26484. },
  26485. set: function (value) {
  26486. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26492. get: function () {
  26493. return this._dPadDown;
  26494. },
  26495. set: function (value) {
  26496. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26497. },
  26498. enumerable: true,
  26499. configurable: true
  26500. });
  26501. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26502. get: function () {
  26503. return this._dPadLeft;
  26504. },
  26505. set: function (value) {
  26506. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26507. },
  26508. enumerable: true,
  26509. configurable: true
  26510. });
  26511. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26512. get: function () {
  26513. return this._dPadRight;
  26514. },
  26515. set: function (value) {
  26516. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26517. },
  26518. enumerable: true,
  26519. configurable: true
  26520. });
  26521. Xbox360Pad.prototype.update = function () {
  26522. _super.prototype.update.call(this);
  26523. this.buttonA = this.browserGamepad.buttons[0].value;
  26524. this.buttonB = this.browserGamepad.buttons[1].value;
  26525. this.buttonX = this.browserGamepad.buttons[2].value;
  26526. this.buttonY = this.browserGamepad.buttons[3].value;
  26527. this.buttonLB = this.browserGamepad.buttons[4].value;
  26528. this.buttonRB = this.browserGamepad.buttons[5].value;
  26529. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26530. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26531. this.buttonBack = this.browserGamepad.buttons[8].value;
  26532. this.buttonStart = this.browserGamepad.buttons[9].value;
  26533. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26534. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26535. this.dPadUp = this.browserGamepad.buttons[12].value;
  26536. this.dPadDown = this.browserGamepad.buttons[13].value;
  26537. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26538. this.dPadRight = this.browserGamepad.buttons[15].value;
  26539. };
  26540. return Xbox360Pad;
  26541. })(Gamepad);
  26542. BABYLON.Xbox360Pad = Xbox360Pad;
  26543. })(BABYLON || (BABYLON = {}));
  26544. //# sourceMappingURL=babylon.gamepads.js.map
  26545. var BABYLON;
  26546. (function (BABYLON) {
  26547. // We're mainly based on the logic defined into the FreeCamera code
  26548. var GamepadCamera = (function (_super) {
  26549. __extends(GamepadCamera, _super);
  26550. function GamepadCamera(name, position, scene) {
  26551. var _this = this;
  26552. _super.call(this, name, position, scene);
  26553. this.angularSensibility = 200;
  26554. this.moveSensibility = 75;
  26555. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26556. _this._onNewGameConnected(gamepad);
  26557. });
  26558. }
  26559. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26560. // Only the first gamepad can control the camera
  26561. if (gamepad.index === 0) {
  26562. this._gamepad = gamepad;
  26563. }
  26564. };
  26565. GamepadCamera.prototype._checkInputs = function () {
  26566. if (!this._gamepad) {
  26567. return;
  26568. }
  26569. var LSValues = this._gamepad.leftStick;
  26570. var normalizedLX = LSValues.x / this.moveSensibility;
  26571. var normalizedLY = LSValues.y / this.moveSensibility;
  26572. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26573. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26574. var RSValues = this._gamepad.rightStick;
  26575. var normalizedRX = RSValues.x / this.angularSensibility;
  26576. var normalizedRY = RSValues.y / this.angularSensibility;
  26577. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26578. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26579. ;
  26580. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26581. var speed = this._computeLocalCameraSpeed() * 50.0;
  26582. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26583. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26584. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26585. };
  26586. GamepadCamera.prototype.dispose = function () {
  26587. this._gamepads.dispose();
  26588. _super.prototype.dispose.call(this);
  26589. };
  26590. return GamepadCamera;
  26591. })(BABYLON.FreeCamera);
  26592. BABYLON.GamepadCamera = GamepadCamera;
  26593. })(BABYLON || (BABYLON = {}));
  26594. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26595. var BABYLON;
  26596. (function (BABYLON) {
  26597. var LinesMesh = (function (_super) {
  26598. __extends(LinesMesh, _super);
  26599. function LinesMesh(name, scene, updatable) {
  26600. if (updatable === void 0) { updatable = false; }
  26601. _super.call(this, name, scene);
  26602. this.color = new BABYLON.Color3(1, 1, 1);
  26603. this.alpha = 1;
  26604. this._indices = new Array();
  26605. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26606. attributes: ["position"],
  26607. uniforms: ["worldViewProjection", "color"],
  26608. needAlphaBlending: true
  26609. });
  26610. }
  26611. Object.defineProperty(LinesMesh.prototype, "material", {
  26612. get: function () {
  26613. return this._colorShader;
  26614. },
  26615. enumerable: true,
  26616. configurable: true
  26617. });
  26618. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26619. get: function () {
  26620. return false;
  26621. },
  26622. enumerable: true,
  26623. configurable: true
  26624. });
  26625. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26626. get: function () {
  26627. return false;
  26628. },
  26629. enumerable: true,
  26630. configurable: true
  26631. });
  26632. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26633. var engine = this.getScene().getEngine();
  26634. var indexToBind = this._geometry.getIndexBuffer();
  26635. // VBOs
  26636. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26637. // Color
  26638. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26639. };
  26640. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26641. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26642. return;
  26643. }
  26644. var engine = this.getScene().getEngine();
  26645. // Draw order
  26646. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26647. };
  26648. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26649. return null;
  26650. };
  26651. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26652. this._colorShader.dispose();
  26653. _super.prototype.dispose.call(this, doNotRecurse);
  26654. };
  26655. return LinesMesh;
  26656. })(BABYLON.Mesh);
  26657. BABYLON.LinesMesh = LinesMesh;
  26658. })(BABYLON || (BABYLON = {}));
  26659. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26660. (function (BABYLON) {
  26661. var OutlineRenderer = (function () {
  26662. function OutlineRenderer(scene) {
  26663. this._scene = scene;
  26664. }
  26665. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26666. var _this = this;
  26667. if (useOverlay === void 0) { useOverlay = false; }
  26668. var scene = this._scene;
  26669. var engine = this._scene.getEngine();
  26670. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26671. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26672. return;
  26673. }
  26674. var mesh = subMesh.getRenderingMesh();
  26675. var material = subMesh.getMaterial();
  26676. engine.enableEffect(this._effect);
  26677. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26678. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26679. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26680. // Bones
  26681. if (mesh.useBones) {
  26682. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26683. }
  26684. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26685. // Alpha test
  26686. if (material && material.needAlphaTesting()) {
  26687. var alphaTexture = material.getAlphaTestTexture();
  26688. this._effect.setTexture("diffuseSampler", alphaTexture);
  26689. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26690. }
  26691. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26692. _this._effect.setMatrix("world", world);
  26693. });
  26694. };
  26695. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26696. var defines = [];
  26697. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26698. var mesh = subMesh.getMesh();
  26699. var material = subMesh.getMaterial();
  26700. // Alpha test
  26701. if (material && material.needAlphaTesting()) {
  26702. defines.push("#define ALPHATEST");
  26703. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26704. attribs.push(BABYLON.VertexBuffer.UVKind);
  26705. defines.push("#define UV1");
  26706. }
  26707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26709. defines.push("#define UV2");
  26710. }
  26711. }
  26712. // Bones
  26713. if (mesh.useBones) {
  26714. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26715. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26716. defines.push("#define BONES");
  26717. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26718. }
  26719. // Instances
  26720. if (useInstances) {
  26721. defines.push("#define INSTANCES");
  26722. attribs.push("world0");
  26723. attribs.push("world1");
  26724. attribs.push("world2");
  26725. attribs.push("world3");
  26726. }
  26727. // Get correct effect
  26728. var join = defines.join("\n");
  26729. if (this._cachedDefines !== join) {
  26730. this._cachedDefines = join;
  26731. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26732. }
  26733. return this._effect.isReady();
  26734. };
  26735. return OutlineRenderer;
  26736. })();
  26737. BABYLON.OutlineRenderer = OutlineRenderer;
  26738. })(BABYLON || (BABYLON = {}));
  26739. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26740. (function (BABYLON) {
  26741. var MeshAssetTask = (function () {
  26742. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26743. this.name = name;
  26744. this.meshesNames = meshesNames;
  26745. this.rootUrl = rootUrl;
  26746. this.sceneFilename = sceneFilename;
  26747. this.isCompleted = false;
  26748. }
  26749. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26750. var _this = this;
  26751. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26752. _this.loadedMeshes = meshes;
  26753. _this.loadedParticleSystems = particleSystems;
  26754. _this.loadedSkeletons = skeletons;
  26755. _this.isCompleted = true;
  26756. if (_this.onSuccess) {
  26757. _this.onSuccess(_this);
  26758. }
  26759. onSuccess();
  26760. }, null, function () {
  26761. if (_this.onError) {
  26762. _this.onError(_this);
  26763. }
  26764. onError();
  26765. });
  26766. };
  26767. return MeshAssetTask;
  26768. })();
  26769. BABYLON.MeshAssetTask = MeshAssetTask;
  26770. var TextFileAssetTask = (function () {
  26771. function TextFileAssetTask(name, url) {
  26772. this.name = name;
  26773. this.url = url;
  26774. this.isCompleted = false;
  26775. }
  26776. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26777. var _this = this;
  26778. BABYLON.Tools.LoadFile(this.url, function (data) {
  26779. _this.text = data;
  26780. _this.isCompleted = true;
  26781. if (_this.onSuccess) {
  26782. _this.onSuccess(_this);
  26783. }
  26784. onSuccess();
  26785. }, null, scene.database, false, function () {
  26786. if (_this.onError) {
  26787. _this.onError(_this);
  26788. }
  26789. onError();
  26790. });
  26791. };
  26792. return TextFileAssetTask;
  26793. })();
  26794. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26795. var BinaryFileAssetTask = (function () {
  26796. function BinaryFileAssetTask(name, url) {
  26797. this.name = name;
  26798. this.url = url;
  26799. this.isCompleted = false;
  26800. }
  26801. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26802. var _this = this;
  26803. BABYLON.Tools.LoadFile(this.url, function (data) {
  26804. _this.data = data;
  26805. _this.isCompleted = true;
  26806. if (_this.onSuccess) {
  26807. _this.onSuccess(_this);
  26808. }
  26809. onSuccess();
  26810. }, null, scene.database, true, function () {
  26811. if (_this.onError) {
  26812. _this.onError(_this);
  26813. }
  26814. onError();
  26815. });
  26816. };
  26817. return BinaryFileAssetTask;
  26818. })();
  26819. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26820. var ImageAssetTask = (function () {
  26821. function ImageAssetTask(name, url) {
  26822. this.name = name;
  26823. this.url = url;
  26824. this.isCompleted = false;
  26825. }
  26826. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26827. var _this = this;
  26828. var img = new Image();
  26829. img.onload = function () {
  26830. _this.image = img;
  26831. _this.isCompleted = true;
  26832. if (_this.onSuccess) {
  26833. _this.onSuccess(_this);
  26834. }
  26835. onSuccess();
  26836. };
  26837. img.onerror = function () {
  26838. if (_this.onError) {
  26839. _this.onError(_this);
  26840. }
  26841. onError();
  26842. };
  26843. img.src = this.url;
  26844. };
  26845. return ImageAssetTask;
  26846. })();
  26847. BABYLON.ImageAssetTask = ImageAssetTask;
  26848. var TextureAssetTask = (function () {
  26849. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26851. this.name = name;
  26852. this.url = url;
  26853. this.noMipmap = noMipmap;
  26854. this.invertY = invertY;
  26855. this.samplingMode = samplingMode;
  26856. this.isCompleted = false;
  26857. }
  26858. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26859. var _this = this;
  26860. var onload = function () {
  26861. _this.isCompleted = true;
  26862. if (_this.onSuccess) {
  26863. _this.onSuccess(_this);
  26864. }
  26865. onSuccess();
  26866. };
  26867. var onerror = function () {
  26868. if (_this.onError) {
  26869. _this.onError(_this);
  26870. }
  26871. onError();
  26872. };
  26873. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26874. };
  26875. return TextureAssetTask;
  26876. })();
  26877. BABYLON.TextureAssetTask = TextureAssetTask;
  26878. var AssetsManager = (function () {
  26879. function AssetsManager(scene) {
  26880. this._tasks = new Array();
  26881. this._waitingTasksCount = 0;
  26882. this.useDefaultLoadingScreen = true;
  26883. this._scene = scene;
  26884. }
  26885. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26886. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26887. this._tasks.push(task);
  26888. return task;
  26889. };
  26890. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26891. var task = new TextFileAssetTask(taskName, url);
  26892. this._tasks.push(task);
  26893. return task;
  26894. };
  26895. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26896. var task = new BinaryFileAssetTask(taskName, url);
  26897. this._tasks.push(task);
  26898. return task;
  26899. };
  26900. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26901. var task = new ImageAssetTask(taskName, url);
  26902. this._tasks.push(task);
  26903. return task;
  26904. };
  26905. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26907. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26908. this._tasks.push(task);
  26909. return task;
  26910. };
  26911. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26912. this._waitingTasksCount--;
  26913. if (this._waitingTasksCount === 0) {
  26914. if (this.onFinish) {
  26915. this.onFinish(this._tasks);
  26916. }
  26917. this._scene.getEngine().hideLoadingUI();
  26918. }
  26919. };
  26920. AssetsManager.prototype._runTask = function (task) {
  26921. var _this = this;
  26922. task.run(this._scene, function () {
  26923. if (_this.onTaskSuccess) {
  26924. _this.onTaskSuccess(task);
  26925. }
  26926. _this._decreaseWaitingTasksCount();
  26927. }, function () {
  26928. if (_this.onTaskError) {
  26929. _this.onTaskError(task);
  26930. }
  26931. _this._decreaseWaitingTasksCount();
  26932. });
  26933. };
  26934. AssetsManager.prototype.reset = function () {
  26935. this._tasks = new Array();
  26936. return this;
  26937. };
  26938. AssetsManager.prototype.load = function () {
  26939. this._waitingTasksCount = this._tasks.length;
  26940. if (this._waitingTasksCount === 0) {
  26941. if (this.onFinish) {
  26942. this.onFinish(this._tasks);
  26943. }
  26944. return this;
  26945. }
  26946. if (this.useDefaultLoadingScreen) {
  26947. this._scene.getEngine().displayLoadingUI();
  26948. }
  26949. for (var index = 0; index < this._tasks.length; index++) {
  26950. var task = this._tasks[index];
  26951. this._runTask(task);
  26952. }
  26953. return this;
  26954. };
  26955. return AssetsManager;
  26956. })();
  26957. BABYLON.AssetsManager = AssetsManager;
  26958. })(BABYLON || (BABYLON = {}));
  26959. //# sourceMappingURL=babylon.assetsManager.js.map
  26960. var BABYLON;
  26961. (function (BABYLON) {
  26962. var VRDeviceOrientationCamera = (function (_super) {
  26963. __extends(VRDeviceOrientationCamera, _super);
  26964. function VRDeviceOrientationCamera(name, position, scene) {
  26965. _super.call(this, name, position, scene);
  26966. this._alpha = 0;
  26967. this._beta = 0;
  26968. this._gamma = 0;
  26969. }
  26970. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26971. this._alpha = +evt.alpha | 0;
  26972. this._beta = +evt.beta | 0;
  26973. this._gamma = +evt.gamma | 0;
  26974. if (this._gamma < 0) {
  26975. this._gamma = 90 + this._gamma;
  26976. }
  26977. else {
  26978. // Incline it in the correct angle.
  26979. this._gamma = 270 - this._gamma;
  26980. }
  26981. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26982. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26983. this.rotation.z = this._beta / 180.0 * Math.PI;
  26984. };
  26985. return VRDeviceOrientationCamera;
  26986. })(BABYLON.OculusCamera);
  26987. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26988. })(BABYLON || (BABYLON = {}));
  26989. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26990. var BABYLON;
  26991. (function (BABYLON) {
  26992. var WebVRCamera = (function (_super) {
  26993. __extends(WebVRCamera, _super);
  26994. function WebVRCamera(name, position, scene) {
  26995. _super.call(this, name, position, scene);
  26996. this._hmdDevice = null;
  26997. this._sensorDevice = null;
  26998. this._cacheState = null;
  26999. this._cacheQuaternion = new BABYLON.Quaternion();
  27000. this._cacheRotation = BABYLON.Vector3.Zero();
  27001. this._vrEnabled = false;
  27002. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  27003. }
  27004. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  27005. var size = devices.length;
  27006. var i = 0;
  27007. // Reset devices.
  27008. this._sensorDevice = null;
  27009. this._hmdDevice = null;
  27010. while (i < size && this._hmdDevice === null) {
  27011. if (devices[i] instanceof HMDVRDevice) {
  27012. this._hmdDevice = devices[i];
  27013. }
  27014. i++;
  27015. }
  27016. i = 0;
  27017. while (i < size && this._sensorDevice === null) {
  27018. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  27019. this._sensorDevice = devices[i];
  27020. }
  27021. i++;
  27022. }
  27023. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  27024. };
  27025. WebVRCamera.prototype._update = function () {
  27026. if (this._vrEnabled) {
  27027. this._cacheState = this._sensorDevice.getState();
  27028. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  27029. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  27030. this.rotation.x = -this._cacheRotation.z;
  27031. this.rotation.y = -this._cacheRotation.y;
  27032. this.rotation.z = this._cacheRotation.x;
  27033. }
  27034. _super.prototype._update.call(this);
  27035. };
  27036. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  27037. _super.prototype.attachControl.call(this, element, noPreventDefault);
  27038. if (navigator.getVRDevices) {
  27039. navigator.getVRDevices().then(this._getWebVRDevices);
  27040. }
  27041. else if (navigator.mozGetVRDevices) {
  27042. navigator.mozGetVRDevices(this._getWebVRDevices);
  27043. }
  27044. };
  27045. WebVRCamera.prototype.detachControl = function (element) {
  27046. _super.prototype.detachControl.call(this, element);
  27047. this._vrEnabled = false;
  27048. };
  27049. return WebVRCamera;
  27050. })(BABYLON.OculusCamera);
  27051. BABYLON.WebVRCamera = WebVRCamera;
  27052. })(BABYLON || (BABYLON = {}));
  27053. //# sourceMappingURL=babylon.webVRCamera.js.map
  27054. var BABYLON;
  27055. (function (BABYLON) {
  27056. // Standard optimizations
  27057. var SceneOptimization = (function () {
  27058. function SceneOptimization(priority) {
  27059. if (priority === void 0) { priority = 0; }
  27060. this.priority = priority;
  27061. this.apply = function (scene) {
  27062. return true; // Return true if everything that can be done was applied
  27063. };
  27064. }
  27065. return SceneOptimization;
  27066. })();
  27067. BABYLON.SceneOptimization = SceneOptimization;
  27068. var TextureOptimization = (function (_super) {
  27069. __extends(TextureOptimization, _super);
  27070. function TextureOptimization(priority, maximumSize) {
  27071. var _this = this;
  27072. if (priority === void 0) { priority = 0; }
  27073. if (maximumSize === void 0) { maximumSize = 1024; }
  27074. _super.call(this, priority);
  27075. this.priority = priority;
  27076. this.maximumSize = maximumSize;
  27077. this.apply = function (scene) {
  27078. var allDone = true;
  27079. for (var index = 0; index < scene.textures.length; index++) {
  27080. var texture = scene.textures[index];
  27081. if (!texture.canRescale) {
  27082. continue;
  27083. }
  27084. var currentSize = texture.getSize();
  27085. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27086. if (maxDimension > _this.maximumSize) {
  27087. texture.scale(0.5);
  27088. allDone = false;
  27089. }
  27090. }
  27091. return allDone;
  27092. };
  27093. }
  27094. return TextureOptimization;
  27095. })(SceneOptimization);
  27096. BABYLON.TextureOptimization = TextureOptimization;
  27097. var HardwareScalingOptimization = (function (_super) {
  27098. __extends(HardwareScalingOptimization, _super);
  27099. function HardwareScalingOptimization(priority, maximumScale) {
  27100. var _this = this;
  27101. if (priority === void 0) { priority = 0; }
  27102. if (maximumScale === void 0) { maximumScale = 2; }
  27103. _super.call(this, priority);
  27104. this.priority = priority;
  27105. this.maximumScale = maximumScale;
  27106. this._currentScale = 1;
  27107. this.apply = function (scene) {
  27108. _this._currentScale++;
  27109. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27110. return _this._currentScale >= _this.maximumScale;
  27111. };
  27112. }
  27113. return HardwareScalingOptimization;
  27114. })(SceneOptimization);
  27115. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27116. var ShadowsOptimization = (function (_super) {
  27117. __extends(ShadowsOptimization, _super);
  27118. function ShadowsOptimization() {
  27119. _super.apply(this, arguments);
  27120. this.apply = function (scene) {
  27121. scene.shadowsEnabled = false;
  27122. return true;
  27123. };
  27124. }
  27125. return ShadowsOptimization;
  27126. })(SceneOptimization);
  27127. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27128. var PostProcessesOptimization = (function (_super) {
  27129. __extends(PostProcessesOptimization, _super);
  27130. function PostProcessesOptimization() {
  27131. _super.apply(this, arguments);
  27132. this.apply = function (scene) {
  27133. scene.postProcessesEnabled = false;
  27134. return true;
  27135. };
  27136. }
  27137. return PostProcessesOptimization;
  27138. })(SceneOptimization);
  27139. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27140. var LensFlaresOptimization = (function (_super) {
  27141. __extends(LensFlaresOptimization, _super);
  27142. function LensFlaresOptimization() {
  27143. _super.apply(this, arguments);
  27144. this.apply = function (scene) {
  27145. scene.lensFlaresEnabled = false;
  27146. return true;
  27147. };
  27148. }
  27149. return LensFlaresOptimization;
  27150. })(SceneOptimization);
  27151. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27152. var ParticlesOptimization = (function (_super) {
  27153. __extends(ParticlesOptimization, _super);
  27154. function ParticlesOptimization() {
  27155. _super.apply(this, arguments);
  27156. this.apply = function (scene) {
  27157. scene.particlesEnabled = false;
  27158. return true;
  27159. };
  27160. }
  27161. return ParticlesOptimization;
  27162. })(SceneOptimization);
  27163. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27164. var RenderTargetsOptimization = (function (_super) {
  27165. __extends(RenderTargetsOptimization, _super);
  27166. function RenderTargetsOptimization() {
  27167. _super.apply(this, arguments);
  27168. this.apply = function (scene) {
  27169. scene.renderTargetsEnabled = false;
  27170. return true;
  27171. };
  27172. }
  27173. return RenderTargetsOptimization;
  27174. })(SceneOptimization);
  27175. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27176. var MergeMeshesOptimization = (function (_super) {
  27177. __extends(MergeMeshesOptimization, _super);
  27178. function MergeMeshesOptimization() {
  27179. var _this = this;
  27180. _super.apply(this, arguments);
  27181. this._canBeMerged = function (abstractMesh) {
  27182. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27183. return false;
  27184. }
  27185. var mesh = abstractMesh;
  27186. if (!mesh.isVisible || !mesh.isEnabled()) {
  27187. return false;
  27188. }
  27189. if (mesh.instances.length > 0) {
  27190. return false;
  27191. }
  27192. if (mesh.skeleton || mesh.hasLODLevels) {
  27193. return false;
  27194. }
  27195. return true;
  27196. };
  27197. this.apply = function (scene) {
  27198. var globalPool = scene.meshes.slice(0);
  27199. var globalLength = globalPool.length;
  27200. for (var index = 0; index < globalLength; index++) {
  27201. var currentPool = new Array();
  27202. var current = globalPool[index];
  27203. // Checks
  27204. if (!_this._canBeMerged(current)) {
  27205. continue;
  27206. }
  27207. currentPool.push(current);
  27208. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27209. var otherMesh = globalPool[subIndex];
  27210. if (!_this._canBeMerged(otherMesh)) {
  27211. continue;
  27212. }
  27213. if (otherMesh.material !== current.material) {
  27214. continue;
  27215. }
  27216. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27217. continue;
  27218. }
  27219. currentPool.push(otherMesh);
  27220. globalLength--;
  27221. globalPool.splice(subIndex, 1);
  27222. subIndex--;
  27223. }
  27224. if (currentPool.length < 2) {
  27225. continue;
  27226. }
  27227. // Merge meshes
  27228. BABYLON.Mesh.MergeMeshes(currentPool);
  27229. }
  27230. return true;
  27231. };
  27232. }
  27233. return MergeMeshesOptimization;
  27234. })(SceneOptimization);
  27235. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27236. // Options
  27237. var SceneOptimizerOptions = (function () {
  27238. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27239. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27240. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27241. this.targetFrameRate = targetFrameRate;
  27242. this.trackerDuration = trackerDuration;
  27243. this.optimizations = new Array();
  27244. }
  27245. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27246. var result = new SceneOptimizerOptions(targetFrameRate);
  27247. var priority = 0;
  27248. result.optimizations.push(new MergeMeshesOptimization(priority));
  27249. result.optimizations.push(new ShadowsOptimization(priority));
  27250. result.optimizations.push(new LensFlaresOptimization(priority));
  27251. // Next priority
  27252. priority++;
  27253. result.optimizations.push(new PostProcessesOptimization(priority));
  27254. result.optimizations.push(new ParticlesOptimization(priority));
  27255. // Next priority
  27256. priority++;
  27257. result.optimizations.push(new TextureOptimization(priority, 1024));
  27258. return result;
  27259. };
  27260. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27261. var result = new SceneOptimizerOptions(targetFrameRate);
  27262. var priority = 0;
  27263. result.optimizations.push(new MergeMeshesOptimization(priority));
  27264. result.optimizations.push(new ShadowsOptimization(priority));
  27265. result.optimizations.push(new LensFlaresOptimization(priority));
  27266. // Next priority
  27267. priority++;
  27268. result.optimizations.push(new PostProcessesOptimization(priority));
  27269. result.optimizations.push(new ParticlesOptimization(priority));
  27270. // Next priority
  27271. priority++;
  27272. result.optimizations.push(new TextureOptimization(priority, 512));
  27273. // Next priority
  27274. priority++;
  27275. result.optimizations.push(new RenderTargetsOptimization(priority));
  27276. // Next priority
  27277. priority++;
  27278. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27279. return result;
  27280. };
  27281. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27282. var result = new SceneOptimizerOptions(targetFrameRate);
  27283. var priority = 0;
  27284. result.optimizations.push(new MergeMeshesOptimization(priority));
  27285. result.optimizations.push(new ShadowsOptimization(priority));
  27286. result.optimizations.push(new LensFlaresOptimization(priority));
  27287. // Next priority
  27288. priority++;
  27289. result.optimizations.push(new PostProcessesOptimization(priority));
  27290. result.optimizations.push(new ParticlesOptimization(priority));
  27291. // Next priority
  27292. priority++;
  27293. result.optimizations.push(new TextureOptimization(priority, 256));
  27294. // Next priority
  27295. priority++;
  27296. result.optimizations.push(new RenderTargetsOptimization(priority));
  27297. // Next priority
  27298. priority++;
  27299. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27300. return result;
  27301. };
  27302. return SceneOptimizerOptions;
  27303. })();
  27304. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27305. // Scene optimizer tool
  27306. var SceneOptimizer = (function () {
  27307. function SceneOptimizer() {
  27308. }
  27309. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27310. // TODO: add an epsilon
  27311. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27312. if (onSuccess) {
  27313. onSuccess();
  27314. }
  27315. return;
  27316. }
  27317. // Apply current level of optimizations
  27318. var allDone = true;
  27319. var noOptimizationApplied = true;
  27320. for (var index = 0; index < options.optimizations.length; index++) {
  27321. var optimization = options.optimizations[index];
  27322. if (optimization.priority === currentPriorityLevel) {
  27323. noOptimizationApplied = false;
  27324. allDone = allDone && optimization.apply(scene);
  27325. }
  27326. }
  27327. // If no optimization was applied, this is a failure :(
  27328. if (noOptimizationApplied) {
  27329. if (onFailure) {
  27330. onFailure();
  27331. }
  27332. return;
  27333. }
  27334. // If all optimizations were done, move to next level
  27335. if (allDone) {
  27336. currentPriorityLevel++;
  27337. }
  27338. // Let's the system running for a specific amount of time before checking FPS
  27339. scene.executeWhenReady(function () {
  27340. setTimeout(function () {
  27341. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27342. }, options.trackerDuration);
  27343. });
  27344. };
  27345. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27346. if (!options) {
  27347. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27348. }
  27349. // Let's the system running for a specific amount of time before checking FPS
  27350. scene.executeWhenReady(function () {
  27351. setTimeout(function () {
  27352. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27353. }, options.trackerDuration);
  27354. });
  27355. };
  27356. return SceneOptimizer;
  27357. })();
  27358. BABYLON.SceneOptimizer = SceneOptimizer;
  27359. })(BABYLON || (BABYLON = {}));
  27360. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27361. (function (BABYLON) {
  27362. var Internals;
  27363. (function (Internals) {
  27364. var MeshLODLevel = (function () {
  27365. function MeshLODLevel(distance, mesh) {
  27366. this.distance = distance;
  27367. this.mesh = mesh;
  27368. }
  27369. return MeshLODLevel;
  27370. })();
  27371. Internals.MeshLODLevel = MeshLODLevel;
  27372. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27373. })(BABYLON || (BABYLON = {}));
  27374. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27375. (function (BABYLON) {
  27376. var AudioEngine = (function () {
  27377. function AudioEngine() {
  27378. this._audioContext = null;
  27379. this._audioContextInitialized = false;
  27380. this.canUseWebAudio = false;
  27381. this.WarnedWebAudioUnsupported = false;
  27382. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27383. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27384. this.canUseWebAudio = true;
  27385. }
  27386. }
  27387. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27388. get: function () {
  27389. if (!this._audioContextInitialized) {
  27390. this._initializeAudioContext();
  27391. }
  27392. return this._audioContext;
  27393. },
  27394. enumerable: true,
  27395. configurable: true
  27396. });
  27397. AudioEngine.prototype._initializeAudioContext = function () {
  27398. try {
  27399. if (this.canUseWebAudio) {
  27400. this._audioContext = new AudioContext();
  27401. // create a global volume gain node
  27402. this.masterGain = this._audioContext.createGain();
  27403. this.masterGain.gain.value = 1;
  27404. this.masterGain.connect(this._audioContext.destination);
  27405. this._audioContextInitialized = true;
  27406. }
  27407. }
  27408. catch (e) {
  27409. this.canUseWebAudio = false;
  27410. BABYLON.Tools.Error("Web Audio: " + e.message);
  27411. }
  27412. };
  27413. AudioEngine.prototype.dispose = function () {
  27414. if (this.canUseWebAudio && this._audioContextInitialized) {
  27415. if (this._connectedAnalyser) {
  27416. this._connectedAnalyser.stopDebugCanvas();
  27417. this._connectedAnalyser.dispose();
  27418. this.masterGain.disconnect();
  27419. this.masterGain.connect(this._audioContext.destination);
  27420. this._connectedAnalyser = null;
  27421. }
  27422. this.masterGain.gain.value = 1;
  27423. }
  27424. this.WarnedWebAudioUnsupported = false;
  27425. };
  27426. AudioEngine.prototype.getGlobalVolume = function () {
  27427. if (this.canUseWebAudio && this._audioContextInitialized) {
  27428. return this.masterGain.gain.value;
  27429. }
  27430. else {
  27431. return -1;
  27432. }
  27433. };
  27434. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27435. if (this.canUseWebAudio && this._audioContextInitialized) {
  27436. this.masterGain.gain.value = newVolume;
  27437. }
  27438. };
  27439. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27440. if (this._connectedAnalyser) {
  27441. this._connectedAnalyser.stopDebugCanvas();
  27442. }
  27443. if (this.canUseWebAudio && this._audioContextInitialized) {
  27444. this._connectedAnalyser = analyser;
  27445. this.masterGain.disconnect();
  27446. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27447. }
  27448. };
  27449. return AudioEngine;
  27450. })();
  27451. BABYLON.AudioEngine = AudioEngine;
  27452. })(BABYLON || (BABYLON = {}));
  27453. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27454. (function (BABYLON) {
  27455. var Sound = (function () {
  27456. /**
  27457. * Create a sound and attach it to a scene
  27458. * @param name Name of your sound
  27459. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27460. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27461. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27462. */
  27463. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27464. var _this = this;
  27465. this.autoplay = false;
  27466. this.loop = false;
  27467. this.useCustomAttenuation = false;
  27468. this.spatialSound = false;
  27469. this.refDistance = 1;
  27470. this.rolloffFactor = 1;
  27471. this.maxDistance = 100;
  27472. this.distanceModel = "linear";
  27473. this._panningModel = "equalpower";
  27474. this._playbackRate = 1;
  27475. this._startTime = 0;
  27476. this._startOffset = 0;
  27477. this._position = BABYLON.Vector3.Zero();
  27478. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27479. this._volume = 1;
  27480. this._isLoaded = false;
  27481. this._isReadyToPlay = false;
  27482. this.isPlaying = false;
  27483. this.isPaused = false;
  27484. this._isDirectional = false;
  27485. // Used if you'd like to create a directional sound.
  27486. // If not set, the sound will be omnidirectional
  27487. this._coneInnerAngle = 360;
  27488. this._coneOuterAngle = 360;
  27489. this._coneOuterGain = 0;
  27490. this.name = name;
  27491. this._scene = scene;
  27492. this._readyToPlayCallback = readyToPlayCallback;
  27493. // Default custom attenuation function is a linear attenuation
  27494. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27495. if (currentDistance < maxDistance) {
  27496. return currentVolume * (1 - currentDistance / maxDistance);
  27497. }
  27498. else {
  27499. return 0;
  27500. }
  27501. };
  27502. if (options) {
  27503. this.autoplay = options.autoplay || false;
  27504. this.loop = options.loop || false;
  27505. // if volume === 0, we need another way to check this option
  27506. if (options.volume !== undefined) {
  27507. this._volume = options.volume;
  27508. }
  27509. this.spatialSound = options.spatialSound || false;
  27510. this.maxDistance = options.maxDistance || 100;
  27511. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27512. this.rolloffFactor = options.rolloffFactor || 1;
  27513. this.refDistance = options.refDistance || 1;
  27514. this.distanceModel = options.distanceModel || "linear";
  27515. this._playbackRate = options.playbackRate || 1;
  27516. }
  27517. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27518. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27519. this._soundGain.gain.value = this._volume;
  27520. this._inputAudioNode = this._soundGain;
  27521. this._ouputAudioNode = this._soundGain;
  27522. if (this.spatialSound) {
  27523. this._createSpatialParameters();
  27524. }
  27525. this._scene.mainSoundTrack.AddSound(this);
  27526. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27527. if (urlOrArrayBuffer) {
  27528. // If it's an URL
  27529. if (typeof (urlOrArrayBuffer) === "string") {
  27530. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27531. _this._soundLoaded(data);
  27532. }, null, null, true);
  27533. }
  27534. else {
  27535. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27536. this._soundLoaded(urlOrArrayBuffer);
  27537. }
  27538. else {
  27539. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27540. }
  27541. }
  27542. }
  27543. }
  27544. else {
  27545. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27546. this._scene.mainSoundTrack.AddSound(this);
  27547. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27548. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27549. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27550. }
  27551. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27552. if (this._readyToPlayCallback) {
  27553. window.setTimeout(function () {
  27554. _this._readyToPlayCallback();
  27555. }, 1000);
  27556. }
  27557. }
  27558. }
  27559. Sound.prototype.dispose = function () {
  27560. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27561. if (this.isPlaying) {
  27562. this.stop();
  27563. }
  27564. this._isReadyToPlay = false;
  27565. if (this.soundTrackId === -1) {
  27566. this._scene.mainSoundTrack.RemoveSound(this);
  27567. }
  27568. else {
  27569. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27570. }
  27571. if (this._soundGain) {
  27572. this._soundGain.disconnect();
  27573. this._soundGain = null;
  27574. }
  27575. if (this._soundPanner) {
  27576. this._soundPanner.disconnect();
  27577. this._soundPanner = null;
  27578. }
  27579. if (this._soundSource) {
  27580. this._soundSource.disconnect();
  27581. this._soundSource = null;
  27582. }
  27583. this._audioBuffer = null;
  27584. if (this._connectedMesh) {
  27585. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27586. this._connectedMesh = null;
  27587. }
  27588. }
  27589. };
  27590. Sound.prototype._soundLoaded = function (audioData) {
  27591. var _this = this;
  27592. this._isLoaded = true;
  27593. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27594. _this._audioBuffer = buffer;
  27595. _this._isReadyToPlay = true;
  27596. if (_this.autoplay) {
  27597. _this.play();
  27598. }
  27599. if (_this._readyToPlayCallback) {
  27600. _this._readyToPlayCallback();
  27601. }
  27602. }, function (error) {
  27603. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27604. });
  27605. };
  27606. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27607. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27608. this._audioBuffer = audioBuffer;
  27609. this._isReadyToPlay = true;
  27610. }
  27611. };
  27612. Sound.prototype.updateOptions = function (options) {
  27613. if (options) {
  27614. this.loop = options.loop || this.loop;
  27615. this.maxDistance = options.maxDistance || this.maxDistance;
  27616. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27617. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27618. this.refDistance = options.refDistance || this.refDistance;
  27619. this.distanceModel = options.distanceModel || this.distanceModel;
  27620. this._playbackRate = options.playbackRate || this._playbackRate;
  27621. }
  27622. };
  27623. Sound.prototype._createSpatialParameters = function () {
  27624. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27625. if (this._scene.headphone) {
  27626. this._panningModel = "HRTF";
  27627. }
  27628. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27629. if (this.useCustomAttenuation) {
  27630. // Tricks to disable in a way embedded Web Audio attenuation
  27631. this._soundPanner.distanceModel = "linear";
  27632. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27633. this._soundPanner.refDistance = 1;
  27634. this._soundPanner.rolloffFactor = 1;
  27635. this._soundPanner.panningModel = this._panningModel;
  27636. }
  27637. else {
  27638. this._soundPanner.distanceModel = this.distanceModel;
  27639. this._soundPanner.maxDistance = this.maxDistance;
  27640. this._soundPanner.refDistance = this.refDistance;
  27641. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27642. this._soundPanner.panningModel = this._panningModel;
  27643. }
  27644. this._soundPanner.connect(this._ouputAudioNode);
  27645. this._inputAudioNode = this._soundPanner;
  27646. }
  27647. };
  27648. Sound.prototype.switchPanningModelToHRTF = function () {
  27649. this._panningModel = "HRTF";
  27650. this._switchPanningModel();
  27651. };
  27652. Sound.prototype.switchPanningModelToEqualPower = function () {
  27653. this._panningModel = "equalpower";
  27654. this._switchPanningModel();
  27655. };
  27656. Sound.prototype._switchPanningModel = function () {
  27657. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27658. this._soundPanner.panningModel = this._panningModel;
  27659. }
  27660. };
  27661. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27662. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27663. this._ouputAudioNode.disconnect();
  27664. this._ouputAudioNode.connect(soundTrackAudioNode);
  27665. }
  27666. };
  27667. /**
  27668. * Transform this sound into a directional source
  27669. * @param coneInnerAngle Size of the inner cone in degree
  27670. * @param coneOuterAngle Size of the outer cone in degree
  27671. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27672. */
  27673. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27674. if (coneOuterAngle < coneInnerAngle) {
  27675. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27676. return;
  27677. }
  27678. this._coneInnerAngle = coneInnerAngle;
  27679. this._coneOuterAngle = coneOuterAngle;
  27680. this._coneOuterGain = coneOuterGain;
  27681. this._isDirectional = true;
  27682. if (this.isPlaying && this.loop) {
  27683. this.stop();
  27684. this.play();
  27685. }
  27686. };
  27687. Sound.prototype.setPosition = function (newPosition) {
  27688. this._position = newPosition;
  27689. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27690. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27691. }
  27692. };
  27693. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27694. this._localDirection = newLocalDirection;
  27695. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27696. this._updateDirection();
  27697. }
  27698. };
  27699. Sound.prototype._updateDirection = function () {
  27700. var mat = this._connectedMesh.getWorldMatrix();
  27701. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27702. direction.normalize();
  27703. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27704. };
  27705. Sound.prototype.updateDistanceFromListener = function () {
  27706. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27707. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27708. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27709. }
  27710. };
  27711. Sound.prototype.setAttenuationFunction = function (callback) {
  27712. this._customAttenuationFunction = callback;
  27713. };
  27714. /**
  27715. * Play the sound
  27716. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27717. */
  27718. Sound.prototype.play = function (time) {
  27719. var _this = this;
  27720. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27721. try {
  27722. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27723. if (!this._soundSource) {
  27724. if (this.spatialSound) {
  27725. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27726. if (this._isDirectional) {
  27727. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27728. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27729. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27730. if (this._connectedMesh) {
  27731. this._updateDirection();
  27732. }
  27733. else {
  27734. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27735. }
  27736. }
  27737. }
  27738. }
  27739. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27740. this._soundSource.buffer = this._audioBuffer;
  27741. this._soundSource.connect(this._inputAudioNode);
  27742. this._soundSource.loop = this.loop;
  27743. this._soundSource.playbackRate.value = this._playbackRate;
  27744. this._startTime = startTime;
  27745. this._soundSource.onended = function () {
  27746. _this._onended();
  27747. };
  27748. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27749. this.isPlaying = true;
  27750. this.isPaused = false;
  27751. }
  27752. catch (ex) {
  27753. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27754. }
  27755. }
  27756. };
  27757. Sound.prototype._onended = function () {
  27758. this.isPlaying = false;
  27759. if (this.onended) {
  27760. this.onended();
  27761. }
  27762. };
  27763. /**
  27764. * Stop the sound
  27765. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27766. */
  27767. Sound.prototype.stop = function (time) {
  27768. if (this.isPlaying) {
  27769. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27770. this._soundSource.stop(stopTime);
  27771. this.isPlaying = false;
  27772. }
  27773. };
  27774. Sound.prototype.pause = function () {
  27775. if (this.isPlaying) {
  27776. this.stop(0);
  27777. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27778. this.isPaused = true;
  27779. }
  27780. };
  27781. Sound.prototype.setVolume = function (newVolume, time) {
  27782. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27783. if (time) {
  27784. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27785. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27786. }
  27787. else {
  27788. this._soundGain.gain.value = newVolume;
  27789. }
  27790. }
  27791. this._volume = newVolume;
  27792. };
  27793. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27794. this._playbackRate = newPlaybackRate;
  27795. if (this.isPlaying) {
  27796. this._soundSource.playbackRate.value = this._playbackRate;
  27797. }
  27798. };
  27799. Sound.prototype.getVolume = function () {
  27800. return this._volume;
  27801. };
  27802. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27803. var _this = this;
  27804. this._connectedMesh = meshToConnectTo;
  27805. if (!this.spatialSound) {
  27806. this._createSpatialParameters();
  27807. this.spatialSound = true;
  27808. if (this.isPlaying && this.loop) {
  27809. this.stop();
  27810. this.play();
  27811. }
  27812. }
  27813. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27814. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27815. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27816. };
  27817. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27818. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27819. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27820. this._updateDirection();
  27821. }
  27822. };
  27823. return Sound;
  27824. })();
  27825. BABYLON.Sound = Sound;
  27826. })(BABYLON || (BABYLON = {}));
  27827. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27828. (function (BABYLON) {
  27829. var SoundTrack = (function () {
  27830. function SoundTrack(scene, options) {
  27831. this.id = -1;
  27832. this._isMainTrack = false;
  27833. this._scene = scene;
  27834. this._audioEngine = BABYLON.Engine.audioEngine;
  27835. this.soundCollection = new Array();
  27836. if (this._audioEngine.canUseWebAudio) {
  27837. this._trackGain = this._audioEngine.audioContext.createGain();
  27838. this._trackGain.connect(this._audioEngine.masterGain);
  27839. if (options) {
  27840. if (options.volume) {
  27841. this._trackGain.gain.value = options.volume;
  27842. }
  27843. if (options.mainTrack) {
  27844. this._isMainTrack = options.mainTrack;
  27845. }
  27846. }
  27847. }
  27848. if (!this._isMainTrack) {
  27849. this._scene.soundTracks.push(this);
  27850. this.id = this._scene.soundTracks.length - 1;
  27851. }
  27852. }
  27853. SoundTrack.prototype.dispose = function () {
  27854. if (this._audioEngine.canUseWebAudio) {
  27855. if (this._connectedAnalyser) {
  27856. this._connectedAnalyser.stopDebugCanvas();
  27857. }
  27858. while (this.soundCollection.length) {
  27859. this.soundCollection[0].dispose();
  27860. }
  27861. this._trackGain.disconnect();
  27862. this._trackGain = null;
  27863. }
  27864. };
  27865. SoundTrack.prototype.AddSound = function (sound) {
  27866. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27867. sound.connectToSoundTrackAudioNode(this._trackGain);
  27868. }
  27869. if (sound.soundTrackId) {
  27870. if (sound.soundTrackId === -1) {
  27871. this._scene.mainSoundTrack.RemoveSound(sound);
  27872. }
  27873. else {
  27874. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27875. }
  27876. }
  27877. this.soundCollection.push(sound);
  27878. sound.soundTrackId = this.id;
  27879. };
  27880. SoundTrack.prototype.RemoveSound = function (sound) {
  27881. var index = this.soundCollection.indexOf(sound);
  27882. if (index !== -1) {
  27883. this.soundCollection.splice(index, 1);
  27884. }
  27885. };
  27886. SoundTrack.prototype.setVolume = function (newVolume) {
  27887. if (this._audioEngine.canUseWebAudio) {
  27888. this._trackGain.gain.value = newVolume;
  27889. }
  27890. };
  27891. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27893. for (var i = 0; i < this.soundCollection.length; i++) {
  27894. this.soundCollection[i].switchPanningModelToHRTF();
  27895. }
  27896. }
  27897. };
  27898. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27900. for (var i = 0; i < this.soundCollection.length; i++) {
  27901. this.soundCollection[i].switchPanningModelToEqualPower();
  27902. }
  27903. }
  27904. };
  27905. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27906. if (this._connectedAnalyser) {
  27907. this._connectedAnalyser.stopDebugCanvas();
  27908. }
  27909. this._connectedAnalyser = analyser;
  27910. if (this._audioEngine.canUseWebAudio) {
  27911. this._trackGain.disconnect();
  27912. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27913. }
  27914. };
  27915. return SoundTrack;
  27916. })();
  27917. BABYLON.SoundTrack = SoundTrack;
  27918. })(BABYLON || (BABYLON = {}));
  27919. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27920. (function (BABYLON) {
  27921. var DebugLayer = (function () {
  27922. function DebugLayer(scene) {
  27923. var _this = this;
  27924. this._transformationMatrix = BABYLON.Matrix.Identity();
  27925. this._enabled = false;
  27926. this._labelsEnabled = false;
  27927. this._displayStatistics = true;
  27928. this._displayTree = false;
  27929. this._displayLogs = false;
  27930. this._identityMatrix = BABYLON.Matrix.Identity();
  27931. this.axisRatio = 0.02;
  27932. this.accentColor = "orange";
  27933. this._scene = scene;
  27934. this._syncPositions = function () {
  27935. var engine = _this._scene.getEngine();
  27936. var canvasRect = engine.getRenderingCanvasClientRect();
  27937. if (_this._showUI) {
  27938. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27939. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27940. _this._statsDiv.style.width = "400px";
  27941. _this._statsDiv.style.height = "auto";
  27942. _this._statsSubsetDiv.style.maxHeight = "240px";
  27943. _this._optionsDiv.style.left = "0px";
  27944. _this._optionsDiv.style.top = "10px";
  27945. _this._optionsDiv.style.width = "200px";
  27946. _this._optionsDiv.style.height = "auto";
  27947. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27948. _this._logDiv.style.left = "0px";
  27949. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27950. _this._logDiv.style.width = "600px";
  27951. _this._logDiv.style.height = "160px";
  27952. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27953. _this._treeDiv.style.top = "10px";
  27954. _this._treeDiv.style.width = "300px";
  27955. _this._treeDiv.style.height = "auto";
  27956. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27957. }
  27958. _this._globalDiv.style.left = canvasRect.left + "px";
  27959. _this._globalDiv.style.top = canvasRect.top + "px";
  27960. _this._drawingCanvas.style.left = "0px";
  27961. _this._drawingCanvas.style.top = "0px";
  27962. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27963. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27964. var devicePixelRatio = window.devicePixelRatio || 1;
  27965. var context = _this._drawingContext;
  27966. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27967. _this._ratio = devicePixelRatio / backingStoreRatio;
  27968. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27969. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27970. };
  27971. this._onCanvasClick = function (evt) {
  27972. _this._clickPosition = {
  27973. x: evt.clientX * _this._ratio,
  27974. y: evt.clientY * _this._ratio
  27975. };
  27976. };
  27977. this._syncUI = function () {
  27978. if (_this._showUI) {
  27979. if (_this._displayStatistics) {
  27980. _this._displayStats();
  27981. _this._statsDiv.style.display = "";
  27982. }
  27983. else {
  27984. _this._statsDiv.style.display = "none";
  27985. }
  27986. if (_this._displayLogs) {
  27987. _this._logDiv.style.display = "";
  27988. }
  27989. else {
  27990. _this._logDiv.style.display = "none";
  27991. }
  27992. if (_this._displayTree) {
  27993. _this._treeDiv.style.display = "";
  27994. if (_this._needToRefreshMeshesTree) {
  27995. _this._needToRefreshMeshesTree = false;
  27996. _this._refreshMeshesTreeContent();
  27997. }
  27998. }
  27999. else {
  28000. _this._treeDiv.style.display = "none";
  28001. }
  28002. }
  28003. };
  28004. this._syncData = function () {
  28005. if (_this._labelsEnabled || !_this._showUI) {
  28006. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28007. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28008. var engine = _this._scene.getEngine();
  28009. var viewport = _this._camera.viewport;
  28010. var globalViewport = viewport.toGlobal(engine);
  28011. // Meshes
  28012. var meshes = _this._camera.getActiveMeshes();
  28013. for (var index = 0; index < meshes.length; index++) {
  28014. var mesh = meshes.data[index];
  28015. var position = mesh.getBoundingInfo().boundingSphere.center;
  28016. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28017. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28018. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28019. }
  28020. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28021. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  28022. mesh.renderOverlay = !mesh.renderOverlay;
  28023. }, function () {
  28024. return mesh.renderOverlay ? 'red' : 'black';
  28025. });
  28026. }
  28027. }
  28028. // Cameras
  28029. var cameras = _this._scene.cameras;
  28030. for (index = 0; index < cameras.length; index++) {
  28031. var camera = cameras[index];
  28032. if (camera === _this._camera) {
  28033. continue;
  28034. }
  28035. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28036. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28037. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28038. _this._camera.detachControl(engine.getRenderingCanvas());
  28039. _this._camera = camera;
  28040. _this._camera.attachControl(engine.getRenderingCanvas());
  28041. }, function () {
  28042. return "purple";
  28043. });
  28044. }
  28045. }
  28046. // Lights
  28047. var lights = _this._scene.lights;
  28048. for (index = 0; index < lights.length; index++) {
  28049. var light = lights[index];
  28050. if (light.position) {
  28051. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28052. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28053. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28054. light.setEnabled(!light.isEnabled());
  28055. }, function () {
  28056. return light.isEnabled() ? "orange" : "gray";
  28057. });
  28058. }
  28059. }
  28060. }
  28061. }
  28062. _this._clickPosition = undefined;
  28063. };
  28064. }
  28065. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28066. while (this._treeSubsetDiv.hasChildNodes()) {
  28067. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28068. }
  28069. // Add meshes
  28070. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28071. sortedArray.sort(function (a, b) {
  28072. if (a.name === b.name) {
  28073. return 0;
  28074. }
  28075. return (a.name > b.name) ? 1 : -1;
  28076. });
  28077. for (var index = 0; index < sortedArray.length; index++) {
  28078. var mesh = sortedArray[index];
  28079. if (!mesh.isEnabled()) {
  28080. continue;
  28081. }
  28082. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28083. m.isVisible = element.checked;
  28084. }, mesh);
  28085. }
  28086. };
  28087. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28088. this._drawingContext.beginPath();
  28089. this._drawingContext.moveTo(zero.x, zero.y);
  28090. this._drawingContext.lineTo(unit.x, unit.y);
  28091. this._drawingContext.strokeStyle = color;
  28092. this._drawingContext.lineWidth = 4;
  28093. this._drawingContext.stroke();
  28094. this._drawingContext.font = "normal 14px Segoe UI";
  28095. this._drawingContext.fillStyle = color;
  28096. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28097. };
  28098. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28099. var position = mesh.getBoundingInfo().boundingSphere.center;
  28100. var worldMatrix = mesh.getWorldMatrix();
  28101. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28102. var unit = (unprojectedVector.subtract(position)).length();
  28103. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28104. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28105. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28106. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28107. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28108. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28109. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28110. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28111. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28112. };
  28113. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28114. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28115. this._drawingContext.font = "normal 12px Segoe UI";
  28116. var textMetrics = this._drawingContext.measureText(text);
  28117. var centerX = projectedPosition.x - textMetrics.width / 2;
  28118. var centerY = projectedPosition.y;
  28119. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28120. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28121. onClick();
  28122. }
  28123. this._drawingContext.beginPath();
  28124. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28125. this._drawingContext.fillStyle = getFillStyle();
  28126. this._drawingContext.globalAlpha = 0.5;
  28127. this._drawingContext.fill();
  28128. this._drawingContext.globalAlpha = 1.0;
  28129. this._drawingContext.strokeStyle = '#FFFFFF';
  28130. this._drawingContext.lineWidth = 1;
  28131. this._drawingContext.stroke();
  28132. this._drawingContext.fillStyle = "#FFFFFF";
  28133. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28134. this._drawingContext.beginPath();
  28135. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28136. this._drawingContext.fill();
  28137. }
  28138. };
  28139. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28140. if (!this._clickPosition) {
  28141. return false;
  28142. }
  28143. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28144. return false;
  28145. }
  28146. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28147. return false;
  28148. }
  28149. return true;
  28150. };
  28151. DebugLayer.prototype.isVisible = function () {
  28152. return this._enabled;
  28153. };
  28154. DebugLayer.prototype.hide = function () {
  28155. if (!this._enabled) {
  28156. return;
  28157. }
  28158. this._enabled = false;
  28159. var engine = this._scene.getEngine();
  28160. this._scene.unregisterBeforeRender(this._syncData);
  28161. this._scene.unregisterAfterRender(this._syncUI);
  28162. document.body.removeChild(this._globalDiv);
  28163. window.removeEventListener("resize", this._syncPositions);
  28164. this._scene.forceShowBoundingBoxes = false;
  28165. this._scene.forceWireframe = false;
  28166. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28167. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28168. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28169. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28170. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28171. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28172. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28173. this._scene.shadowsEnabled = true;
  28174. this._scene.particlesEnabled = true;
  28175. this._scene.postProcessesEnabled = true;
  28176. this._scene.collisionsEnabled = true;
  28177. this._scene.lightsEnabled = true;
  28178. this._scene.texturesEnabled = true;
  28179. this._scene.lensFlaresEnabled = true;
  28180. this._scene.proceduralTexturesEnabled = true;
  28181. this._scene.renderTargetsEnabled = true;
  28182. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28183. };
  28184. DebugLayer.prototype.show = function (showUI, camera) {
  28185. if (showUI === void 0) { showUI = true; }
  28186. if (camera === void 0) { camera = null; }
  28187. if (this._enabled) {
  28188. return;
  28189. }
  28190. this._enabled = true;
  28191. if (camera) {
  28192. this._camera = camera;
  28193. }
  28194. else {
  28195. this._camera = this._scene.activeCamera;
  28196. }
  28197. this._showUI = showUI;
  28198. var engine = this._scene.getEngine();
  28199. this._globalDiv = document.createElement("div");
  28200. document.body.appendChild(this._globalDiv);
  28201. this._generateDOMelements();
  28202. window.addEventListener("resize", this._syncPositions);
  28203. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28204. this._syncPositions();
  28205. this._scene.registerBeforeRender(this._syncData);
  28206. this._scene.registerAfterRender(this._syncUI);
  28207. };
  28208. DebugLayer.prototype._clearLabels = function () {
  28209. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28210. for (var index = 0; index < this._scene.meshes.length; index++) {
  28211. var mesh = this._scene.meshes[index];
  28212. mesh.renderOverlay = false;
  28213. }
  28214. };
  28215. DebugLayer.prototype._generateheader = function (root, text) {
  28216. var header = document.createElement("div");
  28217. header.innerHTML = text + "&nbsp;";
  28218. header.style.textAlign = "right";
  28219. header.style.width = "100%";
  28220. header.style.color = "white";
  28221. header.style.backgroundColor = "Black";
  28222. header.style.padding = "5px 5px 4px 0px";
  28223. header.style.marginLeft = "-5px";
  28224. header.style.fontWeight = "bold";
  28225. root.appendChild(header);
  28226. };
  28227. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28228. var label = document.createElement("label");
  28229. label.innerHTML = title;
  28230. label.style.color = color;
  28231. root.appendChild(label);
  28232. root.appendChild(document.createElement("br"));
  28233. };
  28234. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28235. if (tag === void 0) { tag = null; }
  28236. var label = document.createElement("label");
  28237. var boundingBoxesCheckbox = document.createElement("input");
  28238. boundingBoxesCheckbox.type = "checkbox";
  28239. boundingBoxesCheckbox.checked = initialState;
  28240. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28241. task(evt.target, tag);
  28242. });
  28243. label.appendChild(boundingBoxesCheckbox);
  28244. var container = document.createElement("span");
  28245. var leftPart = document.createElement("span");
  28246. var rightPart = document.createElement("span");
  28247. rightPart.style.cssFloat = "right";
  28248. leftPart.innerHTML = leftTitle;
  28249. rightPart.innerHTML = rightTitle;
  28250. rightPart.style.fontSize = "12px";
  28251. rightPart.style.maxWidth = "200px";
  28252. container.appendChild(leftPart);
  28253. container.appendChild(rightPart);
  28254. label.appendChild(container);
  28255. root.appendChild(label);
  28256. root.appendChild(document.createElement("br"));
  28257. };
  28258. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28259. if (tag === void 0) { tag = null; }
  28260. var label = document.createElement("label");
  28261. var checkBox = document.createElement("input");
  28262. checkBox.type = "checkbox";
  28263. checkBox.checked = initialState;
  28264. checkBox.addEventListener("change", function (evt) {
  28265. task(evt.target, tag);
  28266. });
  28267. label.appendChild(checkBox);
  28268. label.appendChild(document.createTextNode(title));
  28269. root.appendChild(label);
  28270. root.appendChild(document.createElement("br"));
  28271. };
  28272. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28273. if (tag === void 0) { tag = null; }
  28274. var button = document.createElement("button");
  28275. button.innerHTML = title;
  28276. button.style.height = "24px";
  28277. button.style.color = "#444444";
  28278. button.style.border = "1px solid white";
  28279. button.className = "debugLayerButton";
  28280. button.addEventListener("click", function (evt) {
  28281. task(evt.target, tag);
  28282. });
  28283. root.appendChild(button);
  28284. root.appendChild(document.createElement("br"));
  28285. };
  28286. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28287. if (tag === void 0) { tag = null; }
  28288. var label = document.createElement("label");
  28289. var boundingBoxesRadio = document.createElement("input");
  28290. boundingBoxesRadio.type = "radio";
  28291. boundingBoxesRadio.name = name;
  28292. boundingBoxesRadio.checked = initialState;
  28293. boundingBoxesRadio.addEventListener("change", function (evt) {
  28294. task(evt.target, tag);
  28295. });
  28296. label.appendChild(boundingBoxesRadio);
  28297. label.appendChild(document.createTextNode(title));
  28298. root.appendChild(label);
  28299. root.appendChild(document.createElement("br"));
  28300. };
  28301. DebugLayer.prototype._generateDOMelements = function () {
  28302. var _this = this;
  28303. this._globalDiv.id = "DebugLayer";
  28304. this._globalDiv.style.position = "absolute";
  28305. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28306. this._globalDiv.style.fontSize = "14px";
  28307. this._globalDiv.style.color = "white";
  28308. // Drawing canvas
  28309. this._drawingCanvas = document.createElement("canvas");
  28310. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28311. this._drawingCanvas.style.position = "absolute";
  28312. this._drawingCanvas.style.pointerEvents = "none";
  28313. this._drawingContext = this._drawingCanvas.getContext("2d");
  28314. this._globalDiv.appendChild(this._drawingCanvas);
  28315. if (this._showUI) {
  28316. var background = "rgba(128, 128, 128, 0.4)";
  28317. var border = "rgb(180, 180, 180) solid 1px";
  28318. // Stats
  28319. this._statsDiv = document.createElement("div");
  28320. this._statsDiv.id = "DebugLayerStats";
  28321. this._statsDiv.style.border = border;
  28322. this._statsDiv.style.position = "absolute";
  28323. this._statsDiv.style.background = background;
  28324. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28325. this._generateheader(this._statsDiv, "STATISTICS");
  28326. this._statsSubsetDiv = document.createElement("div");
  28327. this._statsSubsetDiv.style.paddingTop = "5px";
  28328. this._statsSubsetDiv.style.paddingBottom = "5px";
  28329. this._statsSubsetDiv.style.overflowY = "auto";
  28330. this._statsDiv.appendChild(this._statsSubsetDiv);
  28331. // Tree
  28332. this._treeDiv = document.createElement("div");
  28333. this._treeDiv.id = "DebugLayerTree";
  28334. this._treeDiv.style.border = border;
  28335. this._treeDiv.style.position = "absolute";
  28336. this._treeDiv.style.background = background;
  28337. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28338. this._treeDiv.style.display = "none";
  28339. this._generateheader(this._treeDiv, "MESHES TREE");
  28340. this._treeSubsetDiv = document.createElement("div");
  28341. this._treeSubsetDiv.style.paddingTop = "5px";
  28342. this._treeSubsetDiv.style.paddingRight = "5px";
  28343. this._treeSubsetDiv.style.overflowY = "auto";
  28344. this._treeSubsetDiv.style.maxHeight = "300px";
  28345. this._treeDiv.appendChild(this._treeSubsetDiv);
  28346. this._needToRefreshMeshesTree = true;
  28347. // Logs
  28348. this._logDiv = document.createElement("div");
  28349. this._logDiv.style.border = border;
  28350. this._logDiv.id = "DebugLayerLogs";
  28351. this._logDiv.style.position = "absolute";
  28352. this._logDiv.style.background = background;
  28353. this._logDiv.style.padding = "0px 0px 0px 5px";
  28354. this._logDiv.style.display = "none";
  28355. this._generateheader(this._logDiv, "LOGS");
  28356. this._logSubsetDiv = document.createElement("div");
  28357. this._logSubsetDiv.style.height = "127px";
  28358. this._logSubsetDiv.style.paddingTop = "5px";
  28359. this._logSubsetDiv.style.overflowY = "auto";
  28360. this._logSubsetDiv.style.fontSize = "12px";
  28361. this._logSubsetDiv.style.fontFamily = "consolas";
  28362. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28363. this._logDiv.appendChild(this._logSubsetDiv);
  28364. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28365. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28366. };
  28367. // Options
  28368. this._optionsDiv = document.createElement("div");
  28369. this._optionsDiv.id = "DebugLayerOptions";
  28370. this._optionsDiv.style.border = border;
  28371. this._optionsDiv.style.position = "absolute";
  28372. this._optionsDiv.style.background = background;
  28373. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28374. this._optionsDiv.style.overflowY = "auto";
  28375. this._generateheader(this._optionsDiv, "OPTIONS");
  28376. this._optionsSubsetDiv = document.createElement("div");
  28377. this._optionsSubsetDiv.style.paddingTop = "5px";
  28378. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28379. this._optionsSubsetDiv.style.overflowY = "auto";
  28380. this._optionsSubsetDiv.style.maxHeight = "200px";
  28381. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28382. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28383. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28384. _this._displayStatistics = element.checked;
  28385. });
  28386. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28387. _this._displayLogs = element.checked;
  28388. });
  28389. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28390. _this._displayTree = element.checked;
  28391. _this._needToRefreshMeshesTree = true;
  28392. });
  28393. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28394. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28395. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28396. _this._scene.forceShowBoundingBoxes = element.checked;
  28397. });
  28398. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28399. _this._labelsEnabled = element.checked;
  28400. if (!_this._labelsEnabled) {
  28401. _this._clearLabels();
  28402. }
  28403. });
  28404. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28405. if (element.checked) {
  28406. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28407. }
  28408. else {
  28409. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28410. }
  28411. });
  28412. ;
  28413. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28414. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28415. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28416. if (element.checked) {
  28417. _this._scene.forceWireframe = false;
  28418. _this._scene.forcePointsCloud = false;
  28419. }
  28420. });
  28421. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28422. if (element.checked) {
  28423. _this._scene.forceWireframe = true;
  28424. _this._scene.forcePointsCloud = false;
  28425. }
  28426. });
  28427. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28428. if (element.checked) {
  28429. _this._scene.forceWireframe = false;
  28430. _this._scene.forcePointsCloud = true;
  28431. }
  28432. });
  28433. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28434. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28435. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28436. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28437. });
  28438. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28439. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28440. });
  28441. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28442. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28443. });
  28444. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28445. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28446. });
  28447. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28448. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28449. });
  28450. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28451. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28452. });
  28453. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28454. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28455. });
  28456. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28457. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28458. });
  28459. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28460. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28461. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28462. _this._scene.animationsEnabled = element.checked;
  28463. });
  28464. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28465. _this._scene.collisionsEnabled = element.checked;
  28466. });
  28467. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28468. _this._scene.fogEnabled = element.checked;
  28469. });
  28470. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28471. _this._scene.lensFlaresEnabled = element.checked;
  28472. });
  28473. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28474. _this._scene.lightsEnabled = element.checked;
  28475. });
  28476. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28477. _this._scene.particlesEnabled = element.checked;
  28478. });
  28479. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28480. _this._scene.postProcessesEnabled = element.checked;
  28481. });
  28482. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28483. _this._scene.proceduralTexturesEnabled = element.checked;
  28484. });
  28485. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28486. _this._scene.renderTargetsEnabled = element.checked;
  28487. });
  28488. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28489. _this._scene.shadowsEnabled = element.checked;
  28490. });
  28491. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28492. _this._scene.skeletonsEnabled = element.checked;
  28493. });
  28494. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28495. _this._scene.spritesEnabled = element.checked;
  28496. });
  28497. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28498. _this._scene.texturesEnabled = element.checked;
  28499. });
  28500. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28501. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28502. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28503. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28504. if (element.checked) {
  28505. _this._scene.headphone = true;
  28506. }
  28507. });
  28508. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28509. if (element.checked) {
  28510. _this._scene.headphone = false;
  28511. }
  28512. });
  28513. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28514. _this._scene.audioEnabled = !element.checked;
  28515. });
  28516. }
  28517. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28518. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28519. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28520. _this._scene.dumpNextRenderTargets = true;
  28521. });
  28522. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28523. this._globalDiv.appendChild(this._statsDiv);
  28524. this._globalDiv.appendChild(this._logDiv);
  28525. this._globalDiv.appendChild(this._optionsDiv);
  28526. this._globalDiv.appendChild(this._treeDiv);
  28527. }
  28528. };
  28529. DebugLayer.prototype._displayStats = function () {
  28530. var scene = this._scene;
  28531. var engine = scene.getEngine();
  28532. var glInfo = engine.getGlInfo();
  28533. 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>";
  28534. if (this.customStatsFunction) {
  28535. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28536. }
  28537. };
  28538. return DebugLayer;
  28539. })();
  28540. BABYLON.DebugLayer = DebugLayer;
  28541. })(BABYLON || (BABYLON = {}));
  28542. //# sourceMappingURL=babylon.debugLayer.js.map
  28543. var BABYLON;
  28544. (function (BABYLON) {
  28545. var RawTexture = (function (_super) {
  28546. __extends(RawTexture, _super);
  28547. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28549. if (invertY === void 0) { invertY = false; }
  28550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28551. _super.call(this, null, scene, !generateMipMaps, invertY);
  28552. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28553. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28554. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28555. }
  28556. // Statics
  28557. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28558. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28559. if (invertY === void 0) { invertY = false; }
  28560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28561. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28562. };
  28563. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28564. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28565. if (invertY === void 0) { invertY = false; }
  28566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28567. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28568. };
  28569. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28570. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28571. if (invertY === void 0) { invertY = false; }
  28572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28573. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28574. };
  28575. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28576. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28577. if (invertY === void 0) { invertY = false; }
  28578. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28579. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28580. };
  28581. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28582. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28583. if (invertY === void 0) { invertY = false; }
  28584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28585. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28586. };
  28587. return RawTexture;
  28588. })(BABYLON.Texture);
  28589. BABYLON.RawTexture = RawTexture;
  28590. })(BABYLON || (BABYLON = {}));
  28591. //# sourceMappingURL=babylon.rawTexture.js.map
  28592. var BABYLON;
  28593. (function (BABYLON) {
  28594. var IndexedVector2 = (function (_super) {
  28595. __extends(IndexedVector2, _super);
  28596. function IndexedVector2(original, index) {
  28597. _super.call(this, original.x, original.y);
  28598. this.index = index;
  28599. }
  28600. return IndexedVector2;
  28601. })(BABYLON.Vector2);
  28602. var PolygonPoints = (function () {
  28603. function PolygonPoints() {
  28604. this.elements = new Array();
  28605. }
  28606. PolygonPoints.prototype.add = function (originalPoints) {
  28607. var _this = this;
  28608. var result = new Array();
  28609. originalPoints.forEach(function (point) {
  28610. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28611. var newPoint = new IndexedVector2(point, _this.elements.length);
  28612. result.push(newPoint);
  28613. _this.elements.push(newPoint);
  28614. }
  28615. });
  28616. return result;
  28617. };
  28618. PolygonPoints.prototype.computeBounds = function () {
  28619. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28620. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28621. this.elements.forEach(function (point) {
  28622. // x
  28623. if (point.x < lmin.x) {
  28624. lmin.x = point.x;
  28625. }
  28626. else if (point.x > lmax.x) {
  28627. lmax.x = point.x;
  28628. }
  28629. // y
  28630. if (point.y < lmin.y) {
  28631. lmin.y = point.y;
  28632. }
  28633. else if (point.y > lmax.y) {
  28634. lmax.y = point.y;
  28635. }
  28636. });
  28637. return {
  28638. min: lmin,
  28639. max: lmax,
  28640. width: lmax.x - lmin.x,
  28641. height: lmax.y - lmin.y
  28642. };
  28643. };
  28644. return PolygonPoints;
  28645. })();
  28646. var Polygon = (function () {
  28647. function Polygon() {
  28648. }
  28649. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28650. return [
  28651. new BABYLON.Vector2(xmin, ymin),
  28652. new BABYLON.Vector2(xmax, ymin),
  28653. new BABYLON.Vector2(xmax, ymax),
  28654. new BABYLON.Vector2(xmin, ymax)
  28655. ];
  28656. };
  28657. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28658. if (cx === void 0) { cx = 0; }
  28659. if (cy === void 0) { cy = 0; }
  28660. if (numberOfSides === void 0) { numberOfSides = 32; }
  28661. var result = new Array();
  28662. var angle = 0;
  28663. var increment = (Math.PI * 2) / numberOfSides;
  28664. for (var i = 0; i < numberOfSides; i++) {
  28665. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28666. angle -= increment;
  28667. }
  28668. return result;
  28669. };
  28670. Polygon.Parse = function (input) {
  28671. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28672. var i, result = [];
  28673. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28674. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28675. }
  28676. return result;
  28677. };
  28678. Polygon.StartingAt = function (x, y) {
  28679. return BABYLON.Path2.StartingAt(x, y);
  28680. };
  28681. return Polygon;
  28682. })();
  28683. BABYLON.Polygon = Polygon;
  28684. var PolygonMeshBuilder = (function () {
  28685. function PolygonMeshBuilder(name, contours, scene) {
  28686. this._points = new PolygonPoints();
  28687. if (!("poly2tri" in window)) {
  28688. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28689. }
  28690. this._name = name;
  28691. this._scene = scene;
  28692. var points;
  28693. if (contours instanceof BABYLON.Path2) {
  28694. points = contours.getPoints();
  28695. }
  28696. else {
  28697. points = contours;
  28698. }
  28699. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28700. }
  28701. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28702. this._swctx.addHole(this._points.add(hole));
  28703. return this;
  28704. };
  28705. PolygonMeshBuilder.prototype.build = function (updatable) {
  28706. if (updatable === void 0) { updatable = false; }
  28707. var result = new BABYLON.Mesh(this._name, this._scene);
  28708. var normals = [];
  28709. var positions = [];
  28710. var uvs = [];
  28711. var bounds = this._points.computeBounds();
  28712. this._points.elements.forEach(function (p) {
  28713. normals.push(0, 1.0, 0);
  28714. positions.push(p.x, 0, p.y);
  28715. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28716. });
  28717. var indices = [];
  28718. this._swctx.triangulate();
  28719. this._swctx.getTriangles().forEach(function (triangle) {
  28720. triangle.getPoints().forEach(function (point) {
  28721. indices.push(point.index);
  28722. });
  28723. });
  28724. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28725. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28726. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28727. result.setIndices(indices);
  28728. return result;
  28729. };
  28730. return PolygonMeshBuilder;
  28731. })();
  28732. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28733. })(BABYLON || (BABYLON = {}));
  28734. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28735. (function (BABYLON) {
  28736. var SimplificationSettings = (function () {
  28737. function SimplificationSettings(quality, distance, optimizeMesh) {
  28738. this.quality = quality;
  28739. this.distance = distance;
  28740. this.optimizeMesh = optimizeMesh;
  28741. }
  28742. return SimplificationSettings;
  28743. })();
  28744. BABYLON.SimplificationSettings = SimplificationSettings;
  28745. var SimplificationQueue = (function () {
  28746. function SimplificationQueue() {
  28747. this.running = false;
  28748. this._simplificationArray = [];
  28749. }
  28750. SimplificationQueue.prototype.addTask = function (task) {
  28751. this._simplificationArray.push(task);
  28752. };
  28753. SimplificationQueue.prototype.executeNext = function () {
  28754. var task = this._simplificationArray.pop();
  28755. if (task) {
  28756. this.running = true;
  28757. this.runSimplification(task);
  28758. }
  28759. else {
  28760. this.running = false;
  28761. }
  28762. };
  28763. SimplificationQueue.prototype.runSimplification = function (task) {
  28764. var _this = this;
  28765. if (task.parallelProcessing) {
  28766. //parallel simplifier
  28767. task.settings.forEach(function (setting) {
  28768. var simplifier = _this.getSimplifier(task);
  28769. simplifier.simplify(setting, function (newMesh) {
  28770. task.mesh.addLODLevel(setting.distance, newMesh);
  28771. newMesh.isVisible = true;
  28772. //check if it is the last
  28773. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28774. //all done, run the success callback.
  28775. task.successCallback();
  28776. }
  28777. _this.executeNext();
  28778. });
  28779. });
  28780. }
  28781. else {
  28782. //single simplifier.
  28783. var simplifier = this.getSimplifier(task);
  28784. var runDecimation = function (setting, callback) {
  28785. simplifier.simplify(setting, function (newMesh) {
  28786. task.mesh.addLODLevel(setting.distance, newMesh);
  28787. newMesh.isVisible = true;
  28788. //run the next quality level
  28789. callback();
  28790. });
  28791. };
  28792. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28793. runDecimation(task.settings[loop.index], function () {
  28794. loop.executeNext();
  28795. });
  28796. }, function () {
  28797. //execution ended, run the success callback.
  28798. if (task.successCallback) {
  28799. task.successCallback();
  28800. }
  28801. _this.executeNext();
  28802. });
  28803. }
  28804. };
  28805. SimplificationQueue.prototype.getSimplifier = function (task) {
  28806. switch (task.simplificationType) {
  28807. case 0 /* QUADRATIC */:
  28808. default:
  28809. return new QuadraticErrorSimplification(task.mesh);
  28810. }
  28811. };
  28812. return SimplificationQueue;
  28813. })();
  28814. BABYLON.SimplificationQueue = SimplificationQueue;
  28815. /**
  28816. * The implemented types of simplification.
  28817. * At the moment only Quadratic Error Decimation is implemented.
  28818. */
  28819. (function (SimplificationType) {
  28820. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28821. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28822. var SimplificationType = BABYLON.SimplificationType;
  28823. var DecimationTriangle = (function () {
  28824. function DecimationTriangle(vertices) {
  28825. this.vertices = vertices;
  28826. this.error = new Array(4);
  28827. this.deleted = false;
  28828. this.isDirty = false;
  28829. this.deletePending = false;
  28830. this.borderFactor = 0;
  28831. }
  28832. return DecimationTriangle;
  28833. })();
  28834. BABYLON.DecimationTriangle = DecimationTriangle;
  28835. var DecimationVertex = (function () {
  28836. function DecimationVertex(position, id) {
  28837. this.position = position;
  28838. this.id = id;
  28839. this.isBorder = true;
  28840. this.q = new QuadraticMatrix();
  28841. this.triangleCount = 0;
  28842. this.triangleStart = 0;
  28843. this.originalOffsets = [];
  28844. }
  28845. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28846. this.position.copyFrom(newPosition);
  28847. };
  28848. return DecimationVertex;
  28849. })();
  28850. BABYLON.DecimationVertex = DecimationVertex;
  28851. var QuadraticMatrix = (function () {
  28852. function QuadraticMatrix(data) {
  28853. this.data = new Array(10);
  28854. for (var i = 0; i < 10; ++i) {
  28855. if (data && data[i]) {
  28856. this.data[i] = data[i];
  28857. }
  28858. else {
  28859. this.data[i] = 0;
  28860. }
  28861. }
  28862. }
  28863. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28864. 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];
  28865. return det;
  28866. };
  28867. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28868. for (var i = 0; i < 10; ++i) {
  28869. this.data[i] += matrix.data[i];
  28870. }
  28871. };
  28872. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28873. for (var i = 0; i < 10; ++i) {
  28874. this.data[i] += data[i];
  28875. }
  28876. };
  28877. QuadraticMatrix.prototype.add = function (matrix) {
  28878. var m = new QuadraticMatrix();
  28879. for (var i = 0; i < 10; ++i) {
  28880. m.data[i] = this.data[i] + matrix.data[i];
  28881. }
  28882. return m;
  28883. };
  28884. QuadraticMatrix.FromData = function (a, b, c, d) {
  28885. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28886. };
  28887. //returning an array to avoid garbage collection
  28888. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28889. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28890. };
  28891. return QuadraticMatrix;
  28892. })();
  28893. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28894. var Reference = (function () {
  28895. function Reference(vertexId, triangleId) {
  28896. this.vertexId = vertexId;
  28897. this.triangleId = triangleId;
  28898. }
  28899. return Reference;
  28900. })();
  28901. BABYLON.Reference = Reference;
  28902. /**
  28903. * An implementation of the Quadratic Error simplification algorithm.
  28904. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28905. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28906. * @author RaananW
  28907. */
  28908. var QuadraticErrorSimplification = (function () {
  28909. function QuadraticErrorSimplification(_mesh) {
  28910. this._mesh = _mesh;
  28911. this.initialized = false;
  28912. this.syncIterations = 5000;
  28913. this.aggressiveness = 7;
  28914. this.decimationIterations = 100;
  28915. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28916. }
  28917. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28918. var _this = this;
  28919. this.initDecimatedMesh();
  28920. //iterating through the submeshes array, one after the other.
  28921. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28922. _this.initWithMesh(loop.index, function () {
  28923. _this.runDecimation(settings, loop.index, function () {
  28924. loop.executeNext();
  28925. });
  28926. }, settings.optimizeMesh);
  28927. }, function () {
  28928. setTimeout(function () {
  28929. successCallback(_this._reconstructedMesh);
  28930. }, 0);
  28931. });
  28932. };
  28933. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28934. var _this = this;
  28935. var gCount = 0;
  28936. triangle.vertices.forEach(function (vertex) {
  28937. var count = 0;
  28938. var vPos = vertex.position;
  28939. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28940. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28941. ++count;
  28942. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28943. ++count;
  28944. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28945. ++count;
  28946. if (count > 1) {
  28947. ++gCount;
  28948. }
  28949. ;
  28950. });
  28951. if (gCount > 1) {
  28952. console.log(triangle, gCount);
  28953. }
  28954. return gCount > 1;
  28955. };
  28956. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28957. var _this = this;
  28958. var targetCount = ~~(this.triangles.length * settings.quality);
  28959. var deletedTriangles = 0;
  28960. var triangleCount = this.triangles.length;
  28961. var iterationFunction = function (iteration, callback) {
  28962. setTimeout(function () {
  28963. if (iteration % 5 === 0) {
  28964. _this.updateMesh(iteration === 0);
  28965. }
  28966. for (var i = 0; i < _this.triangles.length; ++i) {
  28967. _this.triangles[i].isDirty = false;
  28968. }
  28969. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28970. var trianglesIterator = function (i) {
  28971. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28972. var t = _this.triangles[tIdx];
  28973. if (!t)
  28974. return;
  28975. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28976. return;
  28977. }
  28978. for (var j = 0; j < 3; ++j) {
  28979. if (t.error[j] < threshold) {
  28980. var deleted0 = [];
  28981. var deleted1 = [];
  28982. var v0 = t.vertices[j];
  28983. var v1 = t.vertices[(j + 1) % 3];
  28984. if (v0.isBorder !== v1.isBorder)
  28985. continue;
  28986. var p = BABYLON.Vector3.Zero();
  28987. var n = BABYLON.Vector3.Zero();
  28988. var uv = BABYLON.Vector2.Zero();
  28989. var color = new BABYLON.Color4(0, 0, 0, 1);
  28990. _this.calculateError(v0, v1, p, n, uv, color);
  28991. var delTr = [];
  28992. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28993. continue;
  28994. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28995. continue;
  28996. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28997. continue;
  28998. var uniqueArray = [];
  28999. delTr.forEach(function (deletedT) {
  29000. if (uniqueArray.indexOf(deletedT) === -1) {
  29001. deletedT.deletePending = true;
  29002. uniqueArray.push(deletedT);
  29003. }
  29004. });
  29005. if (uniqueArray.length % 2 != 0) {
  29006. continue;
  29007. }
  29008. v0.q = v1.q.add(v0.q);
  29009. v0.updatePosition(p);
  29010. var tStart = _this.references.length;
  29011. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29012. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29013. var tCount = _this.references.length - tStart;
  29014. if (tCount <= v0.triangleCount) {
  29015. if (tCount) {
  29016. for (var c = 0; c < tCount; c++) {
  29017. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29018. }
  29019. }
  29020. }
  29021. else {
  29022. v0.triangleStart = tStart;
  29023. }
  29024. v0.triangleCount = tCount;
  29025. break;
  29026. }
  29027. }
  29028. };
  29029. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  29030. return (triangleCount - deletedTriangles <= targetCount);
  29031. });
  29032. }, 0);
  29033. };
  29034. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29035. if (triangleCount - deletedTriangles <= targetCount)
  29036. loop.breakLoop();
  29037. else {
  29038. iterationFunction(loop.index, function () {
  29039. loop.executeNext();
  29040. });
  29041. }
  29042. }, function () {
  29043. setTimeout(function () {
  29044. //reconstruct this part of the mesh
  29045. _this.reconstructMesh(submeshIndex);
  29046. successCallback();
  29047. }, 0);
  29048. });
  29049. };
  29050. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29051. var _this = this;
  29052. this.vertices = [];
  29053. this.triangles = [];
  29054. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29055. var indices = this._mesh.getIndices();
  29056. var submesh = this._mesh.subMeshes[submeshIndex];
  29057. var findInVertices = function (positionToSearch) {
  29058. if (optimizeMesh) {
  29059. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29060. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29061. return _this.vertices[ii];
  29062. }
  29063. }
  29064. }
  29065. return null;
  29066. };
  29067. var vertexReferences = [];
  29068. var vertexInit = function (i) {
  29069. var offset = i + submesh.verticesStart;
  29070. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29071. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29072. vertex.originalOffsets.push(offset);
  29073. if (vertex.id == _this.vertices.length) {
  29074. _this.vertices.push(vertex);
  29075. }
  29076. vertexReferences.push(vertex.id);
  29077. };
  29078. //var totalVertices = mesh.getTotalVertices();
  29079. var totalVertices = submesh.verticesCount;
  29080. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29081. var indicesInit = function (i) {
  29082. var offset = (submesh.indexStart / 3) + i;
  29083. var pos = (offset * 3);
  29084. var i0 = indices[pos + 0];
  29085. var i1 = indices[pos + 1];
  29086. var i2 = indices[pos + 2];
  29087. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29088. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29089. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29090. var triangle = new DecimationTriangle([v0, v1, v2]);
  29091. triangle.originalOffset = pos;
  29092. _this.triangles.push(triangle);
  29093. };
  29094. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29095. _this.init(callback);
  29096. });
  29097. });
  29098. };
  29099. QuadraticErrorSimplification.prototype.init = function (callback) {
  29100. var _this = this;
  29101. var triangleInit1 = function (i) {
  29102. var t = _this.triangles[i];
  29103. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29104. for (var j = 0; j < 3; j++) {
  29105. 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))));
  29106. }
  29107. };
  29108. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29109. var triangleInit2 = function (i) {
  29110. var t = _this.triangles[i];
  29111. for (var j = 0; j < 3; ++j) {
  29112. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29113. }
  29114. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29115. };
  29116. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29117. _this.initialized = true;
  29118. callback();
  29119. });
  29120. });
  29121. };
  29122. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29123. var newTriangles = [];
  29124. var i;
  29125. for (i = 0; i < this.vertices.length; ++i) {
  29126. this.vertices[i].triangleCount = 0;
  29127. }
  29128. var t;
  29129. var j;
  29130. for (i = 0; i < this.triangles.length; ++i) {
  29131. if (!this.triangles[i].deleted) {
  29132. t = this.triangles[i];
  29133. for (j = 0; j < 3; ++j) {
  29134. t.vertices[j].triangleCount = 1;
  29135. }
  29136. newTriangles.push(t);
  29137. }
  29138. }
  29139. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29140. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29141. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29142. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29143. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29144. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29145. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29146. var vertexCount = 0;
  29147. for (i = 0; i < this.vertices.length; ++i) {
  29148. var vertex = this.vertices[i];
  29149. vertex.id = vertexCount;
  29150. if (vertex.triangleCount) {
  29151. vertex.originalOffsets.forEach(function (originalOffset) {
  29152. newPositionData.push(vertex.position.x);
  29153. newPositionData.push(vertex.position.y);
  29154. newPositionData.push(vertex.position.z);
  29155. newNormalData.push(normalData[originalOffset * 3]);
  29156. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29157. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29158. if (uvs && uvs.length) {
  29159. newUVsData.push(uvs[(originalOffset * 2)]);
  29160. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29161. }
  29162. else if (colorsData && colorsData.length) {
  29163. newColorsData.push(colorsData[(originalOffset * 4)]);
  29164. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29165. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29166. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29167. }
  29168. ++vertexCount;
  29169. });
  29170. }
  29171. }
  29172. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29173. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29174. var submeshesArray = this._reconstructedMesh.subMeshes;
  29175. this._reconstructedMesh.subMeshes = [];
  29176. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29177. var originalIndices = this._mesh.getIndices();
  29178. for (i = 0; i < newTriangles.length; ++i) {
  29179. var t = newTriangles[i];
  29180. //now get the new referencing point for each vertex
  29181. [0, 1, 2].forEach(function (idx) {
  29182. var id = originalIndices[t.originalOffset + idx];
  29183. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29184. if (offset < 0)
  29185. offset = 0;
  29186. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29187. });
  29188. }
  29189. //overwriting the old vertex buffers and indices.
  29190. this._reconstructedMesh.setIndices(newIndicesArray);
  29191. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29192. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29193. if (newUVsData.length > 0)
  29194. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29195. if (newColorsData.length > 0)
  29196. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29197. //create submesh
  29198. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29199. if (submeshIndex > 0) {
  29200. this._reconstructedMesh.subMeshes = [];
  29201. submeshesArray.forEach(function (submesh) {
  29202. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29203. });
  29204. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29205. }
  29206. };
  29207. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29208. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29209. this._reconstructedMesh.material = this._mesh.material;
  29210. this._reconstructedMesh.parent = this._mesh.parent;
  29211. this._reconstructedMesh.isVisible = false;
  29212. };
  29213. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29214. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29215. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29216. if (t.deleted)
  29217. continue;
  29218. var s = this.references[vertex1.triangleStart + i].vertexId;
  29219. var v1 = t.vertices[(s + 1) % 3];
  29220. var v2 = t.vertices[(s + 2) % 3];
  29221. if ((v1 === vertex2 || v2 === vertex2)) {
  29222. deletedArray[i] = true;
  29223. delTr.push(t);
  29224. continue;
  29225. }
  29226. var d1 = v1.position.subtract(point);
  29227. d1 = d1.normalize();
  29228. var d2 = v2.position.subtract(point);
  29229. d2 = d2.normalize();
  29230. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29231. return true;
  29232. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29233. deletedArray[i] = false;
  29234. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29235. return true;
  29236. }
  29237. return false;
  29238. };
  29239. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29240. var newDeleted = deletedTriangles;
  29241. for (var i = 0; i < vertex.triangleCount; ++i) {
  29242. var ref = this.references[vertex.triangleStart + i];
  29243. var t = this.triangles[ref.triangleId];
  29244. if (t.deleted)
  29245. continue;
  29246. if (deletedArray[i] && t.deletePending) {
  29247. t.deleted = true;
  29248. newDeleted++;
  29249. continue;
  29250. }
  29251. t.vertices[ref.vertexId] = origVertex;
  29252. t.isDirty = true;
  29253. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29254. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29255. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29256. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29257. this.references.push(ref);
  29258. }
  29259. return newDeleted;
  29260. };
  29261. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29262. for (var i = 0; i < this.vertices.length; ++i) {
  29263. var vCount = [];
  29264. var vId = [];
  29265. var v = this.vertices[i];
  29266. var j;
  29267. for (j = 0; j < v.triangleCount; ++j) {
  29268. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29269. for (var ii = 0; ii < 3; ii++) {
  29270. var ofs = 0;
  29271. var vv = triangle.vertices[ii];
  29272. while (ofs < vCount.length) {
  29273. if (vId[ofs] === vv.id)
  29274. break;
  29275. ++ofs;
  29276. }
  29277. if (ofs === vCount.length) {
  29278. vCount.push(1);
  29279. vId.push(vv.id);
  29280. }
  29281. else {
  29282. vCount[ofs]++;
  29283. }
  29284. }
  29285. }
  29286. for (j = 0; j < vCount.length; ++j) {
  29287. if (vCount[j] === 1) {
  29288. this.vertices[vId[j]].isBorder = true;
  29289. }
  29290. else {
  29291. this.vertices[vId[j]].isBorder = false;
  29292. }
  29293. }
  29294. }
  29295. };
  29296. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29297. if (identifyBorders === void 0) { identifyBorders = false; }
  29298. var i;
  29299. if (!identifyBorders) {
  29300. var newTrianglesVector = [];
  29301. for (i = 0; i < this.triangles.length; ++i) {
  29302. if (!this.triangles[i].deleted) {
  29303. newTrianglesVector.push(this.triangles[i]);
  29304. }
  29305. }
  29306. this.triangles = newTrianglesVector;
  29307. }
  29308. for (i = 0; i < this.vertices.length; ++i) {
  29309. this.vertices[i].triangleCount = 0;
  29310. this.vertices[i].triangleStart = 0;
  29311. }
  29312. var t;
  29313. var j;
  29314. var v;
  29315. for (i = 0; i < this.triangles.length; ++i) {
  29316. t = this.triangles[i];
  29317. for (j = 0; j < 3; ++j) {
  29318. v = t.vertices[j];
  29319. v.triangleCount++;
  29320. }
  29321. }
  29322. var tStart = 0;
  29323. for (i = 0; i < this.vertices.length; ++i) {
  29324. this.vertices[i].triangleStart = tStart;
  29325. tStart += this.vertices[i].triangleCount;
  29326. this.vertices[i].triangleCount = 0;
  29327. }
  29328. var newReferences = new Array(this.triangles.length * 3);
  29329. for (i = 0; i < this.triangles.length; ++i) {
  29330. t = this.triangles[i];
  29331. for (j = 0; j < 3; ++j) {
  29332. v = t.vertices[j];
  29333. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29334. v.triangleCount++;
  29335. }
  29336. }
  29337. this.references = newReferences;
  29338. if (identifyBorders) {
  29339. this.identifyBorder();
  29340. }
  29341. };
  29342. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29343. var x = point.x;
  29344. var y = point.y;
  29345. var z = point.z;
  29346. 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];
  29347. };
  29348. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29349. var q = vertex1.q.add(vertex2.q);
  29350. var border = vertex1.isBorder && vertex2.isBorder;
  29351. var error = 0;
  29352. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29353. if (qDet !== 0 && !border) {
  29354. if (!pointResult) {
  29355. pointResult = BABYLON.Vector3.Zero();
  29356. }
  29357. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29358. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29359. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29360. error = this.vertexError(q, pointResult);
  29361. }
  29362. else {
  29363. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29364. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29365. var error1 = this.vertexError(q, vertex1.position);
  29366. var error2 = this.vertexError(q, vertex2.position);
  29367. var error3 = this.vertexError(q, p3);
  29368. error = Math.min(error1, error2, error3);
  29369. if (error === error1) {
  29370. if (pointResult) {
  29371. pointResult.copyFrom(vertex1.position);
  29372. }
  29373. }
  29374. else if (error === error2) {
  29375. if (pointResult) {
  29376. pointResult.copyFrom(vertex2.position);
  29377. }
  29378. }
  29379. else {
  29380. if (pointResult) {
  29381. pointResult.copyFrom(p3);
  29382. }
  29383. }
  29384. }
  29385. return error;
  29386. };
  29387. return QuadraticErrorSimplification;
  29388. })();
  29389. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29390. })(BABYLON || (BABYLON = {}));
  29391. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29392. (function (BABYLON) {
  29393. var Analyser = (function () {
  29394. function Analyser(scene) {
  29395. this.SMOOTHING = 0.75;
  29396. this.FFT_SIZE = 512;
  29397. this.BARGRAPHAMPLITUDE = 256;
  29398. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29399. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29400. this._scene = scene;
  29401. this._audioEngine = BABYLON.Engine.audioEngine;
  29402. if (this._audioEngine.canUseWebAudio) {
  29403. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29404. this._webAudioAnalyser.minDecibels = -140;
  29405. this._webAudioAnalyser.maxDecibels = 0;
  29406. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29407. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29408. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29409. }
  29410. }
  29411. Analyser.prototype.getFrequencyBinCount = function () {
  29412. if (this._audioEngine.canUseWebAudio) {
  29413. return this._webAudioAnalyser.frequencyBinCount;
  29414. }
  29415. else {
  29416. return 0;
  29417. }
  29418. };
  29419. Analyser.prototype.getByteFrequencyData = function () {
  29420. if (this._audioEngine.canUseWebAudio) {
  29421. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29422. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29423. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29424. }
  29425. return this._byteFreqs;
  29426. };
  29427. Analyser.prototype.getByteTimeDomainData = function () {
  29428. if (this._audioEngine.canUseWebAudio) {
  29429. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29430. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29431. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29432. }
  29433. return this._byteTime;
  29434. };
  29435. Analyser.prototype.getFloatFrequencyData = function () {
  29436. if (this._audioEngine.canUseWebAudio) {
  29437. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29438. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29439. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29440. }
  29441. return this._floatFreqs;
  29442. };
  29443. Analyser.prototype.drawDebugCanvas = function () {
  29444. var _this = this;
  29445. if (this._audioEngine.canUseWebAudio) {
  29446. if (!this._debugCanvas) {
  29447. this._debugCanvas = document.createElement("canvas");
  29448. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29449. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29450. this._debugCanvas.style.position = "absolute";
  29451. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29452. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29453. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29454. document.body.appendChild(this._debugCanvas);
  29455. this._registerFunc = function () {
  29456. _this.drawDebugCanvas();
  29457. };
  29458. this._scene.registerBeforeRender(this._registerFunc);
  29459. }
  29460. if (this._registerFunc) {
  29461. var workingArray = this.getByteFrequencyData();
  29462. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29463. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29464. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29465. var value = workingArray[i];
  29466. var percent = value / this.BARGRAPHAMPLITUDE;
  29467. var height = this.DEBUGCANVASSIZE.height * percent;
  29468. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29469. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29470. var hue = i / this.getFrequencyBinCount() * 360;
  29471. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29472. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29473. }
  29474. }
  29475. }
  29476. };
  29477. Analyser.prototype.stopDebugCanvas = function () {
  29478. if (this._debugCanvas) {
  29479. this._scene.unregisterBeforeRender(this._registerFunc);
  29480. this._registerFunc = null;
  29481. document.body.removeChild(this._debugCanvas);
  29482. this._debugCanvas = null;
  29483. this._debugCanvasContext = null;
  29484. }
  29485. };
  29486. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29487. if (this._audioEngine.canUseWebAudio) {
  29488. inputAudioNode.connect(this._webAudioAnalyser);
  29489. this._webAudioAnalyser.connect(outputAudioNode);
  29490. }
  29491. };
  29492. Analyser.prototype.dispose = function () {
  29493. if (this._audioEngine.canUseWebAudio) {
  29494. this._webAudioAnalyser.disconnect();
  29495. }
  29496. };
  29497. return Analyser;
  29498. })();
  29499. BABYLON.Analyser = Analyser;
  29500. })(BABYLON || (BABYLON = {}));
  29501. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29502. (function (BABYLON) {
  29503. var DepthRenderer = (function () {
  29504. function DepthRenderer(scene, type) {
  29505. var _this = this;
  29506. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29507. this._viewMatrix = BABYLON.Matrix.Zero();
  29508. this._projectionMatrix = BABYLON.Matrix.Zero();
  29509. this._transformMatrix = BABYLON.Matrix.Zero();
  29510. this._worldViewProjection = BABYLON.Matrix.Zero();
  29511. this._scene = scene;
  29512. var engine = scene.getEngine();
  29513. // Render target
  29514. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29515. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29516. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29517. this._depthMap.refreshRate = 1;
  29518. this._depthMap.renderParticles = false;
  29519. this._depthMap.renderList = null;
  29520. // Custom render function
  29521. var renderSubMesh = function (subMesh) {
  29522. var mesh = subMesh.getRenderingMesh();
  29523. var scene = _this._scene;
  29524. var engine = scene.getEngine();
  29525. // Culling
  29526. engine.setState(subMesh.getMaterial().backFaceCulling);
  29527. // Managing instances
  29528. var batch = mesh._getInstancesRenderList(subMesh._id);
  29529. if (batch.mustReturn) {
  29530. return;
  29531. }
  29532. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29533. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29534. engine.enableEffect(_this._effect);
  29535. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29536. var material = subMesh.getMaterial();
  29537. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29538. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29539. // Alpha test
  29540. if (material && material.needAlphaTesting()) {
  29541. var alphaTexture = material.getAlphaTestTexture();
  29542. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29543. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29544. }
  29545. // Bones
  29546. if (mesh.useBones) {
  29547. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29548. }
  29549. // Draw
  29550. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29551. }
  29552. };
  29553. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29554. var index;
  29555. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29556. renderSubMesh(opaqueSubMeshes.data[index]);
  29557. }
  29558. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29559. renderSubMesh(alphaTestSubMeshes.data[index]);
  29560. }
  29561. };
  29562. }
  29563. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29564. var defines = [];
  29565. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29566. var mesh = subMesh.getMesh();
  29567. var scene = mesh.getScene();
  29568. var material = subMesh.getMaterial();
  29569. // Alpha test
  29570. if (material && material.needAlphaTesting()) {
  29571. defines.push("#define ALPHATEST");
  29572. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29573. attribs.push(BABYLON.VertexBuffer.UVKind);
  29574. defines.push("#define UV1");
  29575. }
  29576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29577. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29578. defines.push("#define UV2");
  29579. }
  29580. }
  29581. // Bones
  29582. if (mesh.useBones) {
  29583. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29584. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29585. defines.push("#define BONES");
  29586. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29587. }
  29588. // Instances
  29589. if (useInstances) {
  29590. defines.push("#define INSTANCES");
  29591. attribs.push("world0");
  29592. attribs.push("world1");
  29593. attribs.push("world2");
  29594. attribs.push("world3");
  29595. }
  29596. // Get correct effect
  29597. var join = defines.join("\n");
  29598. if (this._cachedDefines !== join) {
  29599. this._cachedDefines = join;
  29600. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29601. }
  29602. return this._effect.isReady();
  29603. };
  29604. DepthRenderer.prototype.getDepthMap = function () {
  29605. return this._depthMap;
  29606. };
  29607. // Methods
  29608. DepthRenderer.prototype.dispose = function () {
  29609. this._depthMap.dispose();
  29610. };
  29611. return DepthRenderer;
  29612. })();
  29613. BABYLON.DepthRenderer = DepthRenderer;
  29614. })(BABYLON || (BABYLON = {}));
  29615. //# sourceMappingURL=babylon.depthRenderer.js.map
  29616. var BABYLON;
  29617. (function (BABYLON) {
  29618. var SSAORenderingPipeline = (function (_super) {
  29619. __extends(SSAORenderingPipeline, _super);
  29620. /**
  29621. * @constructor
  29622. * @param {string} name - The rendering pipeline name
  29623. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29624. * @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 }
  29625. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29626. */
  29627. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29628. var _this = this;
  29629. _super.call(this, scene.getEngine(), name);
  29630. // Members
  29631. /**
  29632. * The PassPostProcess id in the pipeline that contains the original scene color
  29633. * @type {string}
  29634. */
  29635. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29636. /**
  29637. * The SSAO PostProcess id in the pipeline
  29638. * @type {string}
  29639. */
  29640. this.SSAORenderEffect = "SSAORenderEffect";
  29641. /**
  29642. * The horizontal blur PostProcess id in the pipeline
  29643. * @type {string}
  29644. */
  29645. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29646. /**
  29647. * The vertical blur PostProcess id in the pipeline
  29648. * @type {string}
  29649. */
  29650. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29651. /**
  29652. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29653. * @type {string}
  29654. */
  29655. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29656. /**
  29657. * The output strength of the SSAO post-process. Default value is 1.0.
  29658. * @type {number}
  29659. */
  29660. this.totalStrength = 1.0;
  29661. /**
  29662. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29663. * @type {number}
  29664. */
  29665. this.radius = 0.0002;
  29666. /**
  29667. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29668. * Must not be equal to fallOff and superior to fallOff.
  29669. * Default value is 0.0075
  29670. * @type {number}
  29671. */
  29672. this.area = 0.0075;
  29673. /**
  29674. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29675. * Must not be equal to area and inferior to area.
  29676. * Default value is 0.0002
  29677. * @type {number}
  29678. */
  29679. this.fallOff = 0.0002;
  29680. this._firstUpdate = true;
  29681. this._scene = scene;
  29682. // Set up assets
  29683. this._createRandomTexture();
  29684. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29685. var ssaoRatio = ratio.ssaoRatio || ratio;
  29686. var combineRatio = ratio.combineRatio || ratio;
  29687. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29688. this._createSSAOPostProcess(ssaoRatio);
  29689. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29690. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29691. this._createSSAOCombinePostProcess(combineRatio);
  29692. // Set up pipeline
  29693. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29694. return _this._originalColorPostProcess;
  29695. }, true));
  29696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29697. return _this._ssaoPostProcess;
  29698. }, true));
  29699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29700. return _this._blurHPostProcess;
  29701. }, true));
  29702. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29703. return _this._blurVPostProcess;
  29704. }, true));
  29705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29706. return _this._ssaoCombinePostProcess;
  29707. }, true));
  29708. // Finish
  29709. scene.postProcessRenderPipelineManager.addPipeline(this);
  29710. if (cameras)
  29711. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29712. }
  29713. // Public Methods
  29714. /**
  29715. * Returns the horizontal blur PostProcess
  29716. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29717. */
  29718. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29719. return this._blurHPostProcess;
  29720. };
  29721. /**
  29722. * Returns the vertical blur PostProcess
  29723. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29724. */
  29725. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29726. return this._blurVPostProcess;
  29727. };
  29728. /**
  29729. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29730. */
  29731. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29732. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29733. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29734. this._originalColorPostProcess = undefined;
  29735. this._ssaoPostProcess = undefined;
  29736. this._blurHPostProcess = undefined;
  29737. this._blurVPostProcess = undefined;
  29738. this._ssaoCombinePostProcess = undefined;
  29739. this._randomTexture.dispose();
  29740. if (disableDepthRender)
  29741. this._scene.disableDepthRenderer();
  29742. };
  29743. // Private Methods
  29744. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29745. var _this = this;
  29746. var sampleSphere = [
  29747. 0.5381,
  29748. 0.1856,
  29749. -0.4319,
  29750. 0.1379,
  29751. 0.2486,
  29752. 0.4430,
  29753. 0.3371,
  29754. 0.5679,
  29755. -0.0057,
  29756. -0.6999,
  29757. -0.0451,
  29758. -0.0019,
  29759. 0.0689,
  29760. -0.1598,
  29761. -0.8547,
  29762. 0.0560,
  29763. 0.0069,
  29764. -0.1843,
  29765. -0.0146,
  29766. 0.1402,
  29767. 0.0762,
  29768. 0.0100,
  29769. -0.1924,
  29770. -0.0344,
  29771. -0.3577,
  29772. -0.5301,
  29773. -0.4358,
  29774. -0.3169,
  29775. 0.1063,
  29776. 0.0158,
  29777. 0.0103,
  29778. -0.5869,
  29779. 0.0046,
  29780. -0.0897,
  29781. -0.4940,
  29782. 0.3287,
  29783. 0.7119,
  29784. -0.0154,
  29785. -0.0918,
  29786. -0.0533,
  29787. 0.0596,
  29788. -0.5411,
  29789. 0.0352,
  29790. -0.0631,
  29791. 0.5460,
  29792. -0.4776,
  29793. 0.2847,
  29794. -0.0271
  29795. ];
  29796. var samplesFactor = 1.0 / 16.0;
  29797. 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);
  29798. this._ssaoPostProcess.onApply = function (effect) {
  29799. if (_this._firstUpdate) {
  29800. effect.setArray3("sampleSphere", sampleSphere);
  29801. effect.setFloat("samplesFactor", samplesFactor);
  29802. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29803. _this._firstUpdate = false;
  29804. }
  29805. effect.setFloat("totalStrength", _this.totalStrength);
  29806. effect.setFloat("radius", _this.radius);
  29807. effect.setFloat("area", _this.area);
  29808. effect.setFloat("fallOff", _this.fallOff);
  29809. effect.setTexture("textureSampler", _this._depthTexture);
  29810. effect.setTexture("randomSampler", _this._randomTexture);
  29811. };
  29812. };
  29813. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29814. var _this = this;
  29815. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29816. this._ssaoCombinePostProcess.onApply = function (effect) {
  29817. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29818. };
  29819. };
  29820. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29821. var size = 512;
  29822. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29823. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29824. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29825. var context = this._randomTexture.getContext();
  29826. var rand = function (min, max) {
  29827. return Math.random() * (max - min) + min;
  29828. };
  29829. for (var x = 0; x < size; x++) {
  29830. for (var y = 0; y < size; y++) {
  29831. var randVector = BABYLON.Vector3.Zero();
  29832. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29833. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29834. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29835. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29836. context.fillRect(x, y, 1, 1);
  29837. }
  29838. }
  29839. this._randomTexture.update(false);
  29840. };
  29841. return SSAORenderingPipeline;
  29842. })(BABYLON.PostProcessRenderPipeline);
  29843. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29844. })(BABYLON || (BABYLON = {}));
  29845. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29846. var BABYLON;
  29847. (function (BABYLON) {
  29848. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29849. var VolumetricLightScatteringPostProcess = (function (_super) {
  29850. __extends(VolumetricLightScatteringPostProcess, _super);
  29851. /**
  29852. * @constructor
  29853. * @param {string} name - The post-process name
  29854. * @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)
  29855. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29856. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29857. * @param {number} samples - The post-process quality, default 100
  29858. * @param {number} samplingMode - The post-process filtering mode
  29859. * @param {BABYLON.Engine} engine - The babylon engine
  29860. * @param {boolean} reusable - If the post-process is reusable
  29861. */
  29862. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29863. var _this = this;
  29864. if (samples === void 0) { samples = 100; }
  29865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29866. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29867. this._screenCoordinates = BABYLON.Vector2.Zero();
  29868. /**
  29869. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29870. * @type {boolean}
  29871. */
  29872. this.useCustomMeshPosition = false;
  29873. /**
  29874. * If the post-process should inverse the light scattering direction
  29875. * @type {boolean}
  29876. */
  29877. this.invert = true;
  29878. /**
  29879. * Array containing the excluded meshes not rendered in the internal pass
  29880. */
  29881. this.excludedMeshes = new Array();
  29882. this.exposure = 0.3;
  29883. this.decay = 0.96815;
  29884. this.weight = 0.58767;
  29885. this.density = 0.926;
  29886. var scene = camera.getScene();
  29887. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29888. // Configure mesh
  29889. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29890. // Configure
  29891. this._createPass(scene, ratio.passRatio || ratio);
  29892. this.onApply = function (effect) {
  29893. _this._updateMeshScreenCoordinates(scene);
  29894. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29895. effect.setFloat("exposure", _this.exposure);
  29896. effect.setFloat("decay", _this.decay);
  29897. effect.setFloat("weight", _this.weight);
  29898. effect.setFloat("density", _this.density);
  29899. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29900. };
  29901. }
  29902. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29903. var mesh = subMesh.getMesh();
  29904. var defines = [];
  29905. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29906. var material = subMesh.getMaterial();
  29907. var needUV = false;
  29908. // Render this.mesh as default
  29909. if (mesh === this.mesh) {
  29910. defines.push("#define BASIC_RENDER");
  29911. defines.push("#define NEED_UV");
  29912. needUV = true;
  29913. }
  29914. // Alpha test
  29915. if (material) {
  29916. if (material.needAlphaTesting() || mesh === this.mesh)
  29917. defines.push("#define ALPHATEST");
  29918. if (material.opacityTexture !== undefined) {
  29919. defines.push("#define OPACITY");
  29920. if (material.opacityTexture.getAlphaFromRGB)
  29921. defines.push("#define OPACITYRGB");
  29922. if (!needUV)
  29923. defines.push("#define NEED_UV");
  29924. }
  29925. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29926. attribs.push(BABYLON.VertexBuffer.UVKind);
  29927. defines.push("#define UV1");
  29928. }
  29929. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29930. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29931. defines.push("#define UV2");
  29932. }
  29933. }
  29934. // Bones
  29935. if (mesh.useBones) {
  29936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29938. defines.push("#define BONES");
  29939. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29940. }
  29941. // Instances
  29942. if (useInstances) {
  29943. defines.push("#define INSTANCES");
  29944. attribs.push("world0");
  29945. attribs.push("world1");
  29946. attribs.push("world2");
  29947. attribs.push("world3");
  29948. }
  29949. // Get correct effect
  29950. var join = defines.join("\n");
  29951. if (this._cachedDefines !== join) {
  29952. this._cachedDefines = join;
  29953. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29954. }
  29955. return this._volumetricLightScatteringPass.isReady();
  29956. };
  29957. /**
  29958. * Sets the new light position for light scattering effect
  29959. * @param {BABYLON.Vector3} The new custom light position
  29960. */
  29961. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29962. this._customMeshPosition = position;
  29963. };
  29964. /**
  29965. * Returns the light position for light scattering effect
  29966. * @return {BABYLON.Vector3} The custom light position
  29967. */
  29968. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29969. return this._customMeshPosition;
  29970. };
  29971. /**
  29972. * Disposes the internal assets and detaches the post-process from the camera
  29973. */
  29974. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29975. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29976. if (rttIndex !== -1) {
  29977. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29978. }
  29979. this._volumetricLightScatteringRTT.dispose();
  29980. _super.prototype.dispose.call(this, camera);
  29981. };
  29982. /**
  29983. * Returns the render target texture used by the post-process
  29984. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29985. */
  29986. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29987. return this._volumetricLightScatteringRTT;
  29988. };
  29989. // Private methods
  29990. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29991. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29992. return true;
  29993. }
  29994. return false;
  29995. };
  29996. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29997. var _this = this;
  29998. var engine = scene.getEngine();
  29999. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  30000. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30001. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30002. this._volumetricLightScatteringRTT.renderList = null;
  30003. this._volumetricLightScatteringRTT.renderParticles = false;
  30004. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  30005. // Custom render function for submeshes
  30006. var renderSubMesh = function (subMesh) {
  30007. var mesh = subMesh.getRenderingMesh();
  30008. if (_this._meshExcluded(mesh)) {
  30009. return;
  30010. }
  30011. var scene = mesh.getScene();
  30012. var engine = scene.getEngine();
  30013. // Culling
  30014. engine.setState(subMesh.getMaterial().backFaceCulling);
  30015. // Managing instances
  30016. var batch = mesh._getInstancesRenderList(subMesh._id);
  30017. if (batch.mustReturn) {
  30018. return;
  30019. }
  30020. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30021. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30022. engine.enableEffect(_this._volumetricLightScatteringPass);
  30023. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  30024. var material = subMesh.getMaterial();
  30025. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  30026. // Alpha test
  30027. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  30028. var alphaTexture = material.getAlphaTestTexture();
  30029. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  30030. if (alphaTexture) {
  30031. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30032. }
  30033. if (material.opacityTexture !== undefined) {
  30034. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  30035. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  30036. }
  30037. }
  30038. // Bones
  30039. if (mesh.useBones) {
  30040. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30041. }
  30042. // Draw
  30043. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  30044. }
  30045. };
  30046. // Render target texture callbacks
  30047. var savedSceneClearColor;
  30048. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  30049. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  30050. savedSceneClearColor = scene.clearColor;
  30051. scene.clearColor = sceneClearColor;
  30052. };
  30053. this._volumetricLightScatteringRTT.onAfterRender = function () {
  30054. scene.clearColor = savedSceneClearColor;
  30055. };
  30056. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  30057. var engine = scene.getEngine();
  30058. var index;
  30059. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30060. renderSubMesh(opaqueSubMeshes.data[index]);
  30061. }
  30062. engine.setAlphaTesting(true);
  30063. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30064. renderSubMesh(alphaTestSubMeshes.data[index]);
  30065. }
  30066. engine.setAlphaTesting(false);
  30067. if (transparentSubMeshes.length) {
  30068. for (index = 0; index < transparentSubMeshes.length; index++) {
  30069. var submesh = transparentSubMeshes.data[index];
  30070. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30071. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30072. }
  30073. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30074. sortedArray.sort(function (a, b) {
  30075. // Alpha index first
  30076. if (a._alphaIndex > b._alphaIndex) {
  30077. return 1;
  30078. }
  30079. if (a._alphaIndex < b._alphaIndex) {
  30080. return -1;
  30081. }
  30082. // Then distance to camera
  30083. if (a._distanceToCamera < b._distanceToCamera) {
  30084. return 1;
  30085. }
  30086. if (a._distanceToCamera > b._distanceToCamera) {
  30087. return -1;
  30088. }
  30089. return 0;
  30090. });
  30091. // Render sub meshes
  30092. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30093. for (index = 0; index < sortedArray.length; index++) {
  30094. renderSubMesh(sortedArray[index]);
  30095. }
  30096. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30097. }
  30098. };
  30099. };
  30100. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30101. var transform = scene.getTransformMatrix();
  30102. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30103. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30104. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30105. if (this.invert)
  30106. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30107. };
  30108. // Static methods
  30109. /**
  30110. * Creates a default mesh for the Volumeric Light Scattering post-process
  30111. * @param {string} The mesh name
  30112. * @param {BABYLON.Scene} The scene where to create the mesh
  30113. * @return {BABYLON.Mesh} the default mesh
  30114. */
  30115. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30116. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30117. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30118. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30119. return mesh;
  30120. };
  30121. return VolumetricLightScatteringPostProcess;
  30122. })(BABYLON.PostProcess);
  30123. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30124. })(BABYLON || (BABYLON = {}));
  30125. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30126. var BABYLON;
  30127. (function (BABYLON) {
  30128. var LensRenderingPipeline = (function (_super) {
  30129. __extends(LensRenderingPipeline, _super);
  30130. /**
  30131. * @constructor
  30132. *
  30133. * Effect parameters are as follow:
  30134. * {
  30135. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30136. * edge_blur: number; // from 0 to x (1 for realism)
  30137. * distortion: number; // from 0 to x (1 for realism)
  30138. * grain_amount: number; // from 0 to 1
  30139. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30140. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30141. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30142. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30143. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30144. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30145. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30146. * }
  30147. * Note: if an effect parameter is unset, effect is disabled
  30148. *
  30149. * @param {string} name - The rendering pipeline name
  30150. * @param {object} parameters - An object containing all parameters (see above)
  30151. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30152. * @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)
  30153. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30154. */
  30155. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30156. var _this = this;
  30157. if (ratio === void 0) { ratio = 1.0; }
  30158. _super.call(this, scene.getEngine(), name);
  30159. // Lens effects can be of the following:
  30160. // - chromatic aberration (slight shift of RGB colors)
  30161. // - blur on the edge of the lens
  30162. // - lens distortion
  30163. // - depth-of-field blur & highlights enhancing
  30164. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30165. // - grain effect (noise or custom texture)
  30166. // Two additional texture samplers are needed:
  30167. // - depth map (for depth-of-field)
  30168. // - grain texture
  30169. /**
  30170. * The chromatic aberration PostProcess id in the pipeline
  30171. * @type {string}
  30172. */
  30173. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30174. /**
  30175. * The highlights enhancing PostProcess id in the pipeline
  30176. * @type {string}
  30177. */
  30178. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30179. /**
  30180. * The depth-of-field PostProcess id in the pipeline
  30181. * @type {string}
  30182. */
  30183. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30184. this._scene = scene;
  30185. // Fetch texture samplers
  30186. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30187. if (parameters.grain_texture) {
  30188. this._grainTexture = parameters.grain_texture;
  30189. }
  30190. else {
  30191. this._createGrainTexture();
  30192. }
  30193. // save parameters
  30194. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30195. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30196. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30197. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30198. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30199. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30200. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30201. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30202. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30203. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30204. // Create effects
  30205. this._createChromaticAberrationPostProcess(ratio);
  30206. this._createHighlightsPostProcess(ratio);
  30207. this._createDepthOfFieldPostProcess(ratio);
  30208. // Set up pipeline
  30209. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30210. return _this._chromaticAberrationPostProcess;
  30211. }, true));
  30212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30213. return _this._highlightsPostProcess;
  30214. }, true));
  30215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30216. return _this._depthOfFieldPostProcess;
  30217. }, true));
  30218. if (this._highlightsGain == -1) {
  30219. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30220. }
  30221. // Finish
  30222. scene.postProcessRenderPipelineManager.addPipeline(this);
  30223. if (cameras) {
  30224. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30225. }
  30226. }
  30227. // public methods (self explanatory)
  30228. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30229. this._edgeBlur = amount;
  30230. };
  30231. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30232. this._edgeBlur = 0;
  30233. };
  30234. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30235. this._grainAmount = amount;
  30236. };
  30237. LensRenderingPipeline.prototype.disableGrain = function () {
  30238. this._grainAmount = 0;
  30239. };
  30240. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30241. this._chromaticAberration = amount;
  30242. };
  30243. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30244. this._chromaticAberration = 0;
  30245. };
  30246. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30247. this._distortion = amount;
  30248. };
  30249. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30250. this._distortion = 0;
  30251. };
  30252. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30253. this._dofDepth = amount;
  30254. };
  30255. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30256. this._dofDepth = -1;
  30257. };
  30258. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30259. this._dofAperture = amount;
  30260. };
  30261. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30262. this._dofPentagon = true;
  30263. };
  30264. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30265. this._dofPentagon = false;
  30266. };
  30267. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30268. this._blurNoise = true;
  30269. };
  30270. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30271. this._blurNoise = false;
  30272. };
  30273. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30274. this._highlightsGain = amount;
  30275. };
  30276. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30277. if (this._highlightsGain == -1) {
  30278. this._highlightsGain = 1.0;
  30279. }
  30280. this._highlightsThreshold = amount;
  30281. };
  30282. LensRenderingPipeline.prototype.disableHighlights = function () {
  30283. this._highlightsGain = -1;
  30284. };
  30285. /**
  30286. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30287. */
  30288. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30289. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30290. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30291. this._chromaticAberrationPostProcess = undefined;
  30292. this._highlightsPostProcess = undefined;
  30293. this._depthOfFieldPostProcess = undefined;
  30294. this._grainTexture.dispose();
  30295. if (disableDepthRender)
  30296. this._scene.disableDepthRenderer();
  30297. };
  30298. // colors shifting and distortion
  30299. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30300. var _this = this;
  30301. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30302. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30303. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30304. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30305. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30306. };
  30307. };
  30308. // highlights enhancing
  30309. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30310. var _this = this;
  30311. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30312. this._highlightsPostProcess.onApply = function (effect) {
  30313. effect.setFloat('gain', _this._highlightsGain);
  30314. effect.setFloat('threshold', _this._highlightsThreshold);
  30315. effect.setBool('pentagon', _this._dofPentagon);
  30316. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30317. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30318. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30319. };
  30320. };
  30321. // colors shifting and distortion
  30322. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30323. var _this = this;
  30324. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30325. "focus_depth",
  30326. "aperture",
  30327. "pentagon",
  30328. "maxZ",
  30329. "edge_blur",
  30330. "chromatic_aberration",
  30331. "distortion",
  30332. "blur_noise",
  30333. "grain_amount",
  30334. "screen_width",
  30335. "screen_height",
  30336. "highlights"
  30337. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30338. this._depthOfFieldPostProcess.onApply = function (effect) {
  30339. effect.setBool('blur_noise', _this._blurNoise);
  30340. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30341. effect.setFloat('grain_amount', _this._grainAmount);
  30342. effect.setTexture("depthSampler", _this._depthTexture);
  30343. effect.setTexture("grainSampler", _this._grainTexture);
  30344. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30345. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30346. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30347. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30348. effect.setFloat('distortion', _this._distortion);
  30349. effect.setFloat('focus_depth', _this._dofDepth);
  30350. effect.setFloat('aperture', _this._dofAperture);
  30351. effect.setFloat('edge_blur', _this._edgeBlur);
  30352. effect.setBool('highlights', (_this._highlightsGain != -1));
  30353. };
  30354. };
  30355. // creates a black and white random noise texture, 512x512
  30356. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30357. var size = 512;
  30358. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30359. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30360. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30361. var context = this._grainTexture.getContext();
  30362. var rand = function (min, max) {
  30363. return Math.random() * (max - min) + min;
  30364. };
  30365. var value;
  30366. for (var x = 0; x < size; x++) {
  30367. for (var y = 0; y < size; y++) {
  30368. value = Math.floor(rand(0.42, 0.58) * 255);
  30369. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30370. context.fillRect(x, y, 1, 1);
  30371. }
  30372. }
  30373. this._grainTexture.update(false);
  30374. };
  30375. return LensRenderingPipeline;
  30376. })(BABYLON.PostProcessRenderPipeline);
  30377. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30378. })(BABYLON || (BABYLON = {}));
  30379. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30380. // This post-process allows the modification of rendered colors by using
  30381. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30382. //
  30383. // The object needs to be provided an url to a texture containing the color
  30384. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30385. // Use an image editing software to tweak the LUT to match your needs.
  30386. //
  30387. // For an example of a color LUT, see here:
  30388. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30389. // For explanations on color grading, see here:
  30390. // http://udn.epicgames.com/Three/ColorGrading.html
  30391. //
  30392. var BABYLON;
  30393. (function (BABYLON) {
  30394. var ColorCorrectionPostProcess = (function (_super) {
  30395. __extends(ColorCorrectionPostProcess, _super);
  30396. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30397. var _this = this;
  30398. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30399. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30400. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30401. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30402. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30403. this.onApply = function (effect) {
  30404. effect.setTexture("colorTable", _this._colorTableTexture);
  30405. };
  30406. }
  30407. return ColorCorrectionPostProcess;
  30408. })(BABYLON.PostProcess);
  30409. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30410. })(BABYLON || (BABYLON = {}));
  30411. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30412. (function (BABYLON) {
  30413. var SmartCollection = (function () {
  30414. function SmartCollection(capacity) {
  30415. if (capacity === void 0) { capacity = 10; }
  30416. this.count = 0;
  30417. this._initialCapacity = capacity;
  30418. this.items = {};
  30419. this._keys = new Array(this._initialCapacity);
  30420. }
  30421. SmartCollection.prototype.add = function (key, item) {
  30422. if (this.items[key] != undefined) {
  30423. return -1;
  30424. }
  30425. this.items[key] = item;
  30426. //literal keys are always strings, but we keep source type of key in _keys array
  30427. this._keys[this.count++] = key;
  30428. if (this.count > this._keys.length) {
  30429. this._keys.length *= 2;
  30430. }
  30431. return this.count;
  30432. };
  30433. SmartCollection.prototype.remove = function (key) {
  30434. if (this.items[key] == undefined) {
  30435. return -1;
  30436. }
  30437. return this.removeItemOfIndex(this.indexOf(key));
  30438. };
  30439. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30440. if (index < this.count && index > -1) {
  30441. delete this.items[this._keys[index]];
  30442. while (index < this.count) {
  30443. this._keys[index] = this._keys[index + 1];
  30444. index++;
  30445. }
  30446. }
  30447. else {
  30448. return -1;
  30449. }
  30450. return --this.count;
  30451. };
  30452. SmartCollection.prototype.indexOf = function (key) {
  30453. for (var i = 0; i !== this.count; i++) {
  30454. if (this._keys[i] === key) {
  30455. return i;
  30456. }
  30457. }
  30458. return -1;
  30459. };
  30460. SmartCollection.prototype.item = function (key) {
  30461. return this.items[key];
  30462. };
  30463. SmartCollection.prototype.getAllKeys = function () {
  30464. if (this.count > 0) {
  30465. var keys = new Array(this.count);
  30466. for (var i = 0; i < this.count; i++) {
  30467. keys[i] = this._keys[i];
  30468. }
  30469. return keys;
  30470. }
  30471. else {
  30472. return undefined;
  30473. }
  30474. };
  30475. SmartCollection.prototype.getKeyByIndex = function (index) {
  30476. if (index < this.count && index > -1) {
  30477. return this._keys[index];
  30478. }
  30479. else {
  30480. return undefined;
  30481. }
  30482. };
  30483. SmartCollection.prototype.getItemByIndex = function (index) {
  30484. if (index < this.count && index > -1) {
  30485. return this.items[this._keys[index]];
  30486. }
  30487. else {
  30488. return undefined;
  30489. }
  30490. };
  30491. SmartCollection.prototype.empty = function () {
  30492. if (this.count > 0) {
  30493. this.count = 0;
  30494. this.items = {};
  30495. this._keys = new Array(this._initialCapacity);
  30496. }
  30497. };
  30498. SmartCollection.prototype.forEach = function (block) {
  30499. var key;
  30500. for (key in this.items) {
  30501. if (this.items.hasOwnProperty(key)) {
  30502. block(this.items[key]);
  30503. }
  30504. }
  30505. };
  30506. return SmartCollection;
  30507. })();
  30508. BABYLON.SmartCollection = SmartCollection;
  30509. })(BABYLON || (BABYLON = {}));
  30510. //# sourceMappingURL=babylon.smartCollection.js.map